text:
Q: C# - Websocket - Sending Message Back To Client I've been working on a C# Web Socket server for roughly 24 hours.
I've currently figured out how to complete a handshake and get the connection initialized.
Also I've figured out how to take the byte[] data and decode it into a it's original string.
But now I'm stuck and looking for help.
I can't seem to figure out how to put together a proper data structure and send it back to the client.
If you send the original data you received the WebSocket on the client-side will tell you the data cannot be masked (which is why it needs to be decoded).
So basically, what I'm asking in short is how do I structure response data to send back to the WebSocket client?
I've been using https://www.rfc-editor.org/rfc/rfc6455 as a resource for my research.
Please keep in mind that I'm just using a regular socket for this.
Here is my decode code:
if (dataBuffer.Length > 0)
{
    if (dataBuffer[0] == 129)
    {
        int msg_length = dataBuffer[1] - 128;
        if (msg_length <= 125)
        {
            // Msg ready to decode.
            Log.info("Message Length: " + msg_length);

            Byte[] decoded = new Byte[dataBuffer.Length];
            Byte[] encoded = new Byte[dataBuffer.Length - 6];

            Array.Copy(dataBuffer, 6, encoded, 0, msg_length);

            Byte[] key = new Byte[4] { dataBuffer[2], dataBuffer[3], dataBuffer[4], dataBuffer[5] };
            for (int i = 0; i < encoded.Length; i++)
            {
                decoded[i] = (Byte)(encoded[i] ^ key[i % 4]);
            }

            Log.info("MSG: " + Encoding.UTF8.GetString(decoded));

            byte[] return_msg = new byte[decoded.Length + 8];

            return_msg[0] = 1;
            return_msg[1] = 0;
            return_msg[2] = 0;
            return_msg[3] = 0;
            // OP Code
            return_msg[4] = 0x1;
            return_msg[5] = 0x0;
            return_msg[6] = 0x0;
            return_msg[7] = 0x0;

            Array.Copy(decoded, 0, return_msg, 8, decoded.Length);

            socket.Send(return_msg);
        }
        else if (msg_length == 126)
        {
            // Longer Message
            msg_length = dataBuffer[2] + dataBuffer[3];

            Log.info("Message Length: " + msg_length);

            Byte[] key = new Byte[4] { dataBuffer[4], dataBuffer[5], dataBuffer[6], dataBuffer[7] };

            Byte[] decoded = new Byte[dataBuffer.Length];
            Byte[] encoded = new Byte[dataBuffer.Length - 8];

            Array.Copy(dataBuffer, 8, encoded, 0, msg_length);

            for (int i = 0; i < encoded.Length; i++)
            {
                decoded[i] = (Byte)(encoded[i] ^ key[i % 4]);
            }

            Log.info("MSG: " + Encoding.UTF8.GetString(decoded));
            byte[] return_msg = new byte[decoded.Length + 4];

            return_msg[0] = 129;
            return_msg[1] = 0;
            return_msg[2] = 0;
            return_msg[3] = 0;

            Array.Copy(decoded,0,return_msg,4,decoded.Length);

            socket.Send(return_msg);
        }
        else if (msg_length == 127)
        {
            // Huge Message:
            Log.info("BIG MESSAGE");
        }
    }

}

A: @vtortola Thank you for posting the links and explanation - I spent a bunch of time studying that and an open source code base (to write my own essentially) and I distilled it down to this for sending a message from the server to the client.
The key, for me, was realizing a couple of things:
First, understand the header.  GetHeader() takes care of whether or not its the final frame and whether or not the opcode is set to text of continuation frame.  The link @vtortola posted explains it, but I had to really stare at it before I saw the bits:
This post actually explains it decently, but you have to take time and study it - take note of how the FIN and opcode bits match GetHeader()'s job:

*

*Client: FIN=1, opcode=0x1, msg="hello" <-- this is a single message, length <= 125

*Server: (process complete message immediately) Hi.

*Client: FIN=0, opcode=0x1, msg="and a" <-- begin multi-frame message, length > 125

*Server: (listening, new message containing text started)

*Client: FIN=0, opcode=0x0, msg="happy new" <-- continue multi-frame message

*Server: (listening, payload concatenated to previous message)

*Client: FIN=1, opcode=0x0, msg="year!" <-- end multi-frame message

*Server: (process complete message) Happy new year to you too!

Next, understand what you're sending when you call stream.Write() - bytes[], index, LENGTH OF BYTES YOU'RE SENDING ;)

NOTE: My intent was to send JSON formatted strings to and from the web client, so my opcode is set for text (and my example here is based
  on the assumption you're wanting to send string data), but you can
  send other types as well.

SendMessageToClient() basically splits the message into 125 chunks and creates a que to be pulled from.  Based on where we're at in the que, the header is created with the proper flags for FIN and opcode.  Finally, with the header ready, backfill the rest of the header with the actual length of the chunk of string (<= 125).  Then write the header to the stream after converting it to a byte array.
At this point, your header is created properly (FIN, rsv1,2,3 set properly, opcode and mask as well as the size of the payload).  Now send it.
public void SendMessageToClient(TcpClient client, string msg)
{
    NetworkStream stream = client.GetStream();
    Queue<string> que = new Queue<string>(msg.SplitInGroups(125));
    int len = que.Count;

    while (que.Count > 0)
    {
        var header = GetHeader(
            que.Count > 1 ? false : true,
            que.Count == len ? false : true
        );

        byte[] list = Encoding.UTF8.GetBytes(que.Dequeue());
        header = (header << 7) + list.Length;
        stream.Write(IntToByteArray((ushort)header), 0, 2);
        stream.Write(list, 0, list.Length);
    }
}

protected int GetHeader(bool finalFrame, bool contFrame)
{
    int header = finalFrame ? 1 : 0;//fin: 0 = more frames, 1 = final frame
    header = (header << 1) + 0;//rsv1
    header = (header << 1) + 0;//rsv2
    header = (header << 1) + 0;//rsv3
    header = (header << 4) + (contFrame ? 0 : 1);//opcode : 0 = continuation frame, 1 = text
    header = (header << 1) + 0;//mask: server -> client = no mask

    return header;
}

protected byte[] IntToByteArray(ushort value)
{
    var ary = BitConverter.GetBytes(value);
    if (BitConverter.IsLittleEndian)
    {
        Array.Reverse(ary);
    }

    return ary;
}

/// ================= [ extension class ]==============>

public static class XLExtensions
{
    public static IEnumerable<string> SplitInGroups(this string original, int size)
    {
        var p = 0;
        var l = original.Length;
        while (l - p > size)
        {
            yield return original.Substring(p, size);
            p += size;
        }
        yield return original.Substring(p);
    }
}

Along with the post above, I studied websocket-sharp's code base.  I literally wanted to learn how to do this and write my own server/client and was able to do so studying that code base as well as a great starting point here for creating a basic c# WebSocket server.
Finally, I thank God for the patience to read through all of this ;)

A: Take a look to this two articles about writing C# WebSocket servers:
https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_servers
https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_server
It seems like they are both the same article, but they are not! In this part of the first link you have the explanation about how to build frames.
UPDATE
The first byte contains several information:

*

*FIN :Indicates that the frame contains a complete message.

*RSV1: Option 1

*RSV2: Option 2

*RSV3: Option 3

*OptCode: Indicates the type of frame.

If you want to send a Text message smaller than 125 bytes, lets say your message has 90 bytes, in the first byte you will put the bit 0 to 1(more significant), the next 3 to 0, unless you want to enable options, and the next 4 would be 0001, indicating a Text frame. So your first bye would be 10000001, or 129.
Now in the second byte, the first bit indicates if the frame is masked. You don't mask frames from server to client, so you set a 0. The next 7 bits indicates rather the length, or the type of frame length. Because you are sending a small frame, you can indicate any value up to 125 in those 7 bits. So because the frame length is 90 bytes, the second byte of the header would be 01011010, or 90.
So when sending from server to client a Text frame of 90 byes, the first two bytes conforming the header would be 129 and 90. The rest of the message would be 90 bytes of UTF8 encoded bytes.
If the frame is longer than 125 bytes, also is the length of the header, check the spec. If the frame need to be masked (like the frames you get from the client), the first 4 bytes of the body contain the masking key. As you see there are some tidbits to cope with, so I recommend you to read the spec : https://www.rfc-editor.org/rfc/rfc6455

A: Here is how to encode the message for length < 125 AND for 126 and less then 65535,
Just pass the string to the method, and it will return array of byte[]:
    private byte[] encodeMessage(string msg)
    {
        int msgLength = msg.Length;
        byte[] msgEncoded = new byte[msgLength + 5];
        int indexAt = 0;

        msgEncoded[0] = 0x81;
        indexAt++;

        if (msgLength <= 125)
        {
            msgEncoded[1] = (byte)msgLength;
            indexAt++;
        } else if (msgLength >= 126 && msgLength <= 65535)
        {
            msgEncoded[1] = 126;
            msgEncoded[2] = (byte)((byte)msgLength >> 8);
            msgEncoded[3] = (byte)msgLength;
            indexAt += 3;
        }

        for (int i = 0; i < msgLength; i++)
        {
            msgEncoded[indexAt + i] = (byte)msg[i];
        }
        return msgEncoded;
    }


text:
Q: ServiceStack 6 /api path causes error for all services I have an self-hosted application written originally using ServiceStack 3.x, where I had dozens of APIs with a route starting with /api
Upon licensing ServiceStack 6, all routes starting with /api are failing with the following error:
"ErrorCode":"NotImplementedException","Message":"The operation 'bu' does not exist for this service"

where the last element in the path is shown as the operation name.
I modified one service to route as:
[Route("/api/hcm/bu")]
[Route("/api/bu")]
[Route("/access/hcm/bu")]

The ones starting with /api fail.  The one starting with /access works perfectly.
These are published APIs, so I really do not want to change them all.
I am guessing the new automatic /api pathways in the newer version of ServiceStack are interfering, but I cannot find any documentation on how to suppress them or work around this.
How can I make the legacy /api path services work again under current ServiceStack?

A: You can disable the API Route with:
ConfigurePlugin<PredefinedRoutesFeature>(feature => feature.JsonApiRoute = null);

redpajama_set_name: RedPajamaStackExchange


text:
Q: check if value in textbox is valid I have a textbox with a validator that permits only integer values. How do I check if text in my textbox represents a correct integer value without checking the text itself?
I am using Prism MVVM so I would like to hear some solution like "bind a validator property to your viewmodel/model code", but a generic WPF solution is also fine.
The problem is that I can't get the incorrect value in my model / viewmodel. If the value is incorrect, then the underlying binded property doesn't get set.

A: You could use IDataErrorInfo, or Data Annotations. The Data Annotations Extensions project contains an Integer attribute.


