text:
Q: Deploying via Capistrano through Jenkins - SSH authentication failed I've got a Jenkins build that runs a Capistrano deploy as a post-build action.
Running the Capistrano task as the Jenkins user from the console works absolutely fine and without a password prompt (I've previously set up SSH keys on both build and staging server). However, when running the same script through Jenkins, I suddenly get a password prompt and the build subsequently fails (no TTY present).
[workspace] $ /bin/sh -xe /tmp/hudson7321493219694918714.sh
Performing Post build task...
Match found for : : True
Logical operation result is TRUE
Running script  : cap _2.13.4_ deploy
[workspace] $ /bin/sh -xe /tmp/hudson1545664641721322948.sh
+ cap _2.13.4_ deploy
  * executing `deploy'
  * executing `deploy:update'
 ** transaction: start
  * executing `deploy:update_code'
    triggering before callbacks for `deploy:update_code'
[32m--> Updating code base with checkout strategy[0m
    executing locally: "git ls-remote git@my.staging-server.com:my_project.git master"
    command finished in 1200ms
  * executing "git clone -q git@my.staging-server.com:my_project.git /var/www/staging/my_project/releases/20121029223619 && cd /var/www/staging/my_project/releases/20121029223619 && git checkout -q -b deploy 1fb11d669a6cb5a714d077162305dfcfaba82f01 && (echo 1fb11d669a6cb5a714d077162305dfcfaba82f01 > /var/www/staging/my_project/releases/20121029223619/REVISION)"
servers: ["my.staging-server.com"]
Password: stty: standard input: Inappropriate ioctl for device
stty: standard input: Inappropriate ioctl for device
stty: standard input: Inappropriate ioctl for device

*** [deploy:update_code] rolling back
  * executing "rm -rf /var/www/staging/my_project/releases/20121029223619; true"
    servers: ["my.staging-server.com"]
 ** [deploy:update_code] exception while rolling back: Capistrano::ConnectionError, connection failed for: my.staging-server.com (Net::SSH::AuthenticationFailed: not-specified)
connection failed for: my.staging-server.com (Net::SSH::AuthenticationFailed: not-specified)
POST BUILD TASK : FAILURE

It looks like Ruby doesn't pick my SSH key up when running through Jenkins perhaps (Net::SSH::AuthenticationFailed: not-specified)?
Does anyone have an idea what might be going wrong here?

A: We ran into something similar to this. It's possible that the login shell for jenkins already has an ssh agent running automatically, but the context that jenkins spawns for your deployment does not.
Try starting one manually within your jenkins script:
# Start the ssh agent. Evaling the output will set the relevant environment
# variables
eval `ssh-agent`

# Add the default keys like id_rsa and id_dsa (or explicitly specify your key,
# if it's not a default)
ssh-add

# Your normal deploy script here

# Save the return value of your script
RETVAL=$?

# Clean up
kill $SSH_AGENT_PID

# Exit the script with the true return value instead of the return value of kill
# which could be successful even when the capistrano portion of the build has
# crashed
exit $RETVAL

Hope this works for you! Shells are annoying.

A: Unfortunately I resolved it only by replacing original deploy.rb before executing cap deploy with another one saved locally where I added set :password, "sshpassword"


text:
Q: query on date column I have a column (completeddate) that I need to do the following
select *
from orders
where completeddate > '01-01-2013'

The problem is the date in the field looks like this (below)
25-FEB-08 12.00.00.000000000 AM

The format of the column is this
TIMESTAMP(6)

How do I set up my query to return rows where the completeddate is greater than 01-01-2013

A: You haven't specified the DBMS you are using, but nearly all of them store dates as a number. The format that you are seeing is almost certainly the client's interpretation of the date and has nothing to do with how the date is actually stored.
Most DBMSes are able to translate standard string representations of dates into a numeric date value. The likely problem is that you aren't using a standard date format. You should either use '2013-01-01' or '01/01/2013'. In my experience, YYYY-MM-DD (ISO 8601 and RFC 3339) is the least ambiguious and most supported format. If you strongly prefer MM/DD/YYYY (a primarily North American representation) then you usually need to use backslashes.

A: Try this
select *
from orders
where completeddate > CONVERT(DATETIME, '01-01-2013', 105)

105 for dd-MM-yyy

A: You need to convert the string '01-01-2013' to a database date object before the comparison. Don't know what is the type of your database, but all databases shall provide a function for converting date objects to and from strings, you can have something like:
where completeddate > TO_DATE('01-01-2013', 'DD-MM-YYYY')

Hope this helps.

A: did you try this?
SELECT CAST(your_timestamp_field AS DATETIME) FROM orders WHERE completeddate > '2013-01-01'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Data Type Conversion Error while trying to dynamically add columns(fields) from excel in MS-Access database using Python I'm trying to populate the 1st row(i.e. the column names) from an excel sheet to the ms-access database, but it's giving me 'Data type conversion Error(3421)'. Any idea why this is happening ?
from comtypes.client import CreateObject
from xlrd import open_workbook,cellname
import os
from comtypes.gen import Access

access = CreateObject('Access.Application')

DBEngine = access.DBEngine

db = DBEngine.CreateDatabase('test.mdb', Access.DB_LANG_GENERAL)

excel_file = open_workbook('test_excel_file.xlsx')
work_sheet = excel_file.sheet_by_index(0)

db.BeginTrans()
db.Execute("CREATE TABLE MY_TABLE (ID Text)")

for row_index in range(0, 1):
    for col_index in range(0, work_sheet.ncols):
        cell_value = work_sheet.cell(row_index,col_index).value
        db.Execute("ALTER TABLE MY_TABLE ADD COLUMN %s", cell_value)

db.CommitTrans()
db.Close()

Error:
Traceback (most recent call last):
File "My_DB_Code.py", line 21, in <module>
db.Execute("ALTER TABLE MY_TABLE ADD COLUMN %s", cell_value)
_ctypes.COMError: (-2146824867, None, (u'Data type conversion error.', u'DAO.Dat
abase', u'jeterr40.chm', 5003421, None))

A: A parameterized query allows parameters to be substituted for the values of a column, but not for table and column names themselves. You will need to use string formatting for that, as in
db.Execute("ALTER TABLE MY_TABLE ADD COLUMN [{0}] TEXT(50)".format(cell_value))


text:
Q: Parameter 'action' should have type assignable to 'Object' when trying to make Redux work with Typescript I'm trying to make redux work in my Typescript app right now, it actually seems to work but typescript seems to have some typing issues with it.
This is what comes up:

And this is my reducer code:
import { PopUpNotification } from "definitions/PopUpNotificationDefinitions";

interface IPopUpNotificationReducerState {
    popUpNotifications: Array<PopUpNotification>;
}

const initialState: IPopUpNotificationReducerState = {
    popUpNotifications: []
}

enum PopUpNotificationActions {
    ADD = "POPUPNOTIFICATION_ADD",
    DELETE = "POPUPNOTIFICATION_DELETE"
}

export interface AddPopUpNotification {
    type: PopUpNotificationActions,
    popUpNotification: PopUpNotification,
}

export interface DeletePopUpNotification {
    type: PopUpNotificationActions,
    popUpNotification: PopUpNotification,
}

export type PopUpNotificationAction = AddPopUpNotification | DeletePopUpNotification;

export function addPopUpNotification(popUpNotification: PopUpNotification): AddPopUpNotification {
    const addPopUpNotification: DeletePopUpNotification = {
        type: PopUpNotificationActions.ADD,
        popUpNotification: popUpNotification
    };

    return addPopUpNotification;
}

export function deletePopUpNotification(popUpNotification: PopUpNotification): DeletePopUpNotification {
    const deletePopUpNotification: DeletePopUpNotification = {
        type: PopUpNotificationActions.DELETE,
        popUpNotification: popUpNotification
    };

    return deletePopUpNotification;
}

export function popUpNotificationReducer(state = initialState, action: PopUpNotificationAction): IPopUpNotificationReducerState {

    switch (action.type) {
        case PopUpNotificationActions.ADD:
        return {
            popUpNotifications: [...state.popUpNotifications, action.popUpNotification]
        };
        case PopUpNotificationActions.DELETE:
        return {
            popUpNotifications: state.popUpNotifications.filter(notification => notification.Id !== action.popUpNotification.Id)
        }
    default:
        return initialState;
    }
}

I tried to follow the tutorial on the redux page as good as possible with small adaptions to my case here.
So, any hints as to where I am going wrong right now?

A: You may look at working example of simple app that is shipped with Visual Studio 2017 Community edition. Example is based on TypeScript, Redux and React. So you'll have examples of actions, reducer etc.
To deploy example use Visual Studio 2017 Community -> New Project -> Visual C# -> .NET Core -> ASP.NET Core Web App -> In upper menu choose .NET Core 2.0 (this is important, as .NET Core 2.1+ templates are based on JavaScript) -> React.js and Redux -> and you'll have fully working typescript app with React and Redux


text:
Q: Stop update the Arp table I have a trouble in my network. Somebody in our network runs a sniffer. He gets all data packets. Actually he is a friend of mine. So what I want do is to only stop update my ARP table. like When he is sniffing, all the ARP tables of all machines always update. Does anybody know to stop this?
Thank you.

A: Actually this is the "ARP Vulnerability" problem. The person in your network uses the mechanism on MITM (Man in the Middle) attack to create a route so that the packets that u receive/send is intercepted by him, thus enabling it to sniff your packets. As far as I know this vulnerability has not been resolved because the ARP protocol is "trusting" , which means it does not validate ip-mac pair. Only way to stop is get him off the LAN :)

A: I don't quite understand your question. When he's sniffing, there should be no change on the ARP table of your machine.
Is he sniffing (reading packets as they go through the network), or is he scanning (sending probes and/or strange packets to other machines)?


text:
Q: PHP: Fatal error after a form POST The following code throws an error in PHP 5.2.9 after submission, but not on the original load.
Error: Fatal error: Only variables can be passed by reference in /home/golfcom/public_html/test.php on line 12
File:
<?php
include('connection.php');
$result = $dbc->query("SELECT subdivision FROM Residential");
$search['subdivision'] = array();

while($i = $result->fetch_array()){
    echo $i['subdivision'];
    array_push($search['subdivision'], $y = $i['subdivision']);
}
?>
<form action="test.php" method="post">
<input type='submit' value='search' class='submit' name='search' /></form>

A: Just a guess, but maybe it has something to do with the assignment operation inside the function:
array_push($search['subdivision'], $y = $i['subdivision']);

Try this instead:
$y = $i['subdivision'];
array_push($search['subdivision'], $y);

A: Figured it out.  My host had register_globals on.  Turning if off fixed everything.

A: Ignore this question, I'm getting inconsistent results.  I think my host is wonky.

A: You have no error control. You need to check the following:

*

*your database connection is OK and connected

*the query did not error and returned a valid result (even if there are no rows)

*dont try to print a row if there was none returned by the query

In your loop, $y will be the value of the LAST row and is set every loop. While its not incorrect, you can change your code to something like:
$t = $result->numRows();
while ($row = $result->fetch_array()) {
    $search['subdivision'][] = $row['subdivision'];
}
$lastResult = $search['subdivision'][$t - 1];


text:
Q: By what principle does the AirTag work? I hope to understand it so that I can also tell whether the following situations work:
First of all, does an AirTag talk to any unencrypted Wifi or cellular tower, or random people who walk by and have the BlueTooth turned on?
So by understanding what principles it works by, then I hope to know whether the following situations can work:

*

*If I want the AirTag to be able to tell where my car is parked, or where that AppleTV remote control (with the AirTag attached) is, and I had an iPhone near me all the time.

*If I leave an AirTag in my car's cup holder, and yesterday night, I parked my car 2 streets way, and I didn't have my iPhone with me, so today, can I use my iPhone to find my car? What if the car is more than 200 or 500 feet away?

*What if the AirTag is attached to a Belkin string attachment and is taped to the back of the Apple TV remote control. Then if the remote is dropped under the bed and is out of battery, can the AirTag still tell where it is when the battery has run out of power?

*What if our cat or dog took the key and the AirTag, and bury it somewhere in the backyard or in a park nearby?  So all this time, there was no iPhone nearby (assuming I am not at home).

A: No, AirTags do not communicate over WiFi (unencrypted or encrypted), nor does it communicate with cell towers. It does communicate over Bluetooth and UWB, and the signals it emit can be received by random people walking by, if they're within range.
Your situations:

*

*Yes, AirTags can help you pinpoint the location of your AppleTV remote with an AirTag attached to you. It is best at doing so if you have a newer iPhone (11+). For your car it depends on how big the parking lot is, and how often other people will walk around the parking lot near your car.

*Yes, you can come back the next day to locate your AirTag even though you didn't have the phone with you when you left the AirTag. If the AirTag is so far from you that you cannot receive its signals, you must rely on some other iPhone user being sufficiently near the AirTag at some point.

*Your question is a bit ambigious. The use of the Belkin string attachment has no impact on whether or not you can find the AirTag. If you mean that the AppleTV remote has run out of battery, that again has no impact on whether or not you can find the AirTag. If the AirTag itself has run out of power, then you cannot use the very precise location method that shows you the angle and distance to the AirTag. It is possible to see the last known location of the AirTag on a map even when out of battery. Note that AirTags have a fairly long battery life.

*This depends on how deep the AirTag is buried and what kind of material is on top of it. The AirTag does not know it is buried - it will still emit its signals, and if there's a receiver (i.e. someone with an iPhone) in range, you can get notified about the position of the lost AirTag.


text:
Q: Spring WebFlux (Flux): how to publish dynamically I am new to Reactive programming and Spring WebFlux. I want to make my App 1 publish Server Sent event through Flux and my App 2 listen on it continuously.
I want Flux publish on-demand (e.g. when something happens). All the example I found is to use Flux.interval to periodically publish event, and there seems no way to append/modify the content in Flux once it is created.
How can I achieve my goal? Or I am totally wrong conceptually.

A: Publish "dynamically" using FluxProcessor and FluxSink
One of the techniques to supply data manually to the Flux is using FluxProcessor#sink method as in the following example
@SpringBootApplication
@RestController
public class DemoApplication {

    final FluxProcessor processor;
    final FluxSink sink;
    final AtomicLong counter;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);

    }

    public DemoApplication() {
        this.processor = DirectProcessor.create().serialize();
        this.sink = processor.sink();
        this.counter = new AtomicLong();
    }

    @GetMapping("/send")
    public void test() {
        sink.next("Hello World #" + counter.getAndIncrement());
    }

    @RequestMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent> sse() {
        return processor.map(e -> ServerSentEvent.builder(e).build());
    }
}

Here, I created DirectProcessor in order to support multiple subscribers, that will listen to the data stream. Also, I provided additional FluxProcessor#serialize which provide safe support for multiproducer (invocation from different threads without violation of Reactive Streams spec rules, especially rule 1.3). Finally, by calling "http://localhost:8080/send" we will see the message Hello World #1 (of course, only in case if you connected to the "http://localhost:8080" previously)
Update For Reactor 3.4
With Reactor 3.4 you have a new API called reactor.core.publisher.Sinks. Sinks API offers a fluent builder for manual data-sending which lets you specify things like the number of elements in the stream and backpressure behavior, number of supported subscribers, and replay capabilities:
@SpringBootApplication
@RestController
public class DemoApplication {

    final Sinks.Many sink;
    final AtomicLong counter;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);

    }

    public DemoApplication() {
        this.sink = Sinks.many().multicast().onBackpressureBuffer();
        this.counter = new AtomicLong();
    }

    @GetMapping("/send")
    public void test() {
        EmitResult result = sink.tryEmitNext("Hello World #" + counter.getAndIncrement());

        if (result.isFailure()) {
          // do something here, since emission failed
        }
    }

    @RequestMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent> sse() {
        return sink.asFlux().map(e -> ServerSentEvent.builder(e).build());
    }
}