text:
Q: Import globally used library module into angular project modules I think I did something wrong here.
I want to use angular-fontawesome module. Following the instructions to import it into AppModule successfully.
export class AppModule {
constructor(library: FaIconLibrary) {
    // Add an icon to the library for convenient access in other components
    library.addIcons(
        faUsers,
        faUserCircle,
        faDesktop,
        faTachometerAlt,
        faWrench,
        faFolder,
        faChartArea,
        faTable,
        faSearch,
        faBell,
        faFileAlt,
        faExclamationTriangle,
        faDonate,
        faEnvelope,
        faUser,
        faCogs,
        faList,
        faSignOutAlt,
        faAngleUp,
        faLaughWink,
        faServer,
        faWarehouse,
        faPlusCircle
    )
}

But when I want to  use it in my own in-project module, say admin.module.ts. I have to import all  that again? The same code have to be placed into admin.module.ts again?
It seems to me. AppModule is the root module. I get that if I have other modules that I want to use icons then I might have to do this. But, really? Even the AppModule is not enough?

A: The FaIconLibrary is an application-level singleton, so you only need to add icons to the library once. However you should add FontAwesomeModule to imports of your AdminModule to make <fa-icon> component accessible to the components declared in the AdminModule (it's a standard Angular thing).
You may also find this answer interesting to read.

A: According to documentation
Icons can be registered once in app.module with FaIconLibrary.addIcons() or FaIconLibrary.addIconPacks(). Icons added to the library will be available to any other components whose parent module also imports FontAwesomeModule.
So re check next steps
1   Import { FontAwesomeModule, FaIconLibrary } from '@fortawesome/angular-fontawesome'
2   Add FontAwesomeModule to imports
3   Inject FaIconLibrary into constructor of the module.
4   Import an icon like { faCoffee } from '@fortawesome/free-solid-svg-icons'
5   Add icon to the library with library.addIcons(faCoffee)


text:
Q: Integer comparision using DBD::SQLite I'm facing a problem with DBIx::Class against an SQLite3 database.
If you don't want to read the following in full, here's the TL;DR version:

Is there a way to force DBD::SQLite to treat integer fields as being unsigned, when it comes to comparisons?

The table definition is here:
sqlite> PRAGMA table_info(entry);
0|entry_key|INTEGER|1||1
1|node|varchar(256)|1||0
2|object_type|varchar(128)|1||0
3|object_id|int|1||0
4|copy_id|tinyint|0||0
5|seq_number|int|1||0
6|root_seq_number|int|1||0
7|first_error|int|1||0
8|last_error|int|1||0
9|error_count|int|1||0
10|error_id|int|1||0
11|error_code|int|0||0
12|status|varchar(64)|1||0
13|type|varchar(64)|1||0
14|sense|char(256)|0||0

The fields of interest are first_error and last_error. These fields contain epoch time values. Thus, they are 32-bit numbers, but they are less than 2147483647
In my code, I have the following:
my @entries =  $self->{row}->search_related_rs('eventlog_entries')
                           ->search_related('entry', {
                             first_error => {'>', $range->{start}},
                             last_error  => {'<', $range->{end}},
                           }
           )->all();

start is set to 0; end is set to 2**32 - 1
When run with DBI_TRACE=1, I get:
<- prepare_cached('SELECT entry.entry_key, entry.node, entry.object_type,
                   entry.object_id, entry.copy_id, entry.seq_number,
                   entry.root_seq_number, entry.first_error, entry.last_error,
                   entry.error_count, entry.error_id, entry.error_code, entry.status,
                   entry.type, entry.sense FROM eventlog_entry me  JOIN entry entry ON
                   entry.entry_key = me.entry_key WHERE ( ( ( first_error > ? AND
                     last_error < ? ) AND me.eventlog_key = ? ) )',
                  HASH(0x2472b54), ...)= ( DBI::st=HASH(0x2442efc) ) [1 items]
   at DBI.pm line 2245
<- bind_param(1, 0, ...)= ( 1 ) [1 items] at DBI.pm line 1574
<- bind_param(2, '4294967295', ...)= ( 1 ) [1 items] at DBI.pm line 1574
<- bind_param(3, 1, ...)= ( 1 ) [1 items] at DBI.pm line 1574
<- execute= ( '0E0' ) [1 items] at DBI.pm line 1586
<- fetchall_arrayref= ( [ ] ) [1 items] row-1 at Cursor.pm line 133

In this case, @entries is an empty array.
On the other hand, if I set end is set to 2**31 - 1, everything works.
My hyopthesis is this:
SQLite fields have an 'affinity', which means that the fields are recognised as integers, but they have no native size. Thus, SQLite "guesses" what the size is, based on the contents of the field. Since the value in the last_error field is less than 2147483647, but greater than 16777215, I'm guessing that SQLite is treating the field as a SIGNED INTEGER (i.e. signed 32-bit number).
As such, my guess is that, when the bind_param takes place, some kind of inspection is done, which results in DBI identifying last_error as a SIGNED INTEGER. As a result, the value of 4294967295 overflows, or gets squished to zero, or something like that, and the comparison works incorrectly.
Thus, my question(s):

*

*Is this hypothesis correct (according to some documentation that I've overlooked)? or

*Is there a way to confirm this hypothesis?

*Is this a bug, or is there a sensible workaround, bearing in mind that I'm using DBIx::Class, so I'm somewhat abstracted away from the database.

A: How about using literal sql in your query:
my $cond = " < $range->{end} ";

my @entries =  $self->{row}->search_related_rs('eventlog_entries')
                       ->search_related('entry', {
                         first_error => {'>', $range->{start}},
                         last_error  => \$cond,
                       }
       )->all();

Should work if perl stringifies $range->[end} as a positive number.


text:
Q: How to convert a string to integer so i can XOR it with another integer in python I have two files msg.log and key.log which the first file contains a plain text Hello World! and the key.log contains a string which is hex 95274DE03C78B0BDEDFBEB0D, I want to do a bitwise XOR between these two files, but first file msg.log needs to be converted to ASCII first.
I have this code:
#!/usr/bin/python3

def main():
    with open ("msg.log", "r") as myfile1:
        a=myfile1.read()
    with open ("key.log", "r") as myfile2:
        b=myfile2.read()
    rr=convert_to_ascii(a)

    xored = xor_strings(a, b)
    print(xored)

def convert_to_ascii(text):
    return "".join(format(ord(char),"x") for char in text)
def xor_strings(xs, ys):
    return "".join(format(ord(x)^y) for x, y in zip(xs, ys))

if __name__ == "__main__": main()

and I get the error that int and str can not be XOR-ed, i tried to use int(y,base=16) function but it changes the values, while i just want to change the type and not a conversion of values in bases. what could be the solution?

A: You need to ord the second string. As pointed out in the comments, this is not the output you want. You need to convert the hex string into integer and then your xor will work.
#!/usr/bin/python3

def main():
    with open ("msg.log", "r") as myfile1:
        a=myfile1.read()
    with open ("key.log", "r") as myfile2:
        b=myfile2.read()
    rr=convert_to_ascii(a)

    xored = xor_strings(a, b)
    print(xored)

def convert_to_ascii(text):
    return "".join(format(ord(char),"x") for char in text)
def xor_strings(xs, ys):
    intlist = [int(ys[i:i+2], base=16) for i in range(0,len(ys),2)]
    return "".join(format(ord(x)^y) for x, y in zip(xs, intlist))

if __name__ == "__main__": main()

A: you are confused about numbers vs their representations
hex_str = "ABC123"
int_value = int(hex_str,16)
xor_value = int_value ^ xor_with_me
print hex(xor_value)

you may want to take it in bytes to xor it (its not clear from the question)
hex_str = "ABC123"
bytes_str = binascii.unhexlify(hex_str) # becomes "\xab\xc1\x23"
byte_values = [ord(x)^xor_with_me for x in bytes_str]
xored_bytes = "".join(chr(x) for x in byte_values)
print binascii.hexlify(xored_bytes)


text:
Q: OpenJPA criteriaBuilder nested object property fetch Is there any way in OpenJPA to get hold of a nested object property via CriteriaBuilder?
Here's a small case.
@Entity
public class X {
       private Object Y;

       // getters, setters...
}

@Entity
public class Y {
       private String Z;

       // getters, setters...
}

So, when using CriteriaBuilder, we use X as Root, i.e.:
@PersistenceContext
private EntityManager entityManager;

//.....

Root<X> rootObj = criteriaBuilder.from(X.class);
CriteriaQuery<X> select;

String param1 = X.getY().getZ();

// initializing predicate, default value is TRUE
Predicate predicate1 = criteriaBuilder.isNull(null);

// construct search predicate which fails miserably due to IllegalArgumentExecption
if (X != null) {
    predicate1 = criteriaBuilder.and(predicate1, criteriaBuilder.equal(rootObj.<String> get("Y.Z"), param1));
}

Now, my grief is this -> get("Y.Z")
CriteriaBuilder doesn't know to fetch Z reflectively (however it can and will resolve Y). Is there any way to get hold of Z directly from get()?
Apart from using JPQL, I can think of one other method - which I dislike immensely: I suppose I could have exposed Z as an @Transient property in X (as to prevent OpenJPA from persisting it as a column), but that sounds like a Really Bad Idea: I am essentially flattening out an object graph manually and introduce unneeded garbage inside the entity bean, not counting the time needed to flatten out a complex graph or the error-proness of this (it can go awry in so many ways).
Is there a way to make this work? Any ideas are appreciated.

A: Heh, the solution is suprisingly simple - and it looks really ugly, but it works.
predicate1 = criteriaBuilder.and(predicate1, criteriaBuilder.equal(rootObj.get("Y").<String> get("Z"), param1));}

I really don't know if there is a more elegant solution to this.

A: For any arbitrary nested attribute path ("relation.subRelation.attribute"):
private Path<T> getPath(Root<T> root, String attributeName) {
    Path<T> path = root;
    for (String part : attributeName.split("\\.")) {
        path = path.get(part);
    }
    return path;
}


text:
Q: How to clear all data in datagridview and it would not effect in delete data How do I clear all data and not delete data or column in datagridview? I want to clear the data first and query on the result to make the result not duplicate.

A: I'm not sure that I understand what you asked, but yet -
Clearing all rows from DataGridView is very simple:
dataGridView1.Rows.Clear();

Regarding the query duplicates, you can use SELECT DISTINCT.
And another thing: I hope your code is only a simplified example, because it is highly exposed to SQL injections.

A: If you are binding your DataGridView through code that is, using DataSource property you can clear DataGridView using the following code.
dataGridView1.DataSource=null;
It will not delete data from your database,just clear your DataGridView.

A: in vb.net you can use :
datagridview1.Datasource = nothing
but it will empty your datagridview1 and initialize it to default.

A: I had to modify Sujith's to the following:

DataGridView1.DataSource = DBNull.Value

A: If datagrid is bound data you should do:
dataGridView.DataSource = null;
dataGridView.DataSource.Clear();

If datagrid is unbound data no need to null the datasource:
dataGridView.DataSource.Clear();

Another trick is:
 dt.Columns.Clear();
 dt.Rows.Clear();
 dataGridView.DataSource = dt;

A: If you want to make sure that it will clear all the states, then the following code can be used:
dataGridView.CancelEdit()
dataGridView.Columns.Clear()
dataGridView.DataSource = Nothing
dataGridView.Rows.Clear()


text:
Q: Tengo el siguiente error. ¿Alguien sabe cuál es el problema?
jm-boilerplate@1.0.0 start /home/frank/Globall66-Projects/Growth-Projects/g66-web
   gulp
[14:30:36] Requiring external module @babel/register
  /home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:178
      throw new Error(Plugin/Preset files are not allowed to export objects, only functions. In ${filepath});
      ^
Error: Plugin/Preset files are not allowed to export objects, only
  functions. In
  /home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/babel-preset-es2015/lib/index.js
      at createDescriptor (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:178:11)
      at items.map (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:109:50)
      at Array.map ()
      at createDescriptors (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
      at createPresetDescriptors (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:101:10)
      at presets (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:47:19)
      at mergeChainOpts (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-chain.js:320:26)
      at /home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-chain.js:283:7
      at buildRootChain (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-chain.js:120:22)
      at loadPrivatePartialConfig (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/partial.js:85:55)
  npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR!
  jm-boilerplate@1.0.0 start: gulp npm ERR! Exit status 1 npm ERR!
  npm ERR! Failed at the jm-boilerplate@1.0.0 start script. npm ERR!
  This is probably not a problem with npm. There is likely additional
  logging output above.
npm ERR! A complete log of this run can be found in: npm ERR!
  /home/frank/.npm/_logs/2019-12-23T19_30_36_678Z-debug.log

A:

jm-boilerplate@1.0.0 start /home/frank/Globall66-Projects/Growth-Projects/g66-web
    gulp

[23:26:34] Requiring external module @babel/register
  /home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:178
      throw new Error(Plugin/Preset files are not allowed to export objects, only functions. In ${filepath});
      ^
Error: Plugin/Preset files are not allowed to export objects, only
  functions. In
  /home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/babel-preset-es2015/lib/index.js
      at createDescriptor (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:178:11)
      at items.map (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:109:50)
      at Array.map ()
      at createDescriptors (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
      at createPresetDescriptors (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:101:10)
      at presets (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-descriptors.js:47:19)
      at mergeChainOpts (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-chain.js:320:26)
      at /home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-chain.js:283:7
      at buildRootChain (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/config-chain.js:120:22)
      at loadPrivatePartialConfig (/home/frank/Globall66-Projects/Growth-Projects/g66-web/node_modules/@babel/core/lib/config/partial.js:85:55)
  npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR!
  jm-boilerplate@1.0.0 start: gulp npm ERR! Exit status 1 npm ERR!
  npm ERR! Failed at the jm-boilerplate@1.0.0 start script. npm ERR!
  This is probably not a problem with npm. There is likely additional
  logging output above.
npm ERR! A complete log of this run can be found in: npm ERR!
  /home/frank/.npm/_logs/2019-12-24T04_26_34_620Z-debug.log


text:
Q: animate a queue elements in ng-repeat So I have a controller like so:
var control = angular.module('controllers', []);
control.controller('aboutme', ['$scope',
  function($scope) {
    $scope.tabs = [{
      "title": "interests",
      "list": ["cats", "kittens"]
    }, {
      "title": "hobbies",
      "list": ["petting kittens", "playing with kittens", "writing bad stack overflow questions"]
    }]
  }
]);

Then within my html, I have the following (using angular-directives addon)

{{ i }}

This will effectively make the tabs and list appear on page. However, what I am trying to do is make each animate in series one after the other. Ie, when one finishes animating, animate the next.
How would this be done in angular?

A: First of all. Angular disables animation when it is bootstrapping the page.
From Angular Docs:

... When an application is bootstrapped Angular will disable animations from running to avoid a frenzy of animations from being triggered as soon as the browser has rendered the screen. For this to work, Angular will wait for two digest cycles until enabling animations. From there on, any animation-triggering layout changes in the application will trigger animations as normal.

So animation will only works for new elements added to your list:
1 - Import angular-animate library:

2 - Enable angular animation module
  var control = angular.module('controllers', ['ngAnimate']);

3 - Make the transition using css
  /*
  Enables the transition
  */
.animation-repeat {
    -webkit-transition:5s linear all;
    -moz-transition:5s linear all;
    -o-transition:5s linear all;
    transition:5s linear all;
}

  /*
  Class added when a new element is added to ng-repeat
  */
 .ng-enter {
   opacity: 0;
 }

/*
  The ng-enter-active and ng-move-active
  are where the transition destination properties
  are set so that the animation knows what to
  animate.
*/
.animation-repeat.ng-enter.ng-enter-active,
.animation-repeat.ng-move.ng-move-active {
  opacity:1;
}

But as I said, it will only works for new itens added in ng-repeat. You may use $timeout to delay add the first itens in your page. Here is the Plunker

A: *

*Include 'angular-animate.js' in your html file of your angular project.

*In your controller file, inject ngAnimate dependency as shown below in the controller code.

*Lastly, add the following styles to your css file.

//controller code goes here

angular.module('treeApp.controllers', ['ngAnimate']).
    controller('treeController', function($scope) {
    $scope.ideas=[
    {name:"ABC", top:"70% !important", left: "4% !important"},
    {name:"XYZ", top:"68% !important", left: "3% !important"},
    {name:"123", top:"66% !important", left: "2% !important"}];
    });
 /*css code goes here*/

        .animate-repeat.ng-enter {
        transition: 0.2s linear all;
        opacity:0;
        }
        .animate-repeat.ng-enter-stagger {
        transition-delay: 0.2s;
        transition-duration: 0s;
        }
        .animate-repeat.ng-enter.ng-enter-active {
        opacity:1;
        }

        {{idea.name}}


text:
Q: PHP Multibyte UTF-8 Strings are Slowly Degrading I'm trying to convert the following javascript function to PHP:
function lzw_decode(s) {
    var dict = {};
    var data = (s + "").split("");
    var currChar = data[0];
    var oldPhrase = currChar;
    var out = [currChar];
    var code = 256;
    var phrase;
    debugger;
    for (var i=1; i<data.length; i++) {
        var currCode = data[i].charCodeAt(0);
        if (currCode < 256) {
            phrase = data[i];
        }
        else {
           phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
        }
        out.push(phrase);
        currChar = phrase.charAt(0);
        dict[code] = oldPhrase + currChar;
        code++;
        oldPhrase = phrase;
    }
    return out.join("");
}

This is my converted code:
function uniord($c) {

    $a = unpack('N', mb_convert_encoding($c, 'UCS-4BE', 'UTF-8'));
    return($a[1]);

}

function mb_str_split( $string ) {
    # Split at all position not after the start: ^
    # and not before the end: $
    return preg_split('/(?<!^)(?!$)/u', $string );
}

function decode($s){

    $dict = array();

    $data = mb_str_split($s);

    // print_r($data);

    $currChar = $data[0];
    // echo $currChar;
    // exit();
    $oldPhrase = $currChar;

    $out = array();
    $out[] = $currChar;
    $code = 256;
    $phrase;

    for ($i=1; $i < count($data); $i++) {

        $currCode = uniord($data[$i]);

        if($currCode < 256){
            $phrase = $data[$i];
        }else{
            $phrase = isset($dict[$currCode]) ? $dict[$currCode] : ($oldPhrase . $currChar);
        }

        $out[] = $phrase;

        $currChar = mb_substr($phrase, 0, 1);
        $dict[$code] = $oldPhrase . $currChar;

        $code++;
        $oldPhrase = $phrase;

    }

    return implode("", $out);

}

While this function is working for some LZW encoded strings, if you use a long enough string you can see that it's not 100% accurate. My guess is that it's a problem with multibyte strings and my carelessness. Anyone have any ideas?


text:
Q: How do I concatenate this CSS background image url correctly? I have the following CSS for a banner like image (external CSS file):
.banner {
    background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.5), rgba( 255, 255, 252, 0.8 )), url('banners/imageA.jpg');
}

and I have a function that changes the background image but also uses the parameter for other things.
function bannerchange(element)    {
    document.getElementById('banner').style.backgroundImage = "linear-gradient(to bottom, rgba(255, 255, 255, 0.2), rgba( 255, 255, 255, 0.8 )), url('banners' + element + .jpg\')";
    document.getElementById('bannertext').innerHTML = element;
    document.getElementById('infotext').src = 'infotexts/' + element + '.txt';

I have no trouble setting the new background image by static url
 document.getElementById('banner').style.backgroundImage = "linear-gradient(to bottom, rgba(255, 255, 255, 0.2), rgba( 255, 255, 255, 0.8 )), url(banners/element.jpg)";

However any combination of concatenations I tried fail to load the image correctly with the function parameter, e.g.
url('banners/' + element + '.jpg')";

and variations.
What is the correct way to use this? I give up.

A: Just use double quotes as follows:
document.getElementById('banner').style.backgroundImage = "linear-gradient(to bottom, rgba(255, 255, 255, 0.2), rgba( 255, 255, 255, 0.8 )), url(banners/" + element + ".jpg)";


text:
Q: How do I add a feature that asks user if they would like to play again? Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game
ask_p1 = input("Player 1, Enter rock/paper/scissors: ")
ask_p2 = input("Player 2, Enter rock/paper/scissors: ")

def rock_paper_scissors(p1, p2):
    a_list = ["rock", "paper", "scissors"]

    while p1 == p2:
        print ("Nobody wins. Try again")
        p1 = input("Player 1, Enter rock/paper/scissors: ")
        p2 = input("Player 2, Enter rock/paper/scissors: ")

    if p1 == "rock" and p2 == "paper":
        print ("Player 2 wins!")

    elif p1 == "paper" and p2 == "rock":
        print ("Player 1 wins!")

    elif p1 == "rock" and p2 == "scissors":
        print ("Player 1 wins!")

    elif p1 == "scissors" and p2 == "rock":
        print ("Player 2 wins")

    elif p1 == "paper" and p2 == "scissors":
        print ("Player 2 wins!")

    elif p1 == "scissors" and p2 == "paper":
        print ("Player 1 wins!")

rock_paper_scissors(ask_p1, ask_p2)

A: You can make the function call itself, something like the example below.
ask_p1 = input("Player 1, Enter rock/paper/scissors: ")
ask_p2 = input("Player 2, Enter rock/paper/scissors: ")

def rock_paper_scissors(p1, p2):
    a_list = ["rock", "paper", "scissors"]

    while p1 == p2:
        print ("Nobody wins. Try again")
        p1 = input("Player 1, Enter rock/paper/scissors: ")
        p2 = input("Player 2, Enter rock/paper/scissors: ")

    if p1 == "rock" and p2 == "paper":
        print ("Player 2 wins!")
        user_Input = input("Do you want to play again? Y or N")

    elif p1 == "paper" and p2 == "rock":
        print ("Player 1 wins!")
        user_Input = input("Do you want to play again? Y or N")
    elif p1 == "rock" and p2 == "scissors":
        print ("Player 1 wins!")
        user_Input = input("Do you want to play again? Y or N")
    elif p1 == "scissors" and p2 == "rock":
        print ("Player 2 wins")
        user_Input = input("Do you want to play again? Y or N")
    elif p1 == "paper" and p2 == "scissors":
        print ("Player 2 wins!")
        user_Input = input("Do you want to play again? Y or N")
    elif p1 == "scissors" and p2 == "paper":
        print ("Player 1 wins!")
        user_Input = input("Do you want to play again? Y or N")

rock_paper_scissors(ask_p1, ask_p2)

and then call the function again if you want to play again (put this at the bottom of the function)
if user_Input == 'Y':
   rock_paper_scissors(ask_p1, ask_p2)
else:
#exit or do other end code here

A: Two Options, Call your function in a while loop, or call the function itself recursively.
1: Call the function in a while loop
while True:
    ask_p1 = input("Player 1, Enter rock/paper/scissors: ")
    ask_p2 = input("Player 2, Enter rock/paper/scissors: ")
    rock_paper_scissors(ask_p1, ask_p2)
    if input('Play Again Y/N')=='N':
        break

2:Call the function recursively. For every statement that ends, ask to play again
def PlayAgain:
    if input('Play Again Y/N')=='Y':
        rock_paper_scissors(ask_p1, ask_p2)

#In the rock_paper_scissors(ask_p1, ask_p2) function
...
if p1 == "rock" and p2 == "paper":
        print ("Player 2 wins!")
        PlayAgain()
...

Final code:
def rock_paper_scissors(p1, p2):
    a_list = ["rock", "paper", "scissors"]

    while p1 == p2:
        print ("Nobody wins. Try again")
        p1 = input("Player 1, Enter rock/paper/scissors: ")
        p2 = input("Player 2, Enter rock/paper/scissors: ")

    if p1 == "rock" and p2 == "paper":
        print ("Player 2 wins!")

    elif p1 == "paper" and p2 == "rock":
        print ("Player 1 wins!")

    elif p1 == "rock" and p2 == "scissors":
        print ("Player 1 wins!")

    elif p1 == "scissors" and p2 == "rock":
        print ("Player 2 wins")

    elif p1 == "paper" and p2 == "scissors":
        print ("Player 2 wins!")

    elif p1 == "scissors" and p2 == "paper":
        print ("Player 1 wins!")
    else:
        print('Invalid')

while True:
    ask_p1 = input("Player 1, Enter rock/paper/scissors: ")
    ask_p2 = input("Player 2, Enter rock/paper/scissors: ")
    rock_paper_scissors(ask_p1, ask_p2)
    if input('Play Again Y/N')=='N':
        break

A: I don't think some of the variables that you are assigning are being used, nor is there much of a need to add players as arguments in the function, since they never come up in the program. I would put everything inside the function and then recursively call it again when they player is asked if they would like to play another game.
def rock_paper_scissors():
    p1 = input("Player 1, Enter rock/paper/scissors: ")
    p2 = input("Player 2, Enter rock/paper/scissors: ")

    while p1 == p2:
        print ("Nobody wins. Try again")
        p1 = input("Player 1, Enter rock/paper/scissors: ")
        p2 = input("Player 2, Enter rock/paper/scissors: ")

    if p1 == "rock" and p2 == "paper":
        print ("Player 2 wins!")

    elif p1 == "paper" and p2 == "rock":
        print ("Player 1 wins!")

    elif p1 == "rock" and p2 == "scissors":
        print ("Player 1 wins!")

    elif p1 == "scissors" and p2 == "rock":
        print ("Player 2 wins")

    elif p1 == "paper" and p2 == "scissors":
        print ("Player 2 wins!")

    elif p1 == "scissors" and p2 == "paper":
        print ("Player 1 wins!")

    answer = input("Reply 'y' to play again, or 'n' to end the game.\n")
    if answer == 'y':
        rock_paper_scissors()

rock_paper_scissors()


text:
Q: A function can be undefined in its domain It's usual in Complex Analysis see some points of the domain of a function as undefined. See for example as Wikipedia defines a removable singularity:

I've seen functions with undefined points in real calculus books as well (they call these points as discontinuities).
I don't feel very well with such points, the definition of functions says clearly that points should be defined in its domain and functions with undefined points break this rule which is unacceptable mathematics speaking.
So where am I wrong?

A: The definition of a singularity is as follows: Let $D$ be an open set in $ \mathbb C$, let $z_0 \in D$ and suppose that $f$ is a holomorphic function on $ D \setminus \{z_0\}$. Then $z_0$ is called an isolated singularity of $f$.
Observe that $f$ is defined on $ D \setminus \{z_0\}$ !
The singularity is called removable , if there is a holomorphic $g$ on $D$ such that
$ f=g$ on $ D \setminus \{z_0\}$


text:
Q: Convergence of the series $\sum_{n=1}^\infty a_n = \frac{(n^n)(x^n)}{(n!)}$ With the help of ratio test, I have been successful in proving it is convergent for
$ex<1$ and divergent for $ex>1$. however for $ex=1$, the ratio test has failed. Hence I had to apply the logarithm test.
The form after applying log test is: n*(-n*log(1+1/n)+1)
this is where it's becoming problematic for me. I do not have any idea how to proceed from here. any help is greatly appreciated. thank you.

A: $\frac {a_{n+1}} {a_n}=(1+\frac1 n)^{n} x$ so the ratio test tells you that the series converges for $|x| <\frac 1 e$ and diverges for $|x|>\frac  1 e$.
When $x =\frac 1 e$ use Stirling's formula to compare the series with $\frac 1 {\sqrt {2\pi}} \frac 1 {\sqrt n}$ to see that the series diverges.


text:
Q: No declaration of property error in Objective-C I wonder what is wrong with this?
.h file:
typedef enum {
    N4LoupeTypeRound,
    N4LoupeTypeRectangle,
} N4LoupeType;

@interface N4LoupeLayer : CALayer {
    N4LoupeType _type;
    UIView *_originalView;
    CALayer *_mask;
    CALayer *_overlay;
}

@property (nonatomic) N4LoupeType type;
@property (nonatomic, assign) UIView *originalView;

@end

.m file:
#import "N4LoupeLayer.h"

@interface N4LoupeLayer (Privates)

@property (nonatomic, retain) CALayer *mask;
@property (nonatomic, retain) CALayer *overlay;

@end

@implementation N4LoupeLayer

@synthesize type = _type;
@synthesize originalView = _originalView;
@synthesize mask = _mask;
@synthesize overlay = _overlay; // ******I GET THE ERROR HERE*********

@end

No declaration of property 'overlay' found in the interface in N4LoupeLayer.m

A: You defined the properties for the Privatescategory, but you are trying to synthesize them in N4LoupeLayer.


text:
Q: Use scipy.integrate.quad to integrate complex numbers I'm using right now the scipy.integrate.quad to successfully integrate some real integrands. Now a situation appeared that I need to integrate a complex integrand. quad seems not be able to do it, as the other scipy.integrate routines, so I ask: is there any way to integrate a complex integrand using scipy.integrate, without having to separate the integral in the real and the imaginary parts?

A: I realize I'm late to the party, but perhaps quadpy (a project of mine) can help. This
import quadpy
import numpy

val, err = quadpy.quad(lambda x: numpy.exp(1j * x), 0, 1)
print(val)

correctly gives
(0.8414709848078964+0.4596976941318605j)

A: What's wrong with just separating it out into real and imaginary parts?  scipy.integrate.quad requires the integrated function return floats (aka real numbers) for the algorithm it uses.
import scipy
from scipy.integrate import quad

def complex_quadrature(func, a, b, **kwargs):
    def real_func(x):
        return scipy.real(func(x))
    def imag_func(x):
        return scipy.imag(func(x))
    real_integral = quad(real_func, a, b, **kwargs)
    imag_integral = quad(imag_func, a, b, **kwargs)
    return (real_integral[0] + 1j*imag_integral[0], real_integral[1:], imag_integral[1:])

E.g.,
>>> complex_quadrature(lambda x: (scipy.exp(1j*x)), 0,scipy.pi/2)
((0.99999999999999989+0.99999999999999989j),
 (1.1102230246251564e-14,),
 (1.1102230246251564e-14,))

which is what you expect to rounding error - integral of exp(i x) from 0, pi/2 is (1/i)(e^i pi/2 - e^0) = -i(i - 1) = 1 + i ~ (0.99999999999999989+0.99999999999999989j).
And for the record in case it isn't 100% clear to everyone, integration is a linear functional, meaning that ∫ { f(x) + k g(x) } dx = ∫ f(x) dx + k ∫ g(x) dx (where k is a constant with respect to x).  Or for our specific case ∫ z(x) dx = ∫ Re z(x) dx + i ∫ Im z(x) dx as z(x) = Re z(x) + i Im z(x).
If you are trying to do a integration over a path in the complex plane (other than along the real axis) or region in the complex plane, you'll need a more sophisticated algorithm.
Note: Scipy.integrate will not directly handle complex integration.  Why?  It does the heavy lifting in the FORTRAN QUADPACK library, specifically in qagse.f which explicitly requires the functions/variables to be real before doing its "global adaptive quadrature based on 21-point Gauss–Kronrod quadrature within each subinterval, with acceleration by Peter Wynn's epsilon algorithm."  So unless you want to try and modify the underlying FORTRAN to get it to handle complex numbers, compile it into a new library, you aren't going to get it to work.
If you really want to do the Gauss-Kronrod method with complex numbers in exactly one integration, look at wikipedias page and implement directly as done below (using 15-pt, 7-pt rule).  Note, I memoize'd function to repeat common calls to the common variables (assuming function calls are slow as if the function is very complex).  Also only did 7-pt and 15-pt rule, since I didn't feel like calculating the nodes/weights myself and those were the ones listed on wikipedia, but getting reasonable errors for test cases (~1e-14)
import scipy
from scipy import array

def quad_routine(func, a, b, x_list, w_list):
    c_1 = (b-a)/2.0
    c_2 = (b+a)/2.0
    eval_points = map(lambda x: c_1*x+c_2, x_list)
    func_evals = map(func, eval_points)
    return c_1 * sum(array(func_evals) * array(w_list))

def quad_gauss_7(func, a, b):
    x_gauss = [-0.949107912342759, -0.741531185599394, -0.405845151377397, 0, 0.405845151377397, 0.741531185599394, 0.949107912342759]
    w_gauss = array([0.129484966168870, 0.279705391489277, 0.381830050505119, 0.417959183673469, 0.381830050505119, 0.279705391489277,0.129484966168870])
    return quad_routine(func,a,b,x_gauss, w_gauss)

def quad_kronrod_15(func, a, b):
    x_kr = [-0.991455371120813,-0.949107912342759, -0.864864423359769, -0.741531185599394, -0.586087235467691,-0.405845151377397, -0.207784955007898, 0.0, 0.207784955007898,0.405845151377397, 0.586087235467691, 0.741531185599394, 0.864864423359769, 0.949107912342759, 0.991455371120813]
    w_kr = [0.022935322010529, 0.063092092629979, 0.104790010322250, 0.140653259715525, 0.169004726639267, 0.190350578064785, 0.204432940075298, 0.209482141084728, 0.204432940075298, 0.190350578064785, 0.169004726639267, 0.140653259715525,  0.104790010322250, 0.063092092629979, 0.022935322010529]
    return quad_routine(func,a,b,x_kr, w_kr)

class Memoize(object):
    def __init__(self, func):
        self.func = func
        self.eval_points = {}
    def __call__(self, *args):
        if args not in self.eval_points:
            self.eval_points[args] = self.func(*args)
        return self.eval_points[args]

def quad(func,a,b):
    ''' Output is the 15 point estimate; and the estimated error '''
    func = Memoize(func) #  Memoize function to skip repeated function calls.
    g7 = quad_gauss_7(func,a,b)
    k15 = quad_kronrod_15(func,a,b)
    # I don't have much faith in this error estimate taken from wikipedia
    # without incorporating how it should scale with changing limits
    return [k15, (200*scipy.absolute(g7-k15))**1.5]

Test case:
>>> quad(lambda x: scipy.exp(1j*x), 0,scipy.pi/2.0)
[(0.99999999999999711+0.99999999999999689j), 9.6120083407040365e-19]

I don't trust the error estimate -- I took something from wiki for recommended error estimate when integrating from [-1 to 1] and the values don't seem reasonable to me.  E.g., the error above compared with truth is ~5e-15 not ~1e-19.  I'm sure if someone consulted num recipes, you could get a more accurate estimate.  (Probably have to multiple by (a-b)/2 to some power or something similar).
Recall, the python version is less accurate than just calling scipy's QUADPACK based integration twice.  (You could improve upon it if desired).


text:
Q: Customizing objects inner property construction using "create" in knockoutJS I am trying to create an objects inner property in knockout, based on this article. Objects can be customized like this:
var data = {
        name: 'Graham',
        children: [
            { id : 1, name : 'Lisa' }
        ]
}

then create a map for it :
var mapping = {
        'children': {
            create: function(options) {
                return new myChildModel(options.data);
            }
        }
    }
    var viewModel = ko.mapping.fromJS(data, mapping);

with the custom field you want to add as new myChildModel() looking like this :
 var myChildModel = function(data) {
    ko.mapping.fromJS(data, {}, this);

    this.nameLength = ko.computed(function() {
        return this.name().length;
    }, this);
}

But what if the data i want to customize is in an objects inner property for example
var data = {
            name: 'Graham',
            family :{

    parents: [
                { id : 1, name : 'Duke' }
              ],

    children: [
                { id : 1, name : 'Lisa' }
              ]
        }
    }

here i would like to customize the children array which is inside family object, which is also inside data object.
This is what i tried:
var mapping = {
    'family.children': {
        create: function(options) {
            return new myChildModel(options.data);
        }
    }
}
var viewModel = ko.mapping.fromJS(data, mapping);

and also:
var mapping = {
    'family[children]': {
        create: function(options) {
            return new myChildModel(options.data);
        }
    }
}
var viewModel = ko.mapping.fromJS(data, mapping);

but none worked, is there a way this can be achieved ?

A: You could nest mappings by specifying a create function for the family property, in which you reference the children strategy.

var personData = {
  name: 'Graham',
  family: {
    parents: [{
      id: 1,
      name: 'Duke'
    }],

    children: [{
      id: 1,
      name: 'Lisa'
    }]
  }
}

var familyMapping = {
  'children': {
    create: function(childData) {
      return new MyChildModel(childData.data);
    }
  }
}

var personMapping = {
  'family': {
    create: function(familyData) {
      return ko.mapping.fromJS(familyData.data, familyMapping, {});
    }
  }
}

var person = ko.mapping.fromJS(personData, personMapping);
ko.applyBindings(person);

function MyChildModel(data) {
  ko.mapping.fromJS(data, {}, this);

  this.nameLength = ko.computed(function() {
    return this.name().length;
  }, this);
}

    <input data-bind="textInput: name"> ()

I have to say I'm not a big fan of the mapping plugin. I don't think it beats writing your own constructors, which isn't that much work.

function Person(id, name, parentsData, childrenData) {
  // For one way binding
  this.id = id;

  // For two way binding
  this.name = ko.observable(name);

  this.parents = ko.observableArray(
    parentsData.map(Person.fromData)
  );

  this.children = ko.observableArray(
    childrenData.map(Person.fromData)
  );

  // Computed
  this.nameLength = ko.pureComputed(
    function() { return this.name().length; },
    this
  );
}

Person.fromData = function(apiData) {
  const id = apiData.id || null;
  const name = apiData.name || "Unknown";
  const parentsData = apiData.family
    ? apiData.family.parents
    : [];
  const childrenData = apiData.family
    ? apiData.family.children
    : [];

  return new Person(id, name, parentsData, childrenData);
}

var personData = {
  name: 'Graham',
  family: {
    parents: [{
      id: 1,
      name: 'Duke'
    }],

    children: [{
      id: 1,
      name: 'Lisa'
    }]
  }
}

ko.applyBindings(Person.fromData(personData));


text:
Q: Synchronize 2 GCS buckets schedulled Didn't find answer for this, so:
I have my production Google Cloud Storage bucket A, and also a bucket B that I keep only for backup of A, and it's actually in another different Google project. I need that:

*

*I can make this sync operation once and have it run forever periodically, instead of having to run or trigger it again and again. With periodically I mean daily or weekly, I don't need more often than that.

*Contents go directly from A to B, to avoid the extra cost of transfering everything through a third machine (like my laptop or a ComputeEngine box).

*Preferably it would imply copying only new contents and changes, since 90% will be the same from last sync.
My questions:

*

*I think that Storage Transfer Service is the best option but I'd like someone who knows better to confirm. Any better option?

*Is it true that Storage Transfer Service meets my second requirement and gsutil doesn't? It seems so, but then I'm surprised they don't mention it when the docs say "Should you use gsutil or Cloud Storage Transfer Service?" (https://cloud.google.com/storage/transfer/)
Thanks a lot in advance.

A: *

*Yes, I think the Storage Transfer Service is the perfect solution for your use case. You can set up a recurring transfer.

*You can also transfer data in the cloud with gsutil, but there are several caveats. See the Copying In The Cloud And Metadata Preservation section of the gsutil rsync docs.


text:
Q: Bootstrap select dropdown gets distorted when used with slick slider When using Bootstrap select dropdown with the slick slider, it gets distorted.
Here is the link to jsfiddle.
HTML code:
<div class="slider">
<select name="test" multiple="" class="selectpicker">
  <option value="Created" data-subtext="">Created (91)</option>
  <option value="Approved" data-subtext="">Approved (6038)</option>
  <option value="Completed" data-subtext="">Completed (477)</option>
   <option value="Held" data-subtext="">Held (54)</option>
   <option value="Rejected" data-subtext="">Rejected (4)</option>
   <option value="Cancelled" data-subtext="">Cancelled (71)</option>
   <option value="Authorized" data-subtext="">Authorized (1)</option>
</select>
<select name="test" multiple="" class="selectpicker">
  <option value="Created" data-subtext="">Created (91)</option>
  <option value="Approved" data-subtext="">Approved (6038)</option>
  <option value="Completed" data-subtext="">Completed (477)</option>
   <option value="Held" data-subtext="">Held (54)</option>
   <option value="Rejected" data-subtext="">Rejected (4)</option>
   <option value="Cancelled" data-subtext="">Cancelled (71)</option>
   <option value="Authorized" data-subtext="">Authorized (1)</option>
</select>
<select name="test" multiple="" class="selectpicker">
  <option value="Created" data-subtext="">Created (91)</option>
  <option value="Approved" data-subtext="">Approved (6038)</option>
  <option value="Completed" data-subtext="">Completed (477)</option>
   <option value="Held" data-subtext="">Held (54)</option>
   <option value="Rejected" data-subtext="">Rejected (4)</option>
   <option value="Cancelled" data-subtext="">Cancelled (71)</option>
   <option value="Authorized" data-subtext="">Authorized (1)</option>
</select>
</div>

JS Code
// A $( document ).ready() block.
$( document ).ready(function() {
    var slickEle = jQuery(".slider").slick();
    slickEle.slick({
      dots: false,
      infinite: false,
      variableWidth: true,
      slidesToShow: 3,
      slidesToScroll: 1,
      touchMove : true,
      mobileFirst: true
    })
});

Steps to reproduce the problem

Click on the select box it gets distorted.

What is the expected behaviour?

Without Slick:

What is observed behaviour?

With Slick:

====================================================================
Does anyone have any solution for this?
Thanks in advance

A: I posted the question on bootstrap-select issue tracker as well: #2314.
As answered by Casey Holzer:

You need to set container: 'body' or data-container="body".
  https://developer.snapappointments.com/bootstrap-select/examples/#container

As per Container documentation:

Append the select menu to a specific element, e.g. container: 'body'
  or data-container=".main-content". This is useful if the select
  element is inside an element with overflow: hidden.

Select element is inside slick-list which sets overflow: hidden so that only current slides are visible, so when we set the container: body it works.
Here is the working fiddle: https://jsfiddle.net/iamaditya/01ncvrbj/4/
Thanks for the response :)

A: Add this style
 .slick-list {
     overflow: unset;
}


text:
Q: download file withough storing file on server? How to give download functionality of file to client withought storing file on server? I am using jasper reports in my liferay portlet and I want that user download the reports directly from the output stream. I don't want to store the reports pdf file on my server.
How can I do this with the jasper report?
File pdf = File.createTempFile("output.", ".pdf");
JasperExportManager.exportReportToPdfStream(jasperPrint, new FileOutputStream(pdf));

Right now I'm doing this which generate pdf file in some directory and then I provide download link to user. But I want that user just download the pdf from direct ouptut stream.

A: In your portlet action:
public void serveResource(ResourceRequest request,ResourceResponse response) throws PortletException, IOException {

    response.setContentType("application/application-download");
    response.setProperty("Content-disposition", "attachement; filename=<some file.pdf>");

    OutputStream responseStream = response.getPortletOutputStream();

    jasperPrint=...
    JasperExportManager.exportReportToPdfStream(jasperPrint, responseStream);

    responseStream.flush();
    responseStream.close();

}

Then create the resource download url like this:
<a href="<portlet:resourceURL/>">Download Report

A: If I understood the question correctly you coud try
  ByteArrayOutputStream bous = new ByteArrayOutputStream();
  JasperExportManager.exportReportToPdfStream(jasperPrint, bous);
  byte[] bytes = bous.toByteArray();


text:
Q: Path from leaf to root permutation Consider a tree in which each vertex has 5 children, and let us label the edges with $a$ or $b$ such that the edges from any parent to its children are always ordered $(a,b,a,b,b)$. See the figure for the case when there are 2 generations of children below the root. We allow $N$ generations in general.
Let us choose a vertex from the tree, at any level and consider its path back to the root. For instance, the left most grandchild has path $a\circ a$, the next is $a\circ b$ and so on.
Let us order the leaves of the tree from the left as $5(j-1)+k$ where $j$ is the index of the parent and $k=1,\dots,5$. In the example, the leaves will have labels 1 to 25.
Question 1
Given the label of a leaf, is there an expression for the path in terms of $a$ and $b$ in closed form. For instance, for some height $i$ and some index $j$ from $1$ to $5^{i-1}$ we might have
$$
\text{leaf}_{ij} = a\circ b\circ \dots \circ a
$$
If there is not, is there an accepted notation to describe this path?
Any help appreciated.
Thoughts
Paths are all the same length. Each position is either $a$ or $b$. If $j$ is $1,3,6,8,11,13, ...$ (congruent to $\{1, 3\}\mod 5$) then the element is $a$, otherwise it is $b$.
https://oeis.org/search?q=1%2C3%2C6%2C8%2C11%2C13&language=english&go=Search

A: Let $\ell$ be the index of the leaf, so $\ell$ is a number between $1$ and $5^N$. In your notation, $\ell=5(j-1)+k$.
In order to get the path sequence for the $\ell$, write $\ell-1$ in base five. The representation is a sequence of $N$ digits, each between $0$ and $4$. You may need to prepend some leading zeroes so the length is exactly $N$. To get the sequence of edge labels, substitute letters for the digits as follows:
$$
0\to a,\quad 1\to b,\quad 2\to a,\quad 3\to b,\quad 4\to b
$$


text:
Q: VueJS / Vue Router - create details page from list item? I have a list of items (taken from a JSON file) which I currently loop through, however I wish to create a details page for each of these items (incorporating VueRouter).
Any pointers on how to achieve this? I'm currently stuck on passing the data to the details page template.
Thanks

    {{ projects.name }}
    <router-link :to="profileLink" class="button is-outlined">View Details</router-link>
    {{ projects.coding }}
    { projects.design }}
    {{ projects.description }}

A: See those links :

*

*https://router.vuejs.org/en/essentials/dynamic-matching.html

*https://router.vuejs.org/en/essentials/named-routes.html
With your use case what you could do is:

*

*set up a new named route called details:
    {
      path: '/project/:projectId/details',
      name: 'details',
      component: Details,
      props: true,
    }

Every time you want to redirect a user to details page, use this route.
The :projectId means it's dynamic, you can provide any id, it will always redirect to the component Details you created to display a project's details.

*Create a new router link in your list like so:
<router-link :to="{ name: 'details', params: { projectId: project.id }}">{{project.name}}</router-link>

*Inside your component details, you have to declare route params as props, for instance props: ["id"],. You can then access it in your component with this.id.


text:
Q: Laravel 4 - no guessers available issue I get this error: LogicException: Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?) while trying to upload an image.
I have enabled the php_fileinfo extension and also restarted the Wamp web server but I still unable to solve this. What am I missing? Thanks
Below are my codes:
Models: Product.php
class Product extends Eloquent {

protected $fillable = array('category_id', 'title', 'description', 'price', 'availability', 'image');

public static $rules = array(
    'category_id'=>'required|integer',
    'title'=>'required|min:2',
    'description'=>'required|min:20',
    'price'=>'required|numeric',
    'availability'=>'integer',
    'image'=>'required|image|mimes:jpeg,jpg,bmp,png,gif|max:3000',
);

public function category() {
    return $this->belongsTo('Category');
}

}
Controllers: ProductsController.php
 public function postCreate() {
    $validator = Validator::make(Input::all(), Product::$rules);

    if($validator->passes()) {
        $product = new Product;
        $product->category_id = Input::get('category_id');
        $product->title = Input::get('title');
        $product->description = Input::get('description');
        $product->price = Input::get('price');

        $image = Input::file('image');
        $filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
        Image::make($image->getRealPath())->resize(468,249)->save('public/img/products/'.$filename);
        $product->image = 'img/products/'.$filename;
        $product->save();

        return Redirect::to('admin/products/index')
            ->with('message', 'Product Created');
    }

    return Redirect::to('admin/products/index')
        ->with('message', 'Something went wrong')
        ->withErrors($validator)
        ->WithInput();
}