Note, message sending via Sinks API introduces a new concept of emission and its result. The reason for such API is the fact that the Reactor extends Reactive-Streams and has to follow the backpressure control. That said if you emit more signals than was requested, and the underlying implementation does not support buffering, your message will not be delivered. Therefore, the result of tryEmitNext returns the EmitResult which indicates if the message was sent or not.
Also, note, that by default Sinsk API gives a serialized version of Sink, which means you don't have to care about concurrency. However, if you know in advance that the emission of the message is serial, you may build a Sinks.unsafe() version which does not serialize given messages

A: Just another idea, using EmitterProcessor as a gateway to flux
    import reactor.core.publisher.EmitterProcessor;
    import reactor.core.publisher.Flux;

    public class MyEmitterProcessor {
        EmitterProcessor<String> emitterProcessor;

        public static void main(String args[]) {

            MyEmitterProcessor myEmitterProcessor = new MyEmitterProcessor();
            Flux<String> publisher = myEmitterProcessor.getPublisher();
            myEmitterProcessor.onNext("A");
            myEmitterProcessor.onNext("B");
            myEmitterProcessor.onNext("C");
            myEmitterProcessor.complete();

            publisher.subscribe(x -> System.out.println(x));

        }

        public Flux<String> getPublisher() {
            emitterProcessor = EmitterProcessor.create();
            return emitterProcessor.map(x -> "consume: " + x);
        }

        public  void onNext(String nextString) {
            emitterProcessor.onNext(nextString);
        }

        public  void complete() {
            emitterProcessor.onComplete();
        }
    }

More info, see here from Reactor doc. There is a recommendation from the document itself that "Most of the time, you should try to avoid using a Processor. They are harder to use correctly and prone to some corner cases." BUT I don't know which kind of corner case.


text:
Q: The Golay-Rudin-Shapiro sequence as "Hankel transform" Let ${\left( {{a_n}} \right)_{n \geqslant 0}}$ be a sequence of real numbers and  ${H_n} = \det \left( {{a_{i + j}}} \right)_{i,j = 0}^{n - 1}$ the $n-$th Hankel determinant. The sequence  ${\left( {{H_n}} \right)_{n \geqslant 0}}$ is sometimes called the "Hankel transform" of  ${\left( {{a_n}} \right)_{n \geqslant 0}}.$
Is the following result known?
Let $a_0=1$, $a_{2^k-2}=(-1)^k$ for $k\ge2$ and $a_n=0$ else.
Then
$${\det \left( {{a_{i + j}}} \right)_{i,j = 0}^{n - 1}=r(n)}$$
where ${\left( {{r(n)}} \right)_{n \geqslant 0}}$ is the Golay-Rudin-Shapiro sequence defined by
$$\begin{gathered}
  r(2n) = r(n), \hfill \\
  r(2n + 1) = {( - 1)^n}r(n), \hfill \\
  r(0) = 1. \hfill \\
\end{gathered} $$

A: Here is an attempt at analyzing this problem. It seems better to adjust the index of the sequence, so let $\;A_n = b_k \mbox{ if } n=2^k,\; 0\;$ otherwise. Let $\;c_n\; := \det \left( {{A_{i + j}}} \right)_{i,j = 1}^n.\;$ In this determinant as a sum over all permutations, only one permutation in the sum corresponds to a nonzero product of members of the sequence $\{b_k\}.\;$ That is, $c_n = \textrm{sgn}(\sigma(n))\prod_{i=1}^k A_{i+\sigma(n)_i}\;$ where  $\;\sigma(n)\;$ is a permutation of $\;\{1,\dots,n\}.\;$ The triangluar array of $\;\{\sigma(n)\}_1^\infty\;$ has a peculiar recursive structure of triangular arrays next to other smaller triangular arrays. In our case, $\;b_1=1,\; b_k=(-1)^k,\;$ for $k>1.\;$ If we know the signature of all $\;\sigma(n),\;$ then the problem is essentially solved.


text:
Q: Document describing Lua 5.2 implementation? Lua.org has a very nice document which describes implementation strategies and novelties of Lua 5.0.
In Lua 5.2 we can add a serious incremental garbage collector and a goto statement to the Lua 5.0 feature list. I would really like to read about how they implemented them (without digging too much in the source).
So, is there a document like the one for 5.0 available for 5.2 somewhere?

A: There is a presentation about Lua 5.2 novelties by Roberto Ierusalimschy. Although it does not give details about garbage collection, there is a slide describing the implementation of goto (slide 17).
If you need more details, I guess you will need to take a look at the source (it's actually pretty readable).

A: Lua 5.1 introduced incremental garbage collection.
Lua 5.2 introduced generational garbage collection as an experimental feature.
But, no, there is no document on this implementation.


text:
Q: What are the best practices for determining the tasks of Constructor, Initialization and Reset methods This is a general OOP question although I am designing in Java. I'm not trying to solve a particular problem, just to think through some design principles.
From my experience I have reached the habit segregating object setup into three phases.
The goal is to minimize: extra work, obfuscated code and crippled extensibility.
Construction

*

*The minimal actions necessary to
create a valid Object, passes an
existence test

*Instantiate and initialize only "one time", never to be over-ridden, non variable objects that will not change/vary for the life of the Object

*Initialize final members

*Essentially a runtime stub

Initialization

*

*Make the Object useful

*Instantiate and initialize publicly accessible members

*Instantiate and initialize private members that are variable values

*Object should now pass external tests with out generating exceptions (assuming code is correct)

Reset

*

*Does not instantiate anything

*Assigns default values to all variable public/private members

*returns the Object to an exact state

A Toy example:
public class TestObject {
   private int priv_a;
   private final int priv_b;
   private static int priv_c;
   private static final int priv_d = 4;

   private Integer priv_aI;
   private final Integer priv_bI;
   private static Integer priv_cI;
   private static final Integer priv_dI = 4;

   public int pub_a;
   public final int pub_b;
   public static int pub_c;
   public static final int pub_d = 4;

   public Integer pub_aI;
   public final Integer pub_bI;
   public static Integer pub_cI;
   public static final Integer pub_dI = 4;

   TestObject(){
        priv_b = 2;
        priv_bI = new Integer(2);
        pub_b = 2;
        pub_bI = new Integer(2);
   }

   public void init() {
       priv_a = 1;
       priv_c = 3;
       priv_aI = new Integer(1);
       priv_cI = new Integer(3);

       pub_a = 1;
       pub_c = 3;
       pub_aI = new Integer(1);
       pub_cI = new Integer(3);
   }

   public void reset() {
       priv_a = 1;
       priv_c = 3;
       priv_aI = 1;
       priv_cI = 3;

       pub_a = 1;
       pub_c = 3;
       pub_aI = 1;
       pub_cI = 3;
   }
}

A: I would design my classes in a way so that an "init" method is not required. I think that all methods of a class, and especially public methods, should guarantee that the object is always left in a "valid" state after they complete successfully and no call to other methods is required.
The same holds for constructors. When an object is created, it should be considered initialized and ready to be used (this is what constructors are for and there are numerous tricks to achieve this). Otherwise, the only way that you can safely use it is checking if the object has been initialized in the beginning of every other public method.

A: I come from a C++ background where the rules are a bit different from Java, but I think these two-stage initialization principles apply in the general case.
Construction

*

*Everything that can be done at construction time should be done at construction time.

*Minimize the amount of "badness" that can result from trying to use your object before calling init().

*All member variables need a value, even if it's a normally invalid sentry value (e.g., set pointers to null).  I think Java will initialize all variables to zero by default, so you need to pick something else if that's a valid number.

Initialization

*

*Initialize those member variables that depend on the existence of other objects.  Basically, do the things you couldn't do at construction time.

*Ensure your object is now in a complete, ready-to-use state.  Consider throwing an exception if it isn't.

Reset

*

*Think long and hard about what state The System will be in when you'd want to call such a function.  It may be better to create a new object from scratch, even if that operation seems expensive.  Profile your code to find out if that's a problem.

*Assuming you got past item 1, consider writing a method to handle the things that both reset() and your constructor need to do.  This eases maintenance and avoids code duplication.

*Return your object to the same state it was in after init().

A: Can't say that I've ever used this exact pattern, but I've used similar things to reduce code duplication.  For example when you have an object that may be either created via a constructor or from a another object (like a DTO) via a factory method.  In that case, I'll often have an internal initializer that populates the properties of the object that is used by both.  Can't say that I've ever used a "reset" method, nor do I see a real need for one if all it does is replicate the process of creating a new object.
Lately, I've moved to only using default constructors and using property settors to initialize the object.  The new C# syntax that allows to easily do this in a "constructor-like" format makes this every easy to use and I find the need to support parameterized constructors disappearing.

A: Is there a reason init() and reset() need to be different? It's hard to see in this simple example why the "does not instantiate anything" rule is important.
Beyond that, I think objects should be useful as soon as they're constructed. If there's a reason -- some circular dependency or inheritance issue -- an object has to be "initialized" after construction, I would hide the constructor and the initialization behind a static factory method. (And probably move the initialization code to a separate configurator object for good measure.)
Otherwise you're counting on callers always to call both the constructor and init(), and that's a non-standard pattern. We have some old, too-useful-to-throw-away code here that does that; it's an abstract dialog class, and what happens is, every time someone extends it, they forget to call constructUI() and then they waste 15 minutes wondering why their new dialog is empty.

A: Interesting. I especially find this construction useful if you have an object that needs to perform IO operations.  I do not want anything to perform IO operations direct or indirectly in their constructor. It makes the object a nightmare to use.


text:
Q: How to write a CLOB to an OS file in Oracle without using UTL_FILE package? I have a variable xml_ which is a CLOB data type variable I use to store some XML data using a PL/SQL procedure dynamically.
I need to write this CLOB data into a file in my machine. The database server is not my machine.
Is there any way to do this?
I am using Oracle 11g.
I am using the procedure given as an answer in another question, but it uses UTL_FILE package , and as I don't have direct access to the database server machine, I would like to know how to write the file into a directory in my local machine instead.
Edit:
I am creating the xml dynamically. I tried to store the data in a table with a CLOB column, but it shows <value error> when I try to see the data using PLSQL Developer. I am thinking it is because the size of the xml is too large to open from the PLSQL editor or there is something wrong with the created data. Hence I am trying to write the data to a file to check if there are some invalid characters etc.
Edit2:
I got this resolved via Oracle SQL Developer.
The CLOB data was over 2 GB, Oracle SQL Developer showed me the column data, hence I was able to export it into a file in my client machine itself.


text:
Q: Set a key value to the closest node element given two lists Say I have a list of keys,  k = [2,3,7,15,18,23] ; and a list of nodes,  n = [1,5,10,15,20] . Both lists are sorted lists.
Then the "closest next node", or the successor node for key  k = 2  is  n = 5 ; for  k = 3  is  n = 5; for  k = 7  is  n = 10 , and so on. If the key value is greater than the last node value, then its successor node is the first node element, so k = 23 is n = 1. I want to output a list array that maps each successor nodes with their keys in format [[successor_node1, key, key],[successor_node2, key, key],...]. So the results for example is output_array = [[5,2,3],[10,7,],[15,15],[20,18],[1,23]]
how can I achieve these with F# in just ONE function?

A: You can do this by writing a recursive function that iterates over the two lists and pattern matches on the first elements. To keep the result, the best option is probably to use an immutable map - as you go, you can add the values for the individual keys associated with individual successor nodes:
let k = [2;3;7;15;18;23]
let n = [1;5;10;15;20]

let rec findSuccessors first res k n =
  // Add a key 'k'  associated with a successor node 'n' to the list
  let add k n =
    match Map.tryFind n res with
    | None -> Map.add n [n; k] res
    | Some l -> Map.add n (l @ [k]) res
  match k, n with
  | [], _ ->
    // If there are no more keys, we return the results
    res |> Map.toList |> List.map snd
  | k::ks, [] ->
    // If there are no more successors, use the special 'first'
    findSuccessors first (add k first) ks []
  | k::ks, n::ns when n < k ->
    // If we have a key 'k', but the next node is smaller, skip it
    findSuccessors first res (k::ks) ns
  | k::ks, n::ns ->
    // Found a key 'k' with a successor 'n' - add it to the list
    findSuccessors first (add k n) ks (n::ns)

findSuccessors (List.head n) Map.empty k n

A: I came up with a new solution to your description of the problem, rather than trying to modify your code. I'm using quite a different approach: no mutable variables or data structures, just pure functional code with one recursive function. I did this because it was easier for me, not because pure code is always better.
let mapNodes startingNodes startingKeys =
    let rec loop remainingNodes remainingKeys acc =
        match remainingNodes, remainingKeys with
        | _, [] ->
            acc
        | [], keys ->
            let next = startingNodes |> List.tryHead |> Option.map (fun firstNode -> firstNode :: keys)
            match next with
            | Some next -> next :: acc
            | None -> acc // this shouldn't happen if there is at least one starting node
        | nextNode :: restNodes, keys ->
            let keysForNode = keys |> List.takeWhile (fun key -> key <= nextNode)
            match keysForNode with
            | [] ->
                loop restNodes keys acc
            | keysForNode ->
                let next = nextNode :: keysForNode
                let restKeys = keys |> List.skip keysForNode.Length
                loop restNodes restKeys (next :: acc)

    loop (startingNodes |> List.tail) startingKeys [] |> List.rev

let nodes = [ 1; 5; 10; 15; 20 ]
let keys = [ 2; 3; 7; 15; 18; 23 ]
let expected = [ [ 5; 2; 3 ]; [ 10; 7 ]; [ 15; 15 ]; [ 20; 18 ]; [ 1; 23 ] ]

let result = mapNodes nodes keys // [[5; 2; 3]; [10; 7]; [15; 15]; [20; 18]; [1; 23]]
result = expected // true

The general approach is to use a recursive loop that explicitly passes through all of the input state required, rather than using mutable variables. An accumulator acc is also passed through to gather the output.
This code uses a List.takeWhile, followed by a List.skip on the same list. This is slightly inefficient. It could be improved if there was a List.splitWhen function in the F# library, or if you were to write one yourself.

A: One more attempt in addition to what was proposed earlier :) I'm not well familiar with F# standard library and idioms, so it might be not idiomatic/suboptimal/both, but I tried to solve it in a very straightforward way (as I would explain the solution verbally):
let nearest_keys_per_node keys nodes =
  (* Simple helper function that finds the nearest next node for a given key *)
  let nearest_next_node nodes k =
    match nodes with
      | [] -> failwith "Empty nodes list!"
      | hd :: tl ->
        let rec nearest_node_tr k current_best = function
          | [] -> current_best
          | hd :: tl when hd < k -> nearest_node_tr k current_best tl
          | hd :: tl -> hd
        nearest_node_tr k hd tl

  List.map (nearest_next_node nodes) keys (* Get the nearest next node for each key *)
  |> List.zip keys                        (* "Glue" them together with the keys - gettin a list of tuples (key, node) *)
  |> Seq.groupBy (fun (_, node) -> node)  (* Group by nodes*)
  |> List.ofSeq
  |> List.map (fun (node, seq) ->         (* "Cleanup" the structure that we got after the grouping and transform in to your desired output *)
      node :: (List.ofSeq(seq) |> List.map fst)
    )
;;

> nearest_keys_per_node [2;3;7;15;18;23] [1;5;10;15;20];;
val it : int list list = [[5; 2; 3]; [10; 7]; [15; 15]; [20; 18]; [1; 23]]


text:
Q: Can the Q really time-travel? Do we really know whether the Q can time-travel as opposed to just having the ability to set up good illusions, and possibly take people out of time?
Don't we only have his word for it? Is there some hard example that shows Q really can travel and alter the timeline?

A: It would seem to me the answer can't be a complete yes, as it appears the Q can't see extremely far into the future, as Q notes in "Hide and Q" there is a future that is beyond even their ability to conceive.

Riker: Eons! Have you any idea how far
              we'll advance?
Q (COMMANDER): Perhaps in a future you cannot yet conceive... even beyond us. And so, we must know more about the human condition. We have selected you, Riker, to become part of the "Q"... to bring that human need and hunger to us so that we may understand it.

A: Yes. In the episode "Death Wish", the Q known as Quinn (AKA Q2) takes the Voyager back in time to the Big Bang itself.