Views: Index.blade.php
  {{ Form::open(array('url'=>'admin/products/create', 'files'=>true)) }}

        {{ Form::label('category_id', 'Category') }}
        {{ Form::select('category_id', $categories) }}

        {{ Form::label('title') }}
        {{ Form::text('title') }}

        {{ Form::label('description') }}
        {{ Form::textarea('description') }}

        {{ Form::label('price') }}
        {{ Form::text('price', null, array('class'=>'form-price')) }}

        {{ Form::label('image', 'Choose an image') }}
        {{ Form::file('image') }}

    {{ Form::submit('Create Product', array('class'=>'secondary-cart-btn')) }}
    {{ Form::close() }}

A: Open php.ini file and you can find ;extension=php_fileinfo.dll remove the semi-coloumn  to extension=php_fileinfo.dll will work perfectly then restart the your apache server or xampp ,wampp whatever environment you are using

A: uncomment this line in php.ini into php folder.
extension=php_fileinfo.dll
and restart the server(enter 'php artisan serve' again). This way will works!

A: I think is the WAMP Web Server's Bug. I switched to XAMPP Web Server and it works fine.
Thanks alot by the way.


text:
Q: How do I properly unit test a repository-pattern method, that has coupling to Entity Framework / DbContext? I'm new to unit testing and wish to write an application that is N-tier, so my ORM is abstracted away from BLL with a repository-pattern inbetween. How would I go about unit testing a repository-pattern method that has coupling to EF (DbContext)?
My SUT method is here:
public IList<Volunteer> GetAllVolunteers() {
    return dbctx.Volunteer.ToList();
}

My unit test so far:
[Fact]
public void GetAllVolunteersMethodWorks() {
    // Arrange
    var fakeVolunteer = new Volunteer { Id = 0, Name = "Dummy" };
    var expected = new List<Volunteer>(new Volunteer[] { fakeVolunteer });

    var mockedCtxVolunteer = new Mock<DbSet<Volunteer>>();
    mockedCtxVolunteer.Setup(m => m.ToList()).Returns(expected);

    var mockedctx = new Mock<RSMContext>();
    mockedctx.Setup(m => m.Volunteer).Returns(mockedCtxVolunteer.Object);

    // Act
    var volunteerRepo = new VolunteerRepository(mockedctx.Object);
    var result = volunteerRepo.GetAllVolunteers();

    // Assert
    Assert.Equal(expected, result);
}

I get an error that System.NotSupportedException: 'Expression references a method that does not belong to the mocked object: m => m.ToList()
So how do I properly mock the DbSet so my fake data resides there to properly test my VolunteerRepository.GetAllVolunteers() method works?
edit (solution):
var mockedDbCtxVolunteer = new Mock<DbSet<Volunteer>>();
mockedDbCtxVolunteer.As<IQueryable<Volunteer>>().Setup(m => m.GetEnumerator()).Returns(expected.GetEnumerator());