TUVOK: Captain, based on our readings, it appears that we have been transported back in time to the birth of the universe.
Janeway looks sharply at Q2 who smiles as he watches the viewscreen... acknowledging.
Q2: Very old hiding place.
ANGLE (OPTICAL) There's a flash, and Q1 appears near Torres.
Q1: (beat, to Q2) I know all the hiding places, Q. I hid here from the Continuum myself once.

Even if Tuvok was somehow mistaken about his readings, since this time jump was made in an attempt to evade another Q (who presumably would be in no way fooled by a mere illusion) it makes no sense for this to have been a trick.

A: Restating other answers, but Star Trek canon is full of examples of humans accidentally or intentionally travelling through time; the time travels are always depicted as "real" (never hallucinations or of ambiguous "reality") and usually explore some aspect of visits to the past influencing the "present" state (or affecting the timeline). This makes time travel an established fact within Star Trek canon, and in a number of cases (e.g. TNG "A Matter of Time") accomplished by a device of human (or at least mortal humanoid) construction and control. See this page for a more comprehensive list

*

*TOS "The Naked Time" (three days to "live over again")

*TOS "Tomorrow is Yesterday" (accidentally thrown into 1960s Earth)

*TOS "Assignment: Earth" (Gary Seven)

*TOS "The City on the Edge of Forever" (the "Guardian of Forever" allows McCoy to mess up the timeline and Kirk & Spock to go back and fix it; OK, not a human device, but apparently of "mortal" construction)

*TNG "Yesterday's Enterprise" (a wormhole allows an earlier Enterprise to escape destruction at the hand of the Romulans by visiting the TNG timeframe)

*TNG "Tapestry" (Picard never gets stabbed through the heart; arguably only playing out in Picard's head so maybe we can't count this one)

*TNG "All Good Things" (three points in the Federation timeline; Q promises Picard that only he will be aware of Q's activity, but that doesn't diminish the fact that Picard is allowed to mess up and then correct the timeline)

*TNG "A Matter of Time" ("Dr. Rasmussen" pays a visit to the Enterprise ostensibly to witness an important disaster relief mission)

*DS9 "Little Green Men" (Quark & co. inadvertently become the 1947 Roswell aliens; played tongue-in-cheek, but no suggestion it was just an illusion)

*DS9 "Trials and Tribble-ations" (The "orb of time" facilitates a visit to space station K7 during the time of "The Trouble with Tribbles")

*DS9 "Past Tense" (Sisko and others accidentally travel back to the time of the "Bell Riots").

*VOY "Time and Again" (time is fractured on a planet utilizing a tricky form of power, pulling Janeway and Paris into the planet's recent past)

*VOY "Future's End" (Henry Starling of the late 20th century acquires technology from Capt. Braxton's time ship)

*VOY "Relativity" (Braxton recruits Seven to find/disarm a bomb planted by his future self)

*VOY "Timeless" (future Chakotay and Kim save "present" Voyager by sending a message into the past via technology from Seven; not a time travel story, but built around the existence of time travel-like technology)

*VOY "Endgame" (future Janeway "borrows" an experimental time travel device to give her past self a little help in getting home sooner)

*ENT (various episodes) - Enterprise had a "temporal cold war" as a recurring theme / series arc. Included in the arc was the mysterious figure from the future guiding the Suliban against the Federation and Crewman Daniels who is revealed to be an operative from the future sent to stop them. Story lines include Archer being scooped out of his present day (by Daniels) to visit a bleak future.

*"The Voyage Home" (movie) - The TOS crew "slingshot" a Klingon bird of prey around the Sun to collect a couple of whales from 20th century Earth

*"Generations" (movie) - Not exactly a time travel story, although the Nexus seems to exist outside of normal space and time, allowing someone to exit it at a time and place of their choosing, as used by Kirk to help Picard.

*"First Contact" (movie) - The Borg go back in time to conquer Earth and the Enterprise follows to stop them, meeting Zefram Cochrane in the process)

Given all that canon, it would be hard to imagine that the Q could not do as much or more with time than humans or "lower forms" (in Q-speak) have done, either accidentally or intentionally.
For what it's worth: there is a DS9 story of Sisko as a 1950s science fiction writer, but this is clearly revealed to be a "vision"/hallucination.

A: Nature of the Q continuum
The Q continuum is an extradimensional realm, and as such exists outside the space-time continuum of the universe as we perceive it.
It is highly likely, as extradimensional beings, that the Q can travel through time in our universe.  Our universe is either a spacetime submanifold of the larger Q continuum or are two disconnected universes.  In either case, the Q seem to be able to enter our spacetime manifold at a point of their choosing ("point" meaning a location in space and time).
Memory Alpha has the same opinion:

The Q Continuum was an extradimensional plane of existence inhabited by a race of beings known as the Q. The term could also refer to the Q society itself.
As a race, the Q were immortal, but not absolutely omniscient or omnipotent, just possessing the ability of instantaneous matter-energy transformation and teleportation, as well as the ability of time travel. Their apparent abilities included moving entire asteroid belts and stars, creating alternate timelines, and affecting universal states of nature such as the gravitational constant.

Note that these are just my opinions and the opinions of whoever contributed to the Memory Alpha entry.
Knowledge of time travel techniques
Since the Q are for all intents and purposes omniscient and know exactly what humans have and have not achieved, there is no denying that the Q would know that humans themselves have achieved time travel in the past (a feat performed twice by the original Enterprise crew).  Therefore, the Q would know how to achieve at least one form of time travel.
Since the question was "Do we really know whether the Q can time-travel?" (rather than, "Have we seen an actual instance of Q travelling through time?"), the answer would almost certainly be Yes.
Possible canon example
In terms of canon, we see in the series finale of TNG ("All Good Things...") an example of Q travelling through time, at least seemingly.  He and Picard travel between four different time periods: the present; seven years prior; twenty-five years into the future; and far into the past to a time when life was only beginning on Earth:

On the face of it, there is no indication that these travels were an "illusion".  On the other hand, since only Picard remembers what happened, it could have been an elaborate illusion.  The sentiments of the official StarTrek.com entry on the episode suggest that it was "real", however:

Picard is returned to the moment his adventure began, coming from the Turbolift in his bathrobe. He shares his experience with the crew, using what he has learned about the future to forge a new, closer relationship with his dearest friends.

(Source)


text:
Q: datepicker not working in wordpress I`m trying to add a custom post field using datepicker jquery ui. In function.php I have the following code:
function daily_idea_admin_script_style( $hook ) {
global $post_type, $wp_scripts;
if ( ( 'post.php' == $hook || 'post-new.php' == $hook ) && ( 'daily_idea' == $post_type ) ) {
    $ui = $wp_scripts->query('jquery-ui-core');
    if ($ui) {
        $uiBase = "http://ajax.googleapis.com/ajax/libs/jqueryui/{$ui->ver}/themes/cupertino";
        wp_enqueue_script('daily_idea', get_template_directory_uri() .'/js/daily_idea_script.js', array( 'jquery', 'jquery-ui-datepicker' ), '1.0', true);
        wp_enqueue_style('jquery-ui-min', "$uiBase/jquery-ui.min.css", FALSE, $ui->ver);
    }
  }
}

add_action( 'admin_enqueue_scripts', 'daily_idea_admin_script_style' );

The info metabox are displayed with the input field but when I clicked on it, datepicker is not displayed.
Note: this is my first this is my first custom post field I`ve ever created on wordpress
EDIT: my custom daily_idea_script.js is :
(function( $ ) {
$.noConflict();
$( '#daily_idea_date' ).datepicker({
    dateFormat: 'dd MM yy',
    onClose: function( selectedDate ){
        $( '#daily_idea_date' ).datepicker( 'option', 'maxDate', selectedDate );
    }
});

})( jQuery );

A: you have a couple of errors here...
remove
$.noConflict(); // not neccessary

remove:
onClose: function( selectedDate ){
    $( '#daily_idea_date' ).datepicker( 'option', 'maxDate', selectedDate );
}

i guess you are trying to set the maximum date of the datepicker but you are trying to recreate a datepicker on the same element? what do you actually want to do here?
Datepicker works much cleaner with jQuery(document).ready() or $(function(){} for short. The method you are using, the function will run immediately, at which stage the dom is not ready and jquery cant find the element identified.


text:
Q: Cannot resolve promise from axios response on client side I am doing an api request to my express backend via axios in my action creators.
I can see the request logged on the backend (but without a status) and successfully going through, but the response never returns to the front end (I do not see the LOGIN_SUCCESS output in the browser console).
When I simulate the same request on curl locally, it works just fine and returns 200 with the message.
Frontend:
./actions/index.js
const loginRequested = function () {
    console.log(LOGIN_REQUESTED)
    return {
        type: LOGIN_REQUESTED,
        loading: true,
    }
}

const loginSuccess = function () {
    console.log(LOGIN_SUCCESS)
    return {
        type: LOGIN_SUCCESS,
        isAuthUser: true,
    }
}

export const login = ({ email, password }) => {
    return dispatch => {
        dispatch(loginRequested());

        axios.post('http://localhost:9000/login', {
            username: email,
            password: password,
        }).then(response => {
            console.log('This has been reached')
            dispatch(loginSuccess(response));
        }).catch(err => {
            console.log('An error took place: ', err)
        })
    }
}

Login component:
import React, { Component } from 'react';
import Button from 'react-bootstrap/Button';
import { connect } from 'react-redux';
import Form from 'react-bootstrap/Form';
import { login } from './actions/index'
class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            password: '',
        }
        this.setEmail = this.setEmail.bind(this);
        this.setPassword = this.setPassword.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit() {
        this.props.login({
            email: this.state.email,
            password: this.state.password,
        })
    }

    setEmail(e) {
        this.setState({ email: e.target.value });
    }

    setPassword(e) {
        this.setState({ password: e.target.value });
    }

    render() {
        return (
            <Form className="Form" onSubmit={this.handleSubmit}>
                <Form.Group controlId="formBasicEmail">
                    <Form.Label>Email address</Form.Label>
                    <Form.Control
                        autoFocus
                        type="email"
                        name="email"
                        placeholder="Enter email"
                        onChange={this.setEmail}
                    />
                    <Form.Text className="text-muted">
                        We'll never share your email with anyone else.
                    </Form.Text>
                </Form.Group>

                <Form.Group controlId="formBasicPassword">
                    <Form.Label>Password</Form.Label>
                    <Form.Control
                        type="password"
                        name="password"
                        placeholder="Password"
                        onChange={this.setPassword}
                    />
                </Form.Group>
                <Form.Group controlId="formBasicCheckbox">
                    <Form.Check type="checkbox" label="Remember Password" />
                </Form.Group>
                <Button variant="primary" type="submit">
                    Submit
                </Button>
            </Form>
        );
    }
}

const mapDispatchToProps = dispatch => {
    return {
        login: user => {
            dispatch(login(user));
        }
    }
}