A: ToList() is an extension method, which Moq (and other libraries) cannot mock.  Don't worry about mocking that method, but instead mock what it would use: GetEnumerator():
var mockedCtxVolunteer = new Mock<DbSet<Volunteer>>();
mockedCtxVolunteer.Setup(m => m.GetEnumerator()).Returns(expected.GetEnumerator());

A: We are using a helper class to mock the DbSet. It uses an internal data store for the mocked items in the set.
public class MockDbSet<T> : IDbSet<T> where T : class {

    readonly HashSet<T> _data;
    readonly IQueryable _query;

    public MockDbSet() : this(new HashSet<T>()) {
    }

    public MockDbSet(params T[] entries) : this(new HashSet<T>(entries)) {
    }

    private MockDbSet(IEnumerable<T> data) {
        _data = new HashSet<T>(data);
        _query = _data.AsQueryable();
    }

    public T Add(T item) {
        _data.Add(item);
         return item;
    }

    public T Remove(T item) {
        _data.Remove(item);
        return item;
    }

    Type IQueryable.ElementType {
        get { return _query.ElementType; }
    }

    IEnumerator IEnumerable.GetEnumerator() {
        return _data.GetEnumerator();
    }

    // implement other members of IDbSet<T> ...
}

Then in your unit test, use Moq to set up the datacontext. Access to the Volunteer set will be redirected to the mock implementation.
var mockedVolunteer1 = new Volunteer { Name = "Uno" };
var mockedDbSet = new MockDbSet<Volunteer> {
     mockedVolunteer1, mockedVolunteer2, mockedVolunteer3
};