const mapStateToProps = state => {
    return {
        isAuthUser: state.isAuthUser,
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Login);

I am also using redux-thunk to support async operations:
const store = createStore(rootReducer, applyMiddleware(thunk));

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

Backend:
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var homeRouter = require('./routes/home')
var loginRouter = require('./routes/login');
var registerRouter = require('./routes/register')
var db = require('./repositories/db');
var app = express();

// Connect to DB
require('./repositories/db')

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// app.use('/', indexRouter);
// app.use('/users', usersRouter);
app.use('/home', homeRouter);
app.use('/login', loginRouter);
app.use('/register', registerRouter)
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

routes/login.js:
router.post('/', function (req, res, next) {
    User.findOne({ email: req.body.username }).then(
        (user) => {
            if (!user) {
                return res.status(401).json({
                    error: new Error('User not found!')
                });
            }
            bcrypt.compare(req.body.password, user.password).then(
                (valid) => {
                    username = req.body.username;
                    if (!valid) {
                        return res.status(401).json({
                            error: new Error('Incorrect password!')
                        });
                    }
                    const token = jwt.sign({ username }, jwtKey, {
                        algorithm: 'HS256',
                        expiresIn: jwtExpirySeconds,
                    });
                    console.log('User successfully logged in.');
                    res.cookie('token', token, { maxAge: jwtExpirySeconds * 1000 });
                    res.send({ message: 'We did it!' })
                }
            ).catch(
                (err) => {
                    console.log('Error logging in: ', err);
                    res.status(500).json({
                        error: err
                    });
                }
            );
        }
    ).catch(
        (err) => {
            res.status(500).json({
                error: err
            });
        }
    );
});

Request from curl:
curl -X POST -H 'Content-Type: application/json' -d '{
    "username": "a@a.com",
    "password": "qwer1234"
}' -v -i 'http://localhost:9000/login'

Output from curl:
User successfully logged in.
POST /login 200 61.225 ms - 24

Output from programmatic API request above:
POST /login - - ms - -
User successfully logged in.


text:
Q: Using a pipe with SQL Server OPENROWSET file spec We're getting some very large .tar.gz files that we want to load into SQL Server (like 3 gig gzipped, 20 gig uncompressed).
I thought I would try to save both some time and disk space by writing a C# layer to decompress and stream to SQL Server on the fly using named pipes.
I found this: Can Sql Server BULK INSERT read from a named pipe/fifo?
and both answers had some "we don't know why this is necessary but it doesn't work otherwise" comments

*

*the need to open 2 pipes and

*the need to do it all in one big write to SQL Server

It's not really practical to do 1 big 20 gig write, so I was tinkering with the code in the above solutions.
What I found was that when I
byte[] buff = new byte[<pick your size here>];
int readlen;

while ((readlen = inputStream.Read(buff, 0, buff.Length)) > 0)
{
    pipeStream.Write(buff, 0, readlen);
    pipeStream.WaitForPipeDrain();
}

I get 2 writes in and I get a "Pipe is broken" error on the third pretty much no matter what the buffer size is.
Originally I tried
inputStream.CopyTo(pipeStream);

and by default that uses an 80k buffer. Looking at Position, I could see that I'd be on the third write when it blew up.
Any idea what might be happening on the SQL Server side to break off after 2 reads?
EDIT:  I did some playing around and found that with larger buffer sizes it would get farther.  When I got above 1 meg buffers, I got almost up to 2 gig written to the pipe before it broke.  Going above 5 meg buffers didn't improve things.
At first I thought the overhead of decompressing the zip might have had the reads lagging the writes, so Sql Server might have closed on a timed out read or something.  I made the reads and writes async so I could get the next read going while the write was happening, but that didn't help.
I added some timing, and it turned out the pipe writes were taking 2.5 times as much time as the gzip reads, so I don't know why the pipe ultimately breaks.
Still almost 2 gig was a lot farther that 2-3 writes of a few hundred K


text:
Q: Nodemailer sends email but cant get response from it am trying to send a email with nodemailer and its sending successfully but its not getting any response so that i can be shown to client side . here is the code
    let mailTransporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'user123@gmail.com', //your email
            pass: ' ' //password
        }

    });

    let mailDetails = {
        from: 'user123@gmail.com',
        to: 'user125@gmail.com',
        subject: 'mail',
        text: 'Thanks for email'
    };

    mailTransporter.sendMail(mailDetails, function(err, data) {
        if(err) {
            console.log(err);
        }
        else {
            res.status(200).send(data)
            console.log(data);
        }
    });
}


text:
Q: Permissions dialog does not show up anymore When a user logs into my website, I want to post a message to the user's wall. Therefore I use this code:
post on wall

function permission() {
    FB.login(wallPost, {perms: 'publish_stream'})
}

function wallPost() {
    var wall = { message: 'testing wallpost'};
    FB.api('/me/feed', 'post', wall, function (response) {
        if (!response) {
            alert("noresponse");
        } else if (response.error) {
            alert("response error");
        } else {
             alert('Post succesfull!" (post id: ' + response.id + ")");
        }
    });
}

So when a user clicks the link, the user gets a pop-up for the publish_stream permission. And when the users allows it, the post is succesful. The first three times I tested this, it worked fine, but now, for some reason, this code does not work anymore (I get the alert "response error")
What am I doing wrong?

A: Use 'scope' instead of 'perms' in the login button. This changed on October 1st 2011.


text:
Q: Easy way to parse array values Is there util that parses array content without the need of iterating it and parsing each value?
input: ['2','3','7']
output: [2, 3, 7]

A: This obviously iterates internally, but you don't have to code an iterator:
$output = array_map('intval', $input);

Maps every value in $input to the intval() function and returns the result.  For things that cannot be converted into an integer you'll get 0 or for objects, a notice and that value will not be returned.
I can't tell if you want to remove 0 values or not from your comment, but if so:
$output = array_filter(array_map('intval', $input));

A: You can use array_map
array = ["2","3","4"];

$intArray = array_map('intval', $array);


text:
Q: redis-data.rdb will not run/corrupted (maybe) i run a discord bot that uses redis, but after i shut down the bot yesterday and restarted it to apply an update, this happened. does anyone know?
redis-data     | --- RDB ERROR DETECTED ---
redis-data     | [offset 119004] Invalid LZF compressed string
redis-data     | [additional info] While doing: read-object-value
redis-data     | [additional info] Reading key 'stupidstuff'
redis-data     | [additional info] Reading type 2 (set-hashtable)
redis-data    | [info] 10 keys read
redis-data    | [info] 3 expires
redis-data    | [info] 0 already expired
redis-data exited with code 1

here is the entire console log:
     https://pastebin.com/MTPBsKGm

A: This might be a the dump.rdb is corrupted. Try running the following command to clean up the redis db dump logs:
docker volume ls - to find the volume used your redis conrtainer

docker volume rm <name> - to remove the


text:
Q: problem with series in this proof I am studying exponential matrices ,  and there is a part of a proof that I don't understand .
Given the matrix
$$
J=\left(\begin{array}{cc}
0 & 1 \\
-1 & 0
\end{array}\right)
$$
the power of $J$ are eas to compute
$$
J^{2 k}=(-1)^k I, J^{2 k+1}=(-1)^k J
$$
and so
$$
\begin{aligned}
e^{\beta_j J t} & =\sum_{k=0}^{+\infty} \frac{\beta_j^k J^k t^k}{k !} \\
& =\left(\sum_{k=0}^{+\infty} \frac{(-1)^k\left(\beta_j t\right)^{2 k}}{(2 k) !}\right) I+\left(\sum_{k=0}^{+\infty} \frac{(-1)^k\left(\beta_j t\right)^{2 k+1}}{(2 k+1) !}\right) J \\
& =\cos \left(\beta_j t\right) I+\sin \left(\beta_j t\right) J=\left(\begin{array}{cc}
\cos \left(\beta_j t\right) & \sin \left(\beta_j t\right) \\
-\sin \left(\beta_j t\right) & \cos \left(\beta_j t\right)
\end{array}\right)
\end{aligned}
$$
The part that I don't understand is when he separate the infinite summation in 2 parts . I Don't know why is possible to do that ,in general you can't separate an infinite series .


text:
Q: Using BETWEEN SYMMETRIC for checking 2 row value expressions I would like to compare two columns values from Table-1 (say colA, colX) to check if these are in the range of values for columns in Table-2 (say colB, colD, colY, colZ). That's, if colA is between colB-colD, and/or colX is between colY-colZ respectively.
I understand BETWEEN SYMMETRIC is used when order is irrelevant, e.g. (min, max) or (max,min). Below is the example I created.
TABLES:
CREATE TABLE location (id int, lat float, lon float, gpstime int);
CREATE TABLE trips( trip_id int, lat_start float, lat_end float,
               lon_start float, lon_end float, travel_mode text);

TABLE VALUES:
INSERT INTO location
SELECT 1, 41.2, 8.3, 11111 UNION ALL   --both lat and lon in the interval
SELECT 2, 43.3, 8.5, 22222 UNION ALL   --only lat meets criteria
SELECT 3, 44.0, 8.5,  33333            --only lon meets criteria

INSERT INTO trips
SELECT 1, 41.1, 41.9, 8.0, 8.8, 'foot' UNION ALL
SELECT 2, 43.1, 43.5, 9.5, 8.9, 'bus' UNION ALL
SELECT 3, 42.1, 42.8, 8.7, 8.0, 'metro'

TASK:
The goal is to get all rows for which either lat or lon (or both) in location table happen to satisfy the criteria (in trips table): lat between lat_start-lat_end; lon between lon_start- lon_end.
Clearly all rows of location table should be returned: row 1 meets all and rows 2 and 3 meet either criteria.
Expected result:
+---------+-----------+------+-----+-------------+
| trip_id | timestamp | lat  | lon | travel_mode |
+---------+-----------+------+-----+-------------+
|       1 |     11111 | 41.2 | 8.3 | foot        |
|       2 |     22222 | 43.1 | 8.5 | bus         |
|       3 |     33333 | 44.0 | 8.5 | metro       |
+---------+-----------+------+-----+-------------+

So I tried different queries using BETWEEN SYMMETRIC but the results aren't correct.
Query-1:
SELECT trip_id, gpstime AS timestamp, lat, lon,  travel_mode
FROM location
INNER JOIN trips
   ON (lat BETWEEN SYMMETRIC lat_start AND lat_end)
   AND (lon BETWEEN SYMMETRIC lon_start AND lon_end)

Query result:
+---------+-----------+------+-----+-------------+
| trip_id | timestamp | lat  | lon | travel_mode |
+---------+-----------+------+-----+-------------+
|       1 |     11111 | 41.2 | 8.3 | foot        |
+---------+-----------+------+-----+-------------+