var mockedContext = new Mock<MyDataContext>();
mockedContext.Setup(ctx => ctx.Volunteer).Returns(mockedDbSet);

Using the MockDbSet class has the advantages that you don't have to guess which methods will be accessed by your test and therefore need mocking, and you don't have to setup the mocked methods every time.


text:
Q: Hibernate: comparing current & previous record I want to compare the current value of an in-memory Hibernate entity with the value in the database:
HibernateSession sess = HibernateSessionFactory.getSession();
MyEntity newEntity = (MyEntity)sess.load(MyEntity.class, id);
newEntity.setProperty("new value");
MyEntity oldEntity = (MyEntity)sess.load(MyEntity.class, id);
// CODEBLOCK#1 evaluate differences between newEntity and oldEntity
sess.update(newEntity);

In CODEBLOCK#1 I get that newEntity.getProperty()="new value" AND oldEntity.getProperty()="new value" (while I expected oldEntity.getProperty()="old value", of course). In fact the two objects are exactly the same in memory.
I messed around with HibernateSessionFactory.getSession().evict(newEntity) and attempted to set oldEntity=null to get rid of it (I need it only for the comparison):
HibernateSession sess = HibernateSessionFactory.getSession();
MyEntity newEntity = (MyEntity)sess.load(MyEntity.class, id);
newEntity.setProperty("new value");
HibernateSessionFactory.getSession().evict(newEntity);
MyEntity oldEntity = (MyEntity)sess.load(MyEntity.class, id);
// CODEBLOCK#1 evaluate differences between newEntity and oldEntity
oldEntity = null;
sess.update(newEntity);

and now the two entities are distinct, but of course I get the dreaded org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session.
Any idea?
EDIT: I tried the double session strategy; I modified my HibernateSessionFactory to implement a map of session and then...
Session session1 = HibernateSessionFactory.getSession(SessionKeys.DEFAULT);
Session session2 = HibernateSessionFactory.getSession(SessionKeys.ALTERNATE);
Entity newEntity = (Entity)entity;
newEntity.setNote("edited note");
Entity oldEntity = (Entity)session1.load(Entity.class, id);

System.out.println("NEW:" + newEntity.getNote());
System.out.println("OLD: " + oldEntity.getNote()); // HANGS HERE!!!

HibernateSessionFactory.closeSession(SessionKeys.ALTERNATE);