Query-2: messed up everything
SELECT trip_id, gpstime AS timestamp, lat, lon,  travel_mode
FROM location
INNER JOIN trips
   ON (lat, lon) BETWEEN SYMMETRIC (lat_start,  lat_end) AND (lon_start, lon_end)

Result:
+---------+-----------+------+-----+-------------+
| trip_id | timestamp | lat  | lon | travel_mode |
+---------+-----------+------+-----+-------------+
|       2 |     11111 | 41.2 | 8.3 | foot        |
|       3 |     11111 | 41.2 | 8.3 | metro       |
+---------+-----------+------+-----+-------------+

Query-3: worst even
SELECT trip_id, gpstime AS timestamp, lat, lon,  travel_mode
FROM location
INNER JOIN trips
   ON lat BETWEEN SYMMETRIC lat_start AND lat_end
UNION
SELECT trip_id, gpstime AS timestamp, lat, lon,  travel_mode
FROM location
INNER JOIN trips
   ON lon BETWEEN SYMMETRIC lon_start AND lon_end

Result:
+---------+-----------+------+-----+-------------+
| trip_id | timestamp | lat  | lon | travel_mode |
+---------+-----------+------+-----+-------------+
|       1 |     11111 | 41.2 | 8.3 | foot        |
|       1 |     22222 | 43.3 | 8.5 | foot        |
|       1 |     33333 | 44   | 8.5 | foot        |
|       2 |     22222 | 43.3 | 8.5 | bus         |
|       3 |     11111 | 41.2 | 8.3 | metro       |
|       3 |     22222 | 43.3 | 8.5 | metro       |
|       3 |     33333 | 44   | 8.5 | metro       |
+---------+-----------+------+-----+-------------+

Question: What is the correct query to achieve the desired result?
EDIT:
Based on answers received, recommending use of OR instead of AND in Query-1, I edit my question below to show the result of the recommended query:
QUERY:
SELECT trip_id, gpstime AS timestamp, lat, lon,  travel_mode
FROM location
INNER JOIN trips
   ON (lat BETWEEN SYMMETRIC lat_start AND lat_end)
   OR (lon BETWEEN SYMMETRIC lon_start AND lon_end);

And here goes the query results:
+---------+-----------+------+-----+-------------+
| trip_id | timestamp | lat  | lon | travel_mode |
+---------+-----------+------+-----+-------------+
|       1 |     11111 | 41.2 | 8.3 | foot        |
|       3 |     11111 | 41.2 | 8.3 | metro       |
|       1 |     22222 | 43.3 | 8.5 | foot        |
|       2 |     22222 | 43.3 | 8.5 | bus         |
|       3 |     22222 | 43.3 | 8.5 | metro       |
|       1 |     33333 | 44   | 8.5 | foot        |
|       3 |     33333 | 44   | 8.5 | metro       |
+---------+-----------+------+-----+-------------+

A:
The goal is to get all rows for which either lat or lon (or both) in
  location table happen to satisfy the criteria

Replace AND with OR in your first query.

A: The query you are looking for is
SELECT trip_id, gpstime AS timestamp, lat, lon,  travel_mode
FROM location
INNER JOIN trips
   ON (lat BETWEEN SYMMETRIC lat_start AND lat_end)
   OR (lon BETWEEN SYMMETRIC lon_start AND lon_end);

like Salman said, but let me help you clear up the misunderstanding.
What does BETWEEN SYMMETRIC mean?
x BETWEEN SYMMETRIC a AND b

is the same as
x BETWEEN SYMMETRIC LEAST(a, b) AND GREATEST(a, b)

So it just swaps boundaries if appropriate.
What does (a, b) < (c, d) mean?
Comparing tuples is done in a lexicographic fashion.
First, a and c are compared, and only if they are equal, b and d are compared.
So
(a, b) < (c, d)

is the same as
a < c OR (a = c AND b < d)

So that is not what you are looking for at all.


text:
Q: Proving addition and multiplication (1)Show that addition and multiplication mod n are associative operations.
(2)Show that there are both an additive and a multiplicative identity.
(3)Show that multiplication distributes over addition modulo n.
(4)Show that for every integer a there is an additive inverse -a:

I know, for both above, they mean that,
(1) (a+b)+c ≡ a+(b+c) (mod n)
(ab)c ≡ ba (mod n)
(2) a+0 ≡ a (mod n)
    a*1 ≡ a (mod n)
(3) a(b+c) ≡ ab+ac (mod n)
(4) a+(-a) ≡ ab+ac (mod n)

Professor said not to worry about the proofs for these, but I'd rather know it for future courses.��
This seems easy to grasp, for the lack of a better word, but I do not know how I would prove this since class just started.

A: Here are the hints for those problems:

*

*Consider $a \bmod n$, $b \bmod n$ and $c \bmod n$.  Write those congruences in the form $z + nk$ where $k$ is any positive integers.  Add the first two congruences altogether and then, add that by $c \bmod n$.  Do the same for the right-hand side.  What do you know about $(a + b) + c \bmod n$ and $a + (b + c) \bmod n$.  Proving multiplicative associativity follows similarly as proving additive associativity.

*Additive identity is $0$, whereas multiplicative identity is $1$.  To show there exists an identity, prove that in $\mathbb{Z}_n$, the set of integers modulo $n$, for any $a \in \mathbb{Z}_n$, $a + 0 = 0 + a = a \bmod n$ and $a \cdot 1 = 1 \cdot a = a \bmod n$.

*Follow the similar steps for this problem as for the first problem.

*If there exists an additive inverse, then for any $a \in \mathbb{Z}_n$, there exists $c \in \mathbb{Z}_n$ such that $a + c = c + a = 0$.  Here $c = -a$.  I want you to prove this, starting with first similar steps for this problem also.

A: The main task is to show that these operations are well defined in the first place. The properties $(1)$–$(4)$ then follow by inspection.
Let an $n\geq1$ be given once and for all. Call two integers $x$ and $y$ equivalent if $x-y$ is an integer  multiple of $n$:
$$x\sim y\quad:\Longleftrightarrow\quad \exists j\in{\Bbb Z}:\quad x-y=j\>n\ .$$
Check that this is an equivalence relation. Denote the set of equivalence classes by ${\Bbb Z}_n$, and denote the equivalence class containing the number $x\in{\Bbb Z}$ by $[x]$. Define addition and multiplication of classes via representants, as follows:
$$[x]\oplus[y]:=[x+y],\qquad[x]\odot[y]:=[x\cdot y]\ .\tag{1}$$
One now has to check that the operations $\oplus$ and $\odot$ are well defined by $(1)$. This means that one has to verify that $[x]=[x']$ and $[y]=[y']$ together imply
$$[x+y]=[x'+y'],\quad [x\cdot y]=[x'\cdot y']\ .$$
Once this is accomplished the laws $(1)$–$(4)$ for ${\Bbb Z}_n$ immediately follow from the corresponding laws in ${\Bbb Z}$. It suffices to verify this for the first part of $(1)$:
$$\bigl([x]+[y]\bigr)+[z]=[x+y]+[z]=[x+y+z]=[x]+[y+z]=[x]+\bigl([y]+[z]\bigr)\ .$$


text:
Q: Hide lightbox in tablet and mobile devices Hello I am using the featherlight lightbox and need for it not to appear on tablet or mobile devices. I tried using the code from Disable Lightbox in responsive design but was unable to get this to work. Here is the code:

$.noConflict();
jQuery( document ).ready(function( $ ) {

var lightbox = '';

function startLightbox(){
  $.featherlight(lightbox);
}

console.log(getCookie("tc_lightbox"));
if(getCookie("tc_lightbox")){
}
else{
  setCookie("tc_lightbox", 1);
  setTimeout(startLightbox, 1500);
}

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

function setCookie(cname, cvalue) {
    var d = new Date();
    d.setTime(d.getTime() + (24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

});
.featherlight-content h1,h3{
  margin:0;
}
.featherlight-content h1{
  font-size:25px;
  font-weight:bold;
}
.featherlight-content form input[type="text"], .featherlight-content form input[type="email"]{
    width:100%;
    height: 34px;
    border: 1px #757576 solid;
    border-radius: 3px;
    font-size: 16px;
    font-family: 'avenirroman';
    color: #999;
    background-color: #fff;
}
.featherlight-content form input[type="submit"]{
    width:100%;
    cursor:pointer;
    background: #f37736;
    padding: 10px 25px;
    color: #fff;
    font-family: 'avenirblack', Arial Black;
    font-size: 20px;
    text-decoration: none;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border: none;
}

.featherlight .featherlight-content {
    background: transparent !important;
}

@media only screen and (max-width: 767px) {
.featherlight img {
    max-width: 100%;
}
}

ive also tried
if ($(window).width() < 960) {
        $(lightbox).hide();
    }

and using display: none in a media query using css
any ideas?

A: The problem with this
if ($(window).width() < 960) {
    $(lightbox).hide();
}

Is just that the lightbox variable is referencing a string of text instead of an element. Checking the featherlight demo listed on their page, you could try something like this
$('a[data-featherlight]').hide();

If that doesn't work, you could also try adding a class to your lightbox string
var lightbox = '';

and then use this line
$('.hidethis').hide();

A: The solution is not to hide it on small screens, but to never load it unless it satisfies your requirements. You could test for touch with Modernizr or some other check for screenSize. If the test doesn't pass... then you don't load the plugin.
if ( shouldWeShowLightbox ) {
  lightbox.init();
else {
  // don't do anything.. or possibly inject link HREFS or something different to deal with your situation
}

You can also periodically check what the screensize is and load the plugin it the screen gets bigger or something. Most quality plugins have a .destroy() method to kill it if for some reason you leave that 'view' or the requirement isn't met.

A: If you want to disable featherlight on a mobile or tablet add this jQuery script somewhere and it works perfectly for my case!

Where 960 is the responsive breakpoint (960pixels) where you want to disable the lightbox effect.
We are force disabling all the a links that has the data-featherlight attribute


text:
Q: create associative array from multi dimensional associative post array - Codeigniter I have created a form that produces a multi-dimensional post array. I want to change to array so I can insert it into my table.
This is the post array that is returned.
Array
(
  [project_no] => 160
  [result] => Array
    (
        [5] => Array
            (
                [temp_dwg_rev] => D
                [temp_dwg_id] => 5
            )

        [6] => Array
            (
                [temp_dwg_rev] => D
                [temp_dwg_id] => 6
            )

        [7] => Array
            (
                [temp_dwg_rev] => E
                [temp_dwg_id] => 7
            )
    )

    [client] => Array
        (
            [1] => Array
                (
                    [client_id] => 1
                )

            [3] => Array
                (
                    [client_id] => 3
                )

        )

)

So I suppose that array should look something like this to get the query to work
Array
(
[0] => Array
    (
        [temp_dwg_id] => 5
        [temp_dwg_rev] => D
        [project_no] => 160
        [client_id] => 1
    )

[1] => Array
    (
        [temp_dwg_id] => 6
        [temp_dwg_rev] => D
        [project_no] => 160
        [client_id] => 1
    )

[2] => Array
    (
        [temp_dwg_id] => 7
        [temp_dwg_rev] => E
        [project_no] => 160
        [client_id] => 1
    )
[3] => Array
    (
        [temp_dwg_id] => 5
        [temp_dwg_rev] => D
        [project_no] => 160
        [client_id] => 3
    )

[4] => Array
    (
        [temp_dwg_id] => 6
        [temp_dwg_rev] => D
        [project_no] => 160
        [client_id] => 3
    )

[5] => Array
    (
        [temp_dwg_id] => 7
        [temp_dwg_rev] => E
        [project_no] => 160
        [client_id] => 3
    )
)

My table in the db looks like this. Note slip_id is auto incremented.
|slip_id |project_no |client_id |temp_dwg_id |temp_dwg_rev
|1       |160        |1         |5           |D
|2       |160        |1         |6           |D
|3       |160        |1         |7           |E
|4       |160        |3         |5           |D
|5       |160        |3         |6           |D
|6       |160        |3         |7           |E

I've tried the following code but this create an array with just temp_dwg_id, temp_dwg_rev and project_on in an associative array. I still need to add the client array to this
        $drawings = $_POST['result'];
        $dist = $_POST['client'];
        $project_no = $_POST['project_no'];

        $test = array();
        foreach ($drawings as $row)
        {
            $test[$row['temp_dwg_id']]['temp_dwg_id']= $row['temp_dwg_id'];
            $test[$row['temp_dwg_id']]['temp_dwg_rev']= $row['temp_dwg_rev'];
            $test[$row['temp_dwg_id']]['project_no']= $project_no;

        }

A: Give this a try:
foreach($dist as $client)
{
  foreach($drawings as $drawing)
  {
    //determine the index for your current drawings
    $index = count($test);
    $test[$index]['temp_dwg_id']= $drawing['temp_dwg_id'];
    $test[$index]['temp_dwg_rev']= $drawing['temp_dwg_rev'];
    $test[$index]['project_no']= $project_no;
    $test[$index]['client_id']= $client['client_id'];
  }
}

Edited to show example using array_push()
foreach($dist as $client)
{
  foreach($drawings as $drawing)
  {
    $newDrawing = array(
      'temp_dwg_id'  => $drawing['temp_dwg_id'],
      'temp_dwg_rev' => $drawing['temp_dwg_rev'],
      'project_no'   => $project_no,
      'client_id'    => $client['client_id'],
    );
    array_push($test, $newDrawing);
  }
}


text:
Q: How to inject 'TeamSpecificConversationState', 'DropNonTeamsActivitiesMiddleware' and 'TeamsMiddleware' into Bot by autofac under .NET Framework I'm a newbie about MS Bot development. I try to develop a MS Teams bot by Web API and autofac under .NET Framework. As MS sample code, the bot can work as a common bot. Now I want to only use it in Teams activity and conversations but person stuation. As Preview Release of .Net Teams Bot Builder v4 SDK, TeamSpecificConversationState, DropNonTeamsActivitiesMiddleware, DropChatActivitiesMiddleware and TeamsMiddleware could be used in my development case. But I cannot use autofac and Bot Frameworkv4 well. Below is my code:
    //setting Bot data store policy to use last write win
    //example if bot service got restarted, existing conversation would just overwrite data to store
    public static class BotConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // The ConfigurationCredentialProvider will retrieve the MicrosoftAppId and
            // MicrosoftAppPassword from Web.config
            builder.RegisterType<ConfigurationCredentialProvider>().As<ICredentialProvider>().SingleInstance();

            // Create the Bot Framework Adapter with error handling enabled.
            builder.RegisterType<AdapterWithErrorHandler>().As<IBotFrameworkHttpAdapter>().SingleInstance();

            // The Memory Storage used here is for local bot debugging only. When the bot
            // is restarted, everything stored in memory will be gone.
            IStorage dataStore = new MemoryStorage();

            //// Create Conversation State object.
            //// The Conversation State object is where we persist anything at the conversation-scope.
            //TeamSpecificConversationState conversationState = new TeamSpecificConversationState(dataStore);
            //builder.RegisterInstance(conversationState).As<TeamSpecificConversationState>().SingleInstance();
            var conversationState = new ConversationState(dataStore);

            //// Drop all activites not received from Microsoft Teams channel.
            //builder.RegisterType<DropNonTeamsActivitiesMiddleware>().As<IMiddleware>().SingleInstance();

            //// For TeamContext object, Add Teams Middleware
            //builder.Register(c => new TeamsMiddleware(
            //   new ConfigurationCredentialProvider())).As<IMiddleware>().SingleInstance();

            //// Automatically drop all non Team messages.
            //builder.RegisterType<DropChatActivitiesMiddleware>().As<IMiddleware>().SingleInstance();

            builder.RegisterInstance(conversationState).As<ConversationState>().SingleInstance();

            // Register the NextLabsBot as the IBot interface
            builder.RegisterType<myBot>().As<IBot>();

            var container = builder.Build();
            var resolver = new AutofacWebApiDependencyResolver(container);
            config.DependencyResolver = resolver;
        }
    }

the code uncommented can work as the common bot, it comes from MS.
the code commented by '//' is my attempt but it cannot work.
the code commented by '////' is SDK usages and some notes on my thought.
What can be done to complete it. Thanks!

A: Don't register bot and inject middleware via AddBot.
You should inject your own IBot (which you are already doing) and add middleware through the adapter.
Here is a correct example.
It's dotnet core however as long as you are using the V4 SDK the pattern should be the same. The example from the official github seems outdated.
For more info, see my discussion with them on github.


text:
Q: Unable to Upgrade A Recipe for a Meta-Layer in Yocto Krogoth I have a layer meta-canboat which has a recipe canboat_1.0.0.bb in it.
I am using the krogoth version for Yocto.
When I tried using devtool in my upgrade workflow as follows:
devtool upgrade canboat --version 1.2.0

I get the following error:
Parsing recipes..done.
NOTE: Fetching canboat...
NOTE: Unpacking...
NOTE: Patching...
NOTE: Unpacking /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/build/downloads/v1.2.0.tar.gz to /tmp/devtoolXfphO2/
WARNING: Command 'git rebase 04c3c274b585bb2c53ce8cc70930867b091a3c5f' failed:
First, rewinding head to replay your work on top of it...
Applying: Non-root user in Makefile
error: Failed to merge in the changes.
Using index info to reconstruct a base tree...
M       Makefile
Falling back to patching base and 3-way merge...
Auto-merging Makefile
CONFLICT (content): Merge conflict in Makefile
Patch failed at 0001 Non-root user in Makefile
The copy of the patch that failed is found in: .git/rebase-apply/patch

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".

Traceback (most recent call last):
  File "/home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/scripts/devtool", line 342, in <module>
    ret = main()
  File "/home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/scripts/devtool", line 329, in main
    ret = args.func(args, config, basepath, workspace)
  File "/home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/scripts/lib/devtool/upgrade.py", line 349, in upgrade
    rf = _create_new_recipe(args.version, md5, sha256, args.srcrev, args.srcbranch, config.workspace_path, tinfoil, rd)
  File "/home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/scripts/lib/devtool/upgrade.py", line 262, in _create_new_recipe
    fullpath = _rename_recipe_files(origpath, bpn, oldpv, newpv, path)
  File "/home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/scripts/lib/devtool/upgrade.py", line 98, in _rename_recipe_files
    return _rename_recipe_file(oldrecipe, bpn, oldpv, newpv, path)
  File "/home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/scripts/lib/devtool/upgrade.py", line 91, in _rename_recipe_file
    shutil.move(os.path.join(path, oldrecipe), os.path.join(path, newrecipe))
  File "/usr/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/usr/lib/python2.7/shutil.py", line 130, in copy2
    copyfile(src, dst)
  File "/usr/lib/python2.7/shutil.py", line 82, in copyfile
    with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: '/home/des/Yocto/PHYTEC_BSPs/yocto_fsl/build/workspace/recipes/canboat/canboat_1.0.0.bb'

Strange enough the workspace directory only the files/ folder with pre-existing patches already in the layer.
The layer is already added:
layer                 path                                      priority
==========================================================================
meta                  /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/meta  5
meta-poky             /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/meta-poky  5
meta-oe               /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-openembedded/meta-oe  6
meta-networking       /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-openembedded/meta-networking  5
meta-python           /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-openembedded/meta-python  7
meta-multimedia       /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-openembedded/meta-multimedia  6
meta-ruby             /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-openembedded/meta-ruby  7
workspace             /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/build/workspace  99
meta-phytec           /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-phytec  20
meta-qt5              /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-qt5  7
meta-yogurt           /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-yogurt  10
meta-UMG              /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-UMG  6
meta-canboat          /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-canboat  6
meta-influx           /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-influx  6
meta-go               /home/des/Yocto/PHYTEC_BSPs/yocto_fsl/sources/poky/../meta-go  1

What is going wrong here? How do I upgrade the recipe if not via devtool?

A: Krogoth Workflow
As mentioned by @danlor and @Nayfe I created a patch for the updated Makefile in the Source Tree.

*

*I added the source tree repository using:
devtool add canboat https://github.com/canboat/canboat.git

it should create workspace/sources/canboat in the build folder

*I created a patch using the following:
# edit the Makefile using your editor (same change as the previous patch)
git add Makefile
git commit -m "Add non root user to new Makefile"
git format-patch -1 -o ../sources/meta-canboat/recipes-support/canboat/files/

*In the sources/meta-canboat I removed the old v.1.0.0 recipe and added the new v1.2.1 recipe and refactored the patch file.

*Bumped the version to v1.0.0 -> v1.2.1 and pushed to code to the meta-canboat


text:
Q: interpolating categorical data in python? (nearest / previous value) How would one interpolate categorical (non-float, or in more broad sense, non-numerical) data in python?
Test data
Here is an example dataset with string-valued y-values.
x = [1.4, 2.8, 3.1, 4.4, 5.2]
y = ['A', 'B', 'A', 'A', 'B']

Expected outputs
# with kind= 'nearest'
x_new = [1, 2, 3, 4, 5]
y_new = ['A', 'A', 'A', 'A', 'B']

# with kind= 'previous', fill_value = None
x_new = [1, 2, 3, 4, 5]
y_new = [None, 'A', 'B', 'A', 'A']

I was expecting that interp1d could do the job with kind='nearest' or kind='previous', but unfortunately that is not the case.

A: You can still use interp1d if you replace your target points with indicies. I.e. construct list of all unique values - in your case it will be ['A', 'B'], transition y to be indicies instead of strings (indicies converted to float - you will be ok as long as number of unique elements can be stored as float without losing precision).
After interpolating you'll just need to get back elements given result of interpolation. As long as you use 'previous' or 'nearest' you'll always get floating point value which is one of your original indicies.
UPD.
Even simpler version would be to use y_int = [float(i) for i in range(len(y))], as input for interp1d, then after you got your interpolation result just use it as index of y.
Example: kind='nearest'
from scipy.interpolate import interp1d
import numpy as np

x = [1.4, 2.8, 3.1, 4.4, 5.2]
y = ['A', 'B', 'A', 'A', 'B']

f = interp1d(x, range(len(y)), kind='nearest', fill_value=(0, len(y)-1), bounds_error=False)
y_idx = f(x_new)
y_new = [y[int(i)] for i in y_idx ]
# ['A', 'A', 'A', 'A', 'B']

Example: kind='previous'
from scipy.interpolate import interp1d
import numpy as np

x = [1.4, 2.8, 3.1, 4.4, 5.2]
y = ['A', 'B', 'A', 'A', 'B']
f = interp1d(x, range(len(y)), kind='previous', fill_value=-1, bounds_error=False)
y_idx = f(x_new)
y_new = [y[int(i)] if i != -1 else None for i in y_idx]
# [None, 'A', 'B', 'A', 'A']


text:
Q: Elasticsearch - incorrect aggregation result I am trying to get the max value of one field on elastic-search 2.4.1, but it different to the actual one.
Looks like ES is doing approximate aggregation, but not sure whether maximum will have the error.
When execute
POST http://192.168.100.211:9200/bt211/_search
{
  "size": 0,
  "query": {
    "match_all": {}
  },
  "aggs": {
    "grades_stats": {
      "max": {
        "field": "4999"
      }
    }
  }
}

Got
{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 245831,
    "max_score": 0,
    "hits": [ ]
  },
  "aggregations": {
    "grades_stats": {
      "value": 4746809856
    }
  }
}

But if I query one specified doc
POST http://192.168.100.223:9200/bt211/_search
{
      "_source": [
        "4999"
      ],
      "query": {
        "terms": {
          "_id": [
            "AV5fg6y-7V3dJ49T89qT"
          ]
        }
      }
    }

It will response
{
  "took": 238,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "bt211201709082",
        "_type": "test",
        "_id": "AV5fg6y-7V3dJ49T89qT",
        "_score": 1,
        "_source": {
          "4999": 4746809900
       }
     }
   ]
  }
}