My unit test hangs while attempting to print the oldEntity note... :-(

A: Two easy options spring to mind:

*

*Evict oldEntity before saving newEntity

*Use session.merge() on oldEntity to replace the version in the session cache (newEntity) with the original (oldEntity)

EDIT: to elaborate a little, the problem here is that Hibernate keeps a persistence context, which is the objects being monitored as part of each session. You can't do update() on a detached object (one not in the context) while there's an attached object in the context. This should work:
HibernateSession sess = ...;
MyEntity oldEntity = (MyEntity) sess.load(...);
sess.evict(oldEntity); // old is now not in the session's persistence context
MyEntity newEntity = (MyEntity) sess.load(...); // new is the only one in the context now
newEntity.setProperty("new value");
// Evaluate differences
sess.update(newEntity); // saving the one that's in the context anyway = fine

and so should this:
HibernateSession sess = ...;
MyEntity newEntity = (MyEntity) sess.load(...);
newEntity.setProperty("new value");
sess.evict(newEntity); // otherwise load() will return the same object again from the context
MyEntity oldEntity = (MyEntity) sess.load(...); // fresh copy into the context
sess.merge(newEntity); // replaces old in the context with this one

A: What about using session.isDirty()? The JavaDoc says that method will answer the question "Would any SQL be executed if we flushed this session?"  Of course, that would only work if you had a new clean Session to start with. Another option - just use two different Sessions.


text:
Q: Bernoulli experiment Let $\lambda = \frac{m}{n}$ where $m<n$ and $m, n$ are positive integers. Let $\{k_i\}$ be a sequence of non-negative reals. For $i=1,2,3,\dots,$ let $X_i$ be a binomial random variable with parameters $n$ and $\lambda$ and $t_i = i\cdot m +k_i.$ Let $Y_i = X_1+X_2+\dots X_i$ for $i = 1,2,3,\dots .$ Is it possible to choose a decreasing sequence of non-negative reals $\{k_i\}$ such that $k_i \rightarrow 0$ as $i \rightarrow \infty$ and $P(\cap_{i=1}^{\infty}\{Y_i \leq t_i\})$ is close to 1 ?
I will try to explain the physical problem which am trying to model so that the above formulation may make sense. There is a bernoulli random variable $X$ with probability of failure $\lambda.$ After $i \cdot n$ number of trials, if the process was truly a bernouli random variable with parameter $\lambda$, I will observe a total number of failures which is close to $i\cdot m.$ After first $n$ trials, I examine the total number of failures. If the total number of failures is much greater than $m,$ then I suspect that the process is not a Bernouli with parameter $\lambda$ and stop the process. (I stop the process only if the process is Bernoulli with parameter strictly greater than $\lambda$ i.e., I can afford a failure rate of atmost $\lambda$). Otherwise I continue with the next $n$ trials and so on. So each $i$th block has $n$ independent trials of the bernoulli r.v $X,$ given that the process did not stop till the first $i-1^{th}$ blocks. The problem then is in some sense to find the correct sequence of thresholds $k_i$ after each $i^{th}$ block, so that I stop the process only when I have strong evidence that the process is a Bernoulli with parameter greater than $\lambda.$
Any help with the problem will be greatly appreciated!!


text:
Q: Fill shape of contour I am trying to pre-process an image for OCR. How do I fill in the contours of the text to make it more readable for the algorithmImage is here

A: do not apply Canny. OCR expects filled letters, not outlines.


text:
Q: Auto play a sound when receive a new row data in Vue.js I am developing a Vue app to fetch orders from Woocommerce REST API. So i am having a HTML Table to fill the JSON Data. So when each order receive to Woocommerce, I will get it in my dashboard using "setInterval" for 60 seconds through refreshing data. Also the flags are set to notify new order in the HTML table using colors.
Apart from this I need to play a sound in the Vue app whenever the Woocommerce receives an order. How can I archive this as a stable function?
My JS code
var app = new Vue({
    el: '#app',
    data: {
      orders: []
    },
    mounted: function() {
  // Call the API the first time
  this.refreshData()
  // Then call the API every minute
  this.setIntervalId = setInterval(this.refreshData, 60000)
},
beforeDestroy: function() {
  // Stop refreshing data after the component is destroyed!
  clearInterval(this.setIntervalId)
},
methods: {
  refreshData () {
    axios.get('https://mysite/wp-json/wc/v3/orders?per_page=20&consumer_key=key1&consumer_secret=key2')
    .then(response => {

      const previouslyFlaggedIds = this.orders.filter(x => x.is_printed).map(x => x.id);
      this.orders = response.data.map(x => ({...x, is_printed: previouslyFlaggedIds.find(y => y === x.id) != null}));
      console.log(response);
     })
     .catch(error => {
       console.log(eror);
    });
  },
  printBill(order) {
    //change flag
    order.is_printed = true;
  }
}
})

HTML

                Order id
                Name
                Order Date
                Phone
                Address
                Items
                Total
                Print

                    {{ order.id }}
                    {{ order.billing.first_name + " " +order.billing.last_name }}
                    {{ order.date_created }}
                    {{ order.billing.phone}}
                    {{ order.billing.address_1 + ", " + order.billing.address_2 + ", " + order.billing.city + order.billing.postcode }}
                    {{ order.line_items[0].name}}
                    {{ order.total}}
                    <button class="btn btn-primary" @click="printBill(order)">Print</button>

A: You can use audio tag for this.
<audio
  ref="audio"
  src="/media/cc0-audio/t-rex-roar.mp3">
</audio>

Then after you receive the new orders just play the audio
this.$refs.audio.play()

JSFiddle example


text:
Q: How to use close statement in case of reading error from file? My IDE is:
Code::Blocks 20.3 ( compiler: mingw 9.2.0 )
The example code is:
module mod_close_file

implicit none

integer :: n_something

contains

function proc_calling() result(err_loc)

  logical :: err_loc

  err_loc = .false.

  open( unit = 15, file = 'data_aa.txt', action = 'read', status = 'old', err = 100 )

    read(15,*, err = 101) n_something

  close(unit = 15, status = 'keep' )

return

100 write(*,'(5x,a)') "err_loc - proc_calling - reading format - 100"
err_loc = .true.
!close(unit = 15, status = 'keep' )

return

101 write(*,'(5x,a)') "err_loc - proc_calling - reading format - 101"
err_loc = .true.
!close(unit = 15, status = 'keep' )

end function proc_calling

end module mod_close_file

program close_file

use, non_intrinsic :: mod_close_file

implicit none

logical :: err_glo

err_glo = proc_calling()

if ( err_glo ) stop "err_glo - proc_calling"

end program close_file

In case that the value n_something in the specified file is not an integer the program will report an error. In that case, is it necessary to write the close command after the return command?

A: You are asking, if you need to close the file prior stopping execution or if it will be closed automatically?
Fortran 2008 Final Draft 9.5.7.1-6 (page 211):

During the completion step (2.3.5) of termination of execution of a program, all units that are connected are closed.

2.3.5-4 (page 33):

Normal termination of execution of an image is initiated when a STOP statement or end-program-stmt is executed.

So no you don't need to close it prior calling STOP, it should close without calling close. (personally I would do it anyway)


text:
Q: Format LocalDateTime with Timezone in Java8 I have the this simple code:
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
LocalDateTime.now().format(FORMATTER)

Then I will get following exception:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds
at java.time.LocalDate.get0(LocalDate.java:680)
at java.time.LocalDate.getLong(LocalDate.java:659)
at java.time.LocalDateTime.getLong(LocalDateTime.java:720)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
at java.time.format.DateTimeFormatterBuilder$OffsetIdPrinterParser.format(DateTimeFormatterBuilder.java:3315)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1745)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1719)
at java.time.LocalDateTime.format(LocalDateTime.java:1746)

How to resolve this issue?

A: The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime). Despite the often misleading name such classes like LocalDateTime or LocalTime have NO timezone information or offset.
You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.
Solution:
Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime (which contains an offset but not a timezone including DST-rules) or ZonedDateTime. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds is supported in OffsetDateTime and ZonedDateTime, but not in LocalDateTime.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);

A: LocalDateTime is a date-time without a time-zone. You specified the time zone offset format symbol in the format, however, LocalDateTime doesn't have such information. That's why the error occured.
If you want time-zone information, you should use ZonedDateTime.
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
ZonedDateTime.now().format(FORMATTER);
=> "20140829 14:12:22.122000 +09"

A: The existing answers are correct but have missed some crucial information.

*

*While Z represents the time-zone offset only, V represents the time-zone ID which gives a ZonedDateTime its identity. Learn more about it from DateTimeFormatter documentation. While a time-zone ID of a place is fixed, the time-zone offset varies if the place observes DST (e.g. Europe/London has +01:00 offset in summer and +00:00, also represented as Z, offset in winter).

*One should always use Locale while using date-time parsing/formatting API because they are Locale-sensitive. Check Never use Date-Time formatting/parsing API without a Locale to learn more about it.

*Since LocalDateTime does not contain any information about time-zone, it should be formatted without any letter that represents time-zone related information. It is obvious that a formatter for LocalDateTime can always be used to format a ZonedDateTime but the reverse may fail (if it contains time-zone related character). If required, a ZonedDateTime representing the system's time zone can be derived from a LocalDateTime.

*I also prefer u to y with DateTimeFormatter.

Demo:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter ldtFormatter = DateTimeFormatter.ofPattern("uuuuMMdd HH:mm:ss.SSSSSS", Locale.ENGLISH);
        System.out.println(LocalDateTime.now().format(ldtFormatter));

        // ZZZZZ can be replaced with XXX
        DateTimeFormatter zdtFormatter = DateTimeFormatter.ofPattern("uuuuMMdd HH:mm:ss.SSSSSS VV ZZZZZ",
                Locale.ENGLISH);
        System.out.println(ZonedDateTime.now().format(zdtFormatter));
        System.out.println(ZonedDateTime.now().getZone());

        // Deriving ZonedDateTime from LocalDateTime using system's time zone
        LocalDateTime ldt = LocalDateTime.of(LocalDate.of(2022, 12, 15), LocalTime.of(10, 20, 30));
        ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
        System.out.println(zdt.format(zdtFormatter));
    }
}

Output:
20221013 20:55:13.466830
20221013 20:55:13.468847 Europe/London +01:00
Europe/London
20221215 10:20:30.000000 Europe/London Z

Learn more about the the modern date-time API from Trail: Date Time.


text:
Q: Why does time need to be a macro? The Clojure source code gives the following definition of time
(defmacro time
  "Evaluates expr and prints the time it took.  Returns the value of
 expr."
  {:added "1.0"}
  [expr]
  `(let [start# (. System (nanoTime))
         ret# ~expr]
     (prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs"))
     ret#))

Why does this need to be a macro? What about it could not be done with a function?

A: Because function evaluates its arguments before it starts working with them. You can write time as function and try to call it:
(defn my-time [expr]
  (let [start (System/nanoTime)
        ret expr]
    (prn (str "Elapsed time: " (/ (double (- (System/nanoTime) start)) 1000000.0) " msecs"))
    ret))

(my-time (Thread/sleep 1000))
"Elapsed time: 0.005199 msecs"
=> nil

Compare that with time macro:
(time (Thread/sleep 1000))
"Elapsed time: 1000.1222 msecs"
=> nil

Function my-time evaluated argument (Thread/sleep 1000), symbol expr got value nil and then body of that function happened- two (System/nanoTime) were called shortly after each other, because value of expr was already computed.
Macro time didn't evaluate (Thread/sleep 1000), but expanded to:
(macroexpand `(time (Thread/sleep 1000)))
=>
(let*
 [start__6136__auto__ (. java.lang.System (clojure.core/nanoTime)) ret__6137__auto__ (java.lang.Thread/sleep 1000)]
 (clojure.core/prn
  (clojure.core/str
   "Elapsed time: "
   (clojure.core//
    (clojure.core/double (clojure.core/- (. java.lang.System (clojure.core/nanoTime)) start__6136__auto__))
    1000000.0)
   " msecs"))
 ret__6137__auto__)

and functions were called in this order: (System/nanoTime), (Thread/sleep 1000) and other (System/nanoTime), which returns correct time.


text:
Q: How do I apply pseudo-selector styles from a parent with shadow DOM? I am basically trying to duplicate the behavior of the CSS Tricks navigation bar, with the animation of the item labels flying in from the left when any part of the whole bar is hovered over. I am trying to do this using Web Components and Polymer.
I have my HTML structured (roughly) like this:
index.html
<!-- ... head stuff ... -->
<body>
  <my-app></my-app>
</body>

my-app.html
<dom-module id="my-app">
  <nav>
    <my-nav-item url="/"
                 text="Home"
                 icon="home.svg#nav-icon-home"></my-nav-item>
  </nav>
</dom-module>

my-nav-item.html
<dom-module id="my-nav-item">
  <a href$="[[url]]">
    <svg height="20px" width="20px" viewBox="0 0 20 20">
      <use href$="[[icon]]"></use>
    </svg>
    <span>[[text]]</span>
  </a>
</dom-module>

And the CSS looks something like this:
my-app.html
nav {
  width: 75px;
  height: calc(100% - 60px);
  background: #222d32;
}

my-nav-item.html
a {
  display: block;
  text-decoration: none;
  color: white;
  margin: 25px auto;
  text-transform: uppercase;
  font-family: 'Exo 2', sans-serif;
  font-size: 12px;
}

svg {
  fill: white;
  margin: 0 auto;
}

span {
  display: block;
  margin: 10px auto;
  transform: translateX(-200px);
  transition: 0.1s;
}

The span starts off-screen as expected, and when I use a:hover span with transform: translateX(0) it works perfectly well with the text flying in from the left. I would, however, like ALL the labels to fly in from the left when any part of nav is hovered over, just like CSS Tricks' website does.
How do I set the nav:hover my-nav-item span transform property without breaking separation of concerns?