The value of "4999" is 4746809900, which is bigger than the result of "max" aggregation.
Is there any way to get the accurate result for max in Elasticsearch?


text:
Q: IIS 8 - Domain and URL rewrite I am trying to rewrite domain and URL of request so when user goes to URL:
http://somedomain.com/
he sees content of:
https://serverdomain.com/applications/somedomain/
Of course, anything that is appended to somedomain.com/ should also be appended to applications/somedomain/
I installed ARR 3 and Failed Request Logging, but I can't get to this result. Moreover, after installing ARR, 404 errors start throwing 502.2.
The best rule I got was:
<rule name="test-domain" stopProcessing="true">
    <match url=".*" />
    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="somedomain.com" />
    </conditions>
    <action type="Rewrite" url="https://serverdomain.com/applications/somedomain{R:0}" logRewrittenUrl="true" />
</rule>

It almost works, but I don't know why it takes me to home page (e.g. https://serverdomain.com/).
When I set action type to Redirect it looks OK, but I need this rewrited, so user sees original URL.


text:
Q: Can I share an ignore file between mercurial and git? I use both mercurial and git for similar types of work, and maintain parallel global ignore files. Now, the basic syntax for the two systems is sufficiently similar that I can almost use the same ignore file for both systems. But not quite.

*

*git uses (extended) globs to specify ignore patterns.

*hg uses either full regular expressions (the default) or extended globs to specify ignore patterns. There is a way to specify which system to use.
So to use the same list of globs for both systems, my hg ignore file needs to include a line declaring that the glob syntax is in effect:
syntax: glob
# Compilation artifacts
*.o

This syntax declaration is not recognized by git (which doesn't need one, since it only accepts the glob syntax). I have tried it out and confirmed that it's treated as just another filename: if I create a file called syntax: glob (with a space in the name), git ignores it. This seems harmless but ugly. So: Is there a way to construct a file of ignore patterns that is valid for both systems, without this little wart?


text:
Q: Actual class of object reference Given three classes A, B, and C, where B is a subclass of A, and C is a subclass of B.
(a) (o instanceof B) && (!(o instanceof A))
(b) (o instanceof B) && (!(o instanceof C))
(c) !((o instanceof A) || (o instanceof B))
(d) (o instanceof B)
(e) (o instanceof B) && !((o instanceof A) || (o instanceof C))

Question: Which option is true only when an object denoted by reference o has actually been instantiated from class B?
Note: I am unable to understand the question. Even though the object is instantiated from B, we can instantiate objects from any of the classes A, B or C.
What is the question exactly trying to state?

A: Since this is clearly a homework exercise, it is not appropriate for me to provide an answer directly. Instead, I have written a little program for you to demonstrate what the question means, and running it will provide an answer.
You can try this out for yourself:
public class Main {

  class A {}
  class B extends A {}
  class C extends B {}

  public static void main(String[] args) {
    new Main().experiment();
  }

  private void experiment() {
    Object o = new B();

    boolean a = (o instanceof B) && (!(o instanceof A));
    boolean b = (o instanceof B) && (!(o instanceof C));
    boolean c = !((o instanceof A) || (o instanceof B));
    boolean d = (o instanceof B);
    boolean e = (o instanceof B) && !((o instanceof A) || (o instanceof C));

    System.out.println("a = "+a);
    System.out.println("b = "+b);
    System.out.println("c = "+c);
    System.out.println("d = "+d);
    System.out.println("e = "+e);
  }

}

A: If you do not understand instanceof, read this.
The example provided explains what you are asking quite clearly.

*

*Is a superclass an instanceof a subclass? No

*Is a subclass an instanceof a superclass? Yes

From the question, you know the relationships between A, B, C.
Since o 's actual class is B, you should be able to answer those questions with the given information.


text:
Q: SharePoint Quick Part Label Stopped Working We are currently migrating our EDMS into SharePoint. As part of this workstream, I recently set up a SharePoint site with a Quick Part Label containing just the version number - as per the instructions here.
This worked fine in testing, now a few users have been added to the site and the migration works have begun. The option for "Label" within Quick Parts has simply dissapeared.
I tried some trouble shooting on Friday and found the following:

*

*Recovering an old document from the recycle bin, still contain a correct version number label.

*This label can be copy and pasted to a new document, and it correct applies the label quick part with the new documents version.

*I set up a new test site and the Quick Part Label behaved exactly as expected, meaning the issue is within the Live SharePoint site itself.

*I turned off labels and reset them. With no success.

I am opening in the app, the library has minor versions, check-in/check-out turned on (and currently approvals are turned off).
I also suspected that OneDrive sync might cause issues, but this again didn't seem to solve anything in the test site.
NB: this is also posted here, I will keep both threads up to date.
Screenshot showing label missing
Update 20/12/22
Since this morning I have now taken the following additional steps:

*

*Added a new content type

*Recreated the label for that content type

*Change the content type of the document in the library, and the label
option now appears

*This seems like a fix, but I am also curious as to limitations of
this method.

*Limitations noticed so far: cannot edit SharePoint columns in the
details pane


text:
Q: Can a Gyroscope be Used to Stop a Spinning Cable? The scenario here is a helicopter attempting to hoist someone vertically into the air. When the person leaves the ground they begin to spin (sometimes slowly, other times quite fast if not stabilized by a guide rope or something of a similar nature).
Would it be possible to have a gyroscope attached to the bottom end of the cable (near the hook that attaches to the person/load) that is able to prevent the cable and/or the person from spinning as it is hoisted up?
If possible, how would one calculate the quantities associated with sizing a gyroscope for such a task?

A: A gyroscope is not suitable. Maybe a reaction wheel could be an idea.
To explain why a gyroscope would not be suitable let me describe a situation where gyros work well: stabilizing a ship.
In the luxury yacht market you see usage of a design called control moment gyroscope.
Depending on the orientation of the ship with respect to the waves the ship will tend to have rolling motion. In order to exert a force a control moment gyroscope must have some leverage. On a yacht that is achieved as follows. When the control motion gyro counters roll to the right the bow of the ship is pushed down; when the control motion gyro counters roll to the right the stern of the ship is pushed down. (Or vice versa, depending on direction of gyro spin.) On a ship that pitching effect is negligably small; a ship is far more stable around its pitch axis than around its roll axis simply because a ship is longer than it is wide.
Going back to the case of hoisting up to a helicopter:
A single gyroscope can counteract tendency to spin, but you end up trading one problem for another.
Incidentally, another option, I suppose, is to outfit the basket with a small rotor, a rotor like the tail rotor of the helicopter itself. As with a reaction wheel design the basket tail rotor would have to be controlled by a sensor that senses that the basket starts spinning.
A reaction wheel design will probably be heavier than a basket tail rotor design.
Also this:
Let's say that the wash of the helicopter does tend to make the basket spin. That is a continuous torque. To counteract that for an extended time the reaction wheel would have to keep increasing its angular velocity. Pretty soon the reaction wheel will max out, and then you have a fast spinning wheel on your hand. When the rescuers start handling the basket they will then have to deal with the counter-intuitive gyroscopic effect of the reaction wheel.
Conversely, with a basket tail rotor design: when the basket no longer tends to spin the basket tail rotor also stops doing anything.


text:
Q: Independence of the sum of two dice given one of them is odd the result I'm not sure how to argue this.
Two fair dice, one red and one blue are rolled.
Let $A$ be the event that the number rolled on the red die is odd.
Let $B$ be the event that the number rolled on the blue die is odd.
Let $C$ be the event that the sum of the two dice is odd.
Show that $B$ and $C$ are independent.
It's obvious that $A$ & $B$ are independent
I tried
$$P(C \mid B) = P(\text{Die Red + Die Blue is odd} \mid B) = \frac{P(\text{Die Red + Die Blue is odd} \cap B)}{P( B )}$$
If $B$ is odd, Die Red should be Even. Therefore, the sum will be Odd.
$$\frac{P(A^{c}B)}{P(B)} = \frac{P(A^{c})P(B)}{P(B)}= \frac{1}{2}$$
If someone has a suggestion, I would really appreciate that.

A: The sum of the die is odd if one die is odd and the other is even.
Then the event of the red die being odd and the sum being odd, is the same event as the red die being odd and the blue die being even.   And such.
Thus $(A \cap C) = (A\cap B^\complement)$ and $(B\cap C)=(B\cap A^\complement)$.
So...

Hint: $\mathsf P(A) = \mathsf P(A\cap B)+\mathsf P(A\cap B^\complement)$ by the Law of Total Probability