A: I ended up fixing the problem (reluctantly) with ::shadow /deep/:
my-app.html
nav:hover worf-nav-item::shadow /deep/ span {
  transform: translateX(0);
}

What might be nice is something along the lines of the native CSS properties used as mixins as proposed at 11:40 in the talk from Polymer Summit 2015: "Polymer's Styling System."
I might propose something like this:
my-app.html
nav:hover {
  --transform-no-translate-x: {
    transform: translateX(0);
  }
}

my-nav-item.html
span {
  @apply(--transform-no-translate-x);
}

But wait... there's more!
I actually kept playing with it while writing this and came up with another solution. I like this much better.
my-app.html
nav {
  --nav-transform: translateX(-200px);
}

nav:hover {
  --nav-transform: translateX(0);
}

my-nav-item.html
span {
  transform: var(--nav-transform);
}


text:
Q: Finding the expectation from the cdf of a vector-valued random variable We can calculate the expectation of a real-valued random variable by integrating its cumulative distribution function. What is the analogue of this fact for a random variable that takes values in a partially ordered vector space?
Suppose that $X$ is a random variable that takes values in a partially ordered vector space $V$. Let's warm up with the case where $X$ takes only takes values in a finite set of positive vectors $U ⊂ V$. (Let $U$ contain $0$ for convenience.) In the totally ordered case, if we let $d(x) = x - y$ where $y$ is the immediate predecessor of $x$ in $U$ (and $d(0) = 0$), then we have
$$
\sum_{x ∈ U} P(X = x) · x = \sum_{x ∈ U} P(X \geq x) · d(x)
$$
But this does not make sense if $V$ is only partially ordered, since $x$ need not have a single predecessor in $U$. We could try something like
$$d(x) = x - \sum \{y ∣ \text{$y$ is an immediate predecessor of $x$ in $U$} \}$$
But this doesn't work either: we end up double-counting some values of $x$, when we have branches in $U$ that eventually join again. I've been trying out more elaborate definitions of $d(x)$ that compensate for this, and I think I might be able to get it to work, but it feels like I'm probably reinventing a wheel.

A: I think I have an answer to the warm-up question for the case where $U$ has the structure of a finite lattice. But it's kind of complicated.
For any $x ∈ U$, let
$$\begin{aligned}
U_k^{\wedge}(x) & = \{ y_1 \wedge ⋯ \wedge y_k ∣ y_1, \dots, y_k \text{ are distinct and immediately precede $x$} \} \\
U_k^{\vee}(x) & = \{ y_1 \vee ⋯ \vee y_k ∣ y_1, \dots, y_k \text{ are distinct and immediately succeed $x$} \}
\end{aligned}$$
Then let
$$
d(x) = x + \sum_k (-1)^k \sum U_k^{\wedge}(x)
$$
Then the result holds. To show this, I'll use two lemmas.
Lemma 1. Let $E$ be a finite set of events.
$$
P(\cup E) = \sum_k (-1)^{k+1} \sum_{A_1 \neq \dots \neq A_k ∈ E} P(A_1 ∩ ⋯ ∩ A_k)
$$
This is a generalization of the simple fact that
$$P(A_1 ∪ A_2) = P(A_1) + P(A_2) - P(A_1 ∩ A_2)$$
Lemma 2. For any $x, z ∈ U$, $x ∈ U_k^{\wedge}(z)$ iff $z ∈ U_k^{\vee}(x)$.
Now consider the sum
$$
\sum_{x ∈ U} P(X \ge x)· d(x)
$$
For a given element $x ∈ U$, for which $z$ does $x$ appear as a term in $d(z)$? First, obviously $x$ appears in $d(x)$; and second, $x$ appears in any $z$ term such that $x ∈ U_k^{\wedge}(z)$, or equivalently by Lemma 2, where $z ∈ U_k^{\vee}(x)$. So the final coefficient for $x$ in the sum will be
$$
P(X \geq x) + \sum_k (-1)^k \sum_{z ∈ U_k^{\vee}(x)} P(X \geq z)
$$
Moreover, $P(X \ge x) = P(X = x) + P(X > x)$, and $X > x$ holds iff
$X \ge y_1$ or … or $X \ge y_n$, where $y_1, \dots, y_n$ are all of the immediate successors of $x$ in $U$.
So by Lemma 1,
$$
P(X > x) = \sum_k(-1)^k \sum_{z ∈ U_k^{\wedge}} P(X \ge z)
$$
So all of those terms cancel out, leaving just $P(X = x) · x$.


text:
Q: A better verb for "cement" in "cement one's interest" Is there a better word for cemented in the following sentence?

All the experiences I went through have cemented my interest in this field.

I was told "cemented" doesn't quite fit in and I was asked to find a replacement. Any synonyms, anyone?
I know this question sounds vague, please comment if you need additional details.

A: The noun cement refers to the binder in concrete which in combination with water forms a paste which solidifies into mortar, which is solid and strong. Together with sand and stone this forms concrete.
In the context of All the experiences I went through have cemented my interest in this field., cementing means strengthening or solidifying.
I would say the most suitable alternative word word be solidified here:
All the experiences I went through have solidified my interest in this field.

A: I would say confirmed. In this context.

A: To me,HARDENED or SET can also be used in the place of CEMENTED in the sentence.
AZEEZ TANUR

A: I would probably say ingrained, meaning deeply embedded

A: I think 'cemented' is perfect. I'd change 'All the experiences I went through ... ', though, to 'My experiences have cemented my interest in this field'.

A: I guess cemented or its synonym won't fit the context that you have mentioned. Try strengthened, steeled, etc.


text:
Q: Geometric Matrix Transformations r = rectangle('Position', [1 2 4 6])
axis([0 15 0 15])

I know how to create a transformation matrix and how to store it as an affine2d geometric transformation object.
However, my issue comes with multiplying the rectangle object with the transformation matrix.
Is there a way to multiply the rectangle object created above with the transformation matrix to get a resultant translated rectangle?


text:
Q: Why is this retruning itiems that are not "SHOP" Select pnm.pnm_auto_key, pnm.pn, whs.warehouse_code, pnm.loc_auto_key
      from parts_master pnm join warehouse whs on pnm.whs_auto_key = whs.whs_auto_key

     where whs.warehouse_code = 'SHOP'
          pnm.loc_auto_key = '39'
           or pnm.loc_auto_key = '14'

Thank you.
Jeff

A: Because of OR you misused. Should have probably been
where whs.warehouse_code = 'SHOP'
  and (   pnm.loc_auto_key = '39'
       or pnm.loc_auto_key = '14'
      )

Or, why not
where whs.warehouse_code = 'SHOP'
  and pnm.loc_auto_key in ('14', '39')


text:
Q: SharePoint 2013 Visual Studio Workflow ListIId I'm trying to implement some Workflows on SharePoint 2013 using Visual Studio 2012 for learning purposes. The workflow I'm working on now is very simple, it supposed to copy one list item to another list, but I'm getting an exception when obtaining the other ListId.
So here is how it goes,

*

*First I obtain the current list guid using the GetCurrentListId activity and save it to a variable of the type System.Guid.

*After that I obtain the current item guid using the GetCurrentItemGuid activity and save it to another variable of the type System.Guid

*Finally, I use the CopyItem Activity, this activity needs three parameters: ListId, ItemGuid and ToListId. Since I haven't found any activity that gets a ListId, I selected the list I want on the ToListId combobox and it writes this on the expression editor:
System.Guid.Parse("{$ListId:List2;}")

Very simple, right? But when I run the workflow I get this exception:
Dispatcher encountered an unexpected exception: System.Runtime.CallbackException: The call to OnRequestAbort on the WorkflowInstance 'b1eb965e-d6e4-47d3-9170-ae2677897947' threw an exception. This is considered fatal. See inner exception for details. ---> System.AggregateException: Should be processing if notifying about persistable idle. ---> System.AggregateException: One or more errors occurred. ---> System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
I have no idea why is it throwing that exception and I haven't found any other way to obtain the GUID of a list that is not the CurrentList of the workflow context.
A little help please....

A:
From: Shawn Baerwald
  (http://answers.flyppdevportal.com/categories/azure/workflow.aspx?ID=d9b2e284-13e2-431b-8299-b3b4510942ce)

Fix/HACK involves selecting one of the lists, clicking the elipse (...) and in the resulting edit box replace:
System.Guid.Parse("{$ListId:Lists/Tasks;}")

With the list GUID:
System.Guid.Parse("{4CGG7172-6EB0-4414-82E6-92BBE8A5E64A}")


text:
Q: Call to undefined function utf8_decode I looked at other SO answers here and here about this error: FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught Error: Call to undefined function utf8_decode
Both answers say that installing php-xml will fix the error. But that didn't work. I ran sudo apt install php-xml which installed both php-xml and php7.0-xml and I restarted php-fpm and nginx. But I still get the same error.
Also checked function_exists('utf8_decode') and it returns false. So the error is obviously thrown when utf8_decode is called.
The server is Ubuntu 16.04 and PHP 7.0. Here's the phpinfo output (PDF): https://drive.google.com/file/d/0B3GpdAvwm4fOaWMwb0JkTFQyb0U/view?usp=sharing

A: OK so I figured it out. This was related to missing files in /etc/php/7.0/mods-available/
Normally there should be an xml.ini file there but that file was missing because of how I had installed, uninstalled and re-installed PHP. That operation was not done cleanly. After installing PHP from the PPA I had uninstalled it, deleted many files from /etc/php/ (which is not recommended. Use apt-get purge instead).
So long story short, this worked:
sudo apt-get purge php-xml php7.0-xml
sudo apt-get install php-xml

A: Run php -v to check the version of PHP.
If you're running version is 5.6, the solution is as follows:
sudo apt-get install php5.6-mbstring php5.6-mcrypt php5.6-mysql php5.6-xml

Otherwise, run the following:
sudo apt-get install php7.2-mbstring php7.2-mcrypt php7.2-mysql php7.2-xml

A: looking for the modules that I have installed in php
php -m | grep -i xml
after I run this command
yum --enablerepo remi install php-xml

and restart apache
sudo service httpd restart


text:
Q: Why I am getting SAXNotRecognizedException while setting isSupportingExternalEntities? I am getting SAXNotRecognizedException, while trying to set the property of 'isSupportingExternalEntities' in Java 8
final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
sf.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);

Exception:
org.xml.sax.SAXNotRecognizedException: Property 'javax.xml.stream.isSupportingExternalEntities' is not recognized.

A: I guess you use the wrong property for SchemeFactory. According to OWASP docs you should use the following code
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
Schema schema = factory.newSchema(Source);


text:
Q: Image Alignment in Div centered with Jquery SO,
I've got a horizontally and vertically centered div for a landing page. I'm attempting to add an image to the div, but as soon as I insert it, the content of the centered div is either pushed to the bottom of the screen or to one side (see the page here). I've tried to solve the problem with this CSS:
#landlogo {
display: block;
margin-left: auto;
margin-right: auto;
float: left;
clear: both;
}

But to no avail. For some reason, the image refuses to align to the center just above the text like the other components on the page. I suppose there could be an issue with the Jquery that somehow prevents it from properly centering with images, but I thought perhaps I'd run it by the much sharper minds on SO before I try any more in-depth solutions.

A: You have float:left being applied to the img.
As soon as I remove that css in my browser, it centers itself.