text:
Q: unable to get CPP WPTools-(Delphi)-derived components to install in C++Builder I'm working with C++Builder XE6 & XE7. I've derived some CPP components from WPTools (Pascal-based) components and have been unable to get them to work with WPTools7, although they worked fine with WPTools6 and earlier versions of XE.
When trying to build my derived CPP components, Builder does not seem to like the passing by reference code it is finding in the WPTools .HPP files.
Lines like the following:
extern DELPHI_PACKAGE bool __fastcall WPLocateNextPrev(bool Previous, TParagraph* &active_paragraph, int &active_posinpar, bool &EOF);
extern DELPHI_PACKAGE bool __fastcall WPLocateNext(TParagraph* &active_paragraph, int &active_posinpar, bool &EOF);
extern DELPHI_PACKAGE bool __fastcall WPLocatePrev(TParagraph* &active_paragraph, int &active_posinpar, bool &BOF);``

For which I get errors like this:
[bcc32 Error] WPRTEDefs.hpp(6117): extern variable cannot be initialized
[bcc32 Error] WPRTEDefs.hpp(6117): Improper use of typedef 'TParagraph'
[bcc32 Error] WPRTEDefs.hpp(6117): Undefined symbol 'active_paragraph'

It is not apparent to me that the above declarations in the .HPP code is trying to initialize an extern variable, but please enlighten me if that is the case.
The developer, usually helpful in the past, hasn't been very helpful. I'm not sure if he doesn't know what the problem is or if he just doesn't have any other customers who have tried deriving CPP components the way I have.
If I have to give up my CPP WPTools-derived components, it will probably take a month or more to revise all my code, so I am eager to find a solution if there is one. Does anyone know a fix for this?
It is my impression that it is possible to get the same result as passing by reference in C++ if you simply pass a pointer, so long as you do not deference the variable and explicitly check for the NULL value.
I am thinking about modifying the WPTools7 code to see if bypassing this passing by reference thing would fix the trouble, but as others have developed for Delphi and Builder for so much longer than I have, I thought I'd ask for advice before spending too much time on it.
Since the source is in Object Pascal/Delphi, I'll have to try to figure out what not dereferencing means. I'm sort of the impression that everything in Object Pascal is essentially a pointer, but I'm not entirely sure.
In any case, I thought I'd ask if anyone has ever tried something like this? And/or if anyone has any thoughts about whether or not it would help with my troubles, or create any new ones?
Thanks in advance for any help.


text:
Q: Explanation for Big-O notation comparison in different complexity class Why Big-O notation can not compare algorithms in the same complexity class. Please explain, I can not find any detailed explanation.

A: So, O(n^2) says that this algorithm requires less or equal number of operations to perform. So, when you have algorithm A which requires f(n) = 1000n^2 + 2000n + 3000 operations and algorithm B which requires g(n) = n^2 + 10^20 operations. They're both O(n^2)
For small n the first algorithm will perform better than the second one. And for big ns second algorithm looks better since it has 1 * n^2, but first has 1000 * n^2.
Also, h(n) = n is also O(n^2) and k(n) = 5 is O(n^2). So, I can say that k(n) is better than h(n) because I know how these functions look like.
Consider the case when I don't know how functions k(n) and h(n) look like. The only thing I'm given is k(n) ~ O(n^2), h(n) ~ O(n^2). Can I say which function is better? No.
Summary
You can't say which function is better because Big O notation stays for less or equal. And following is true
O(1) is O(n^2)
O(n) is O(n^2)

How to compare functions?
There is Big Omega notation which stays for greater or equal, for example f(n) = n^2 + n + 1, this function is Omega(n^2) and Omega(n) and Omega(1). When function has complexity equal to some asymptotic, Big Theta is used, so for f(n) described above we can say that:
f(n) is O(n^3)
f(n) is O(n^2)
f(n) is Omega(n^2)
f(n) is Omega(n)
f(n) is Theta(n^2) // this is only one way we can describe f(n) using theta notation

So, to compare asymptotics of functions you need to use Theta instead of Big O or Omega.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Memory is leaking for Postgres in Docker I make loading testing for companies service.
Compose version: Docker Compose version v2.4.1
My compose for DB:
version: '3.4'
x-check: &default-healthcheck
  healthcheck:
    test: [ "CMD", "/data/.prepare" ]
    interval: 30s
    timeout: 30s

services:
  postgres-api:
    image: postgres:11
    container_name: 'load-POSTGRES-API'
    restart: unless-stopped
    environment:
      - POSTGRES_USER=test
      - POSTGRES_PASSWORD=test
    command: [
      "postgres",
      "-c",
      "log_statement=all",
      "-c",
      "log_destination=stderr",
      "-c",
      "max_connections=50",
      "-c",
      "shared_buffers=1GB",
      "-c",
      "effective_cache_size=4GB",
      "-c",
      "work_mem=16MB",
      "-c",
      "maintenance_work_mem=512MB",
      "-c",
      "random_page_cost=1.1",
      "-c",
      "temp_file_limit=10GB",
      "-c",
      "log_min_duration_statement=200ms",
      "-c",
      "idle_in_transaction_session_timeout=10s",
      "-c",
      "lock_timeout=1s",
      "-c",
      "statement_timeout=60s",
      "-c",
      "shared_preload_libraries=pg_stat_statements",
      "-c",
      "pg_stat_statements.max=10000",
      "-c",
      "pg_stat_statements.track=all"
    ]
    ports:
      - "${EXT_IP}:${POSTGRES_EXPOSE_API}"
    volumes:
      - ./postgres-l3/data:/data:rw
    deploy:
      resources:
        limits:
          cpus: '1'
          memory: 4G
        reservations:
          memory: 256M
    <<: *default-healthcheck

The allocated memory lasts for 5-10 minutes (depending on the load), then an overflow occurs, the services will not connect to the database and I observe an error:
"message":"the database system is in recovery mode"

Connections are lost, the database memory is cleared and starts to melt quickly again.
The size of all tables is ~50Mb.
How can this be solved? How normal is it?


text:
Q: How to calculate the mod value of a rational/irrational value? We have a course in network security this semester and we are being taught RSA algorithm.
I came across a typical math problem that I was unable to solve here.
$$D*E \equiv 1 \mod{\phi(n)}$$
This became $$D \equiv E^{-1}  \mod{\phi(n)}$$ How do you solve this ???
My lect gave this specific example
$$D \equiv 7^{-1} \mod{160}$$ and the solution for $D$ was $23$! How did she arrive at this.

A: Hint
$7D = 1 \mod 160$
Sol'n

$7D = 1 \mod 160$ and $D = 23 \Longrightarrow 23*7 \mod 160$ satisfies this.

A: D ≡ (mod 160)/7 which is equal to 7D ≡ 1 * (mod 160)
This type of question is a Congruence Relation.
This means that (1 mod 160) = (7D mod 160)
(1 mod 160) simplifies to 1 so that means that (7D mod 160) = 1
This means that 7D/160 must have a remainder of 1
You know that 1 is a possible answer but that would create a decimal when divided by 7 and RSA numbers do not do decimals.
The equation will usually get the number just above but also closest to the modular divisor which in this case is 160+1 or 161.
161/7 = 23

A: https://www.youtube.com/watch?v=mgvA3z-vOzc
Check this out. The problem can be solved using extended Euclidean Algorithm to be precise. For smaller numbers, the answers already mentioned are sufficient.


text:
Q: Evaluate the complex integral: $\int_{|z|=1}xdz$ $\int_{|z|=1}xdz$
I ended up with $2\pi$ as my final answer, can anyone confirm and/or give me a shorter way to do it? Mine involved lots of sines & cosines.

A: $$\int_C x dz=\int_C \frac{z+\overline z}{2} dz\\
\left(z=e^{i\theta}, dz=izd\theta\right)\\
=\int_0^{2\pi}\frac{e^{i\theta}+e^{-i\theta}}{2}ie^{i\theta}d\theta
=\int_0^{2\pi}i\frac{e^{2i\theta}+1}{2}d\theta\\
=\left[\frac{e^{2i\theta}}{4}+i\frac{\theta}{2}\right]_0^{2\pi}=\pi i
$$


text:
Q: Apache sticky session from response header I have a requirement where I need to route a series of requests to the same member
in a load balancer cluster.
The requests look like this:

*

*/server/create-some-id => responds with a unique ID

*/server/do-something-with-id/{ID}

*/server/do-something-with-id/{ID}
... etc.

The requirement is that requests 2 and on have to be routed to the same balancer
member as request 1. Due to some legacy code, I can't just create a cookie in
the response of request 1 to use for routing.
I'm wondering if there's an Apache module which is able to SetEnvIf based on either
a response header or the response body, or any other way to solve this?
Thanks!

A: It does not seem to be possible to enable stickyness based on the response headers or body in Apache 2.


text:
Q: how to get Umbraco landing page to select a child page as default I'm working on an umbraco site using the Fanoe starterkit, where I do not want the vistor to land on the landing page, but be redirected to the first grandchild page underneath that.
So that in the example if the visitor clicks Parent or Child1, they would land on Grandchild 1A, if they clicked on child 2 they would land on grandChild 2A, etc. The client does't want to have 'Parent or Child pages' - just grandchild pages... Thoughts?
Parent
 - Child 1
 -- Grandchild 1A
 -- Grandchild 1B
 - Child 2
 -- Grandchild 2A
 -- Grandchild 2B
 - Child 3

A: Add Umbraco Redirect property (UmbracoRedirect) to your home node and select child page.
Every time you will load home page, it will be redirected to the selected child page.

A: Are these pages all the same document type? If your landing pages are a different document type you add something like this to the template:
if (Model.Content.DocumentTypeAlias == "LandingPage") {
  Response.Redirect(Model.Content.Child.Url);
}


text:
Q: diff to detect only case changes Is there a simple way to have a diff between two versions of a file, showing only those lines/words that differ by a change to upper-/lowercase? All other differences should be omitted.
Background: I have a VBA project under version control (git) and Microsoft's editor tends to change casing every time a new variable is declared. I want to identify (and possibly count) such changes in order to prevent them from being committed.

A: Based on a suggestion from this answer I have done it as follows, using basic Linux scripting tools:
GIT_EXTERNAL_DIFF='diff -p -U 0 "$2" "$5" | cat #' git diff --ext-diff >  cdiff
GIT_EXTERNAL_DIFF='diff -ip -U 0 "$2" "$5" | cat #' git diff --ext-diff > idiff

diff idiff cdiff | grep '^> [+-] '

The code makes first a case-sensitive diff cdiff, second a case-insensitive diff idiff. The case-only changes consist then of the lines in cdiff which are not contained in idiff.


text:
Q: Django REST Framework : update() based on query string parameter Is it possible to modify a ViewSet's update() function to update based on a query string parameter instead of a URL resource name or the request body?
For example, I want trigger something like this:
payload = {'field' : '2'}
r = requests.put("http://127.0.0.1:9876/job-defs?job-def-id=2", data=payload)

and have this update my field when job-def-id = 2.
What I have so far is this:
class JobDefinitionsViewSet(mixins.ListModelMixin,
                        mixins.CreateModelMixin,
                        mixins.UpdateModelMixin,
                        mixins.DestroyModelMixin,
                        viewsets.GenericViewSet):

    serializer_class = JobDefinitionsSerializer

    def update(self, request, pk=None):
        job_def_id = self.request.query_params.get('job-def-id', None)
        super(JobDefinitionsViewSet, self).update(self, request, pk=job_def_id)

    ...
    # other unrelated code
    ...

I'm not too sure how to continue.
I want to reuse as much as the update() function from mixins.UpdateModelMixin as possible.
Any help is appreciated.

A: Assuming you want to use the same url for listing and for retrieving the details of the entity, discriminating on the presence of the url parameter job-def-id, here is a crazy idea:
class JobDefinitionsAllInOneView(mixins.UpdateModelMixin,
                                 mixins.DestroyModelMixin,
                                 mixins.ListModelMixin,
                                 mixins.CreateModelMixin,
                                 generics.GenericAPIView):

    queryset = JobDefinitions.objects.all()
    serializer_class = JobDefinitionsSerializer

    def get_object(self):
        job_def_id = self.request.query_params.get('job-def-id', None)
        if job_def_id is not None:
            self.kwargs['pk'] = job_def_id
        return super(JobDefinitionsAllInOneView, self).get_object()

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        job_def_id = self.request.query_params.get('job-def-id', None)
        if job_def_id is not None:
            # return the details
            return self.retrieve(request, *args, **kwargs)
        else:
            # return a list
            return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def patch(self, request, *args, **kwargs):
        return self.partial_update(self, request, *args, **kwargs)
    def delete(self, request, *args, **kwargs):
        return self.destroy(self, request, *args, **kwargs)

I haven't tried it yet. I had a look at the source code here for get_object and here for the mixins


text:
Q: PostgreSQL: UPDATE ... ON MISSING INSERT? PostgreSQL has "INSERT ... ON CONFLICT UPDATE" construct, but in my queries in most cases I need UPDATE.
So I don't want that DB will try insert and only then update, I want that it will try UPDATE and if the record does not exist - will INSERT.
Is it possible?
Will it increase performance?

A: It will increase performance, and it also depends which code you will have. If you construct a table and then use a separate function to check whether it has the data that you want to add or no, and then do accordingly(if exists- insert else no). In this case your code takes some part of memory. This method is good when working with a mass data, to save even a small part of memmory

A: INSERT INTO hundred(name, name_slug, status)
SELECT DISTINCT name, name_slug, status
FROM hundred
WHERE NOT EXISTS (
 SELECT 'X'
 FROM temp_data
 WHERE temp_data.name = hundred.name AND temp_data.name_slug = hundred.name_slug  AND temp_data.status = status );

To simplify, "where" statement is the key point to do what you want:
   INSERT INTO table (id, field, field2)
   SELECT 3, 'C', 'Z'
   WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);


text:
Q: Find the longest string in matrix a, recursively - Python I want to find the longest string (most repeated char) in a given matrix using recursion. The input given by the user is the matrix, and the start position of the recursion. Another thing is that each element of the matrix can be "checked" by the recursive function only once.
So here is an example:
If my matrix looks like this:
abcdeaab
adfdgagh
madafaff
abaacafr

The result should be start=(5,0), stop=(5,4), c='a'. The result is this, because the char 'a', is the longest string in the matrix, that starts at position (5,0) and ends at (5,4). As you can see, the matrix has to be checked on horizontally and also vertically.
I didn't really used much recursion in past, that's why I got stuck in here.
I've read the article here: http://interactivepython.org/courselib/static/pythonds/Recursion/recursionsimple.html. I understand that in order to achieve what I want to achieve, my program has to obey the three laws of recursion:

*

*A recursive algorithm must have a base case.

*A recursive algorithm must change its state and move toward the base case.

*A recursive algorithm must call itself, recursively.

I started to write the code, and got up to here:
#!/bin/python2.7

#Longest string in matrix

#Given a matrix filled with letters. Find the longest string, containing only the same letter, which can be obtained by starting
#with any position and then moving horizontally and vertically (each cell can be visited no more than 1 time).

# Settings here
# -------------
string_matrix = """
abcdeaab
adfdgagh
madafaff
abaacafr
"""
pos = (0,0)
# -------------

rows = 0
columns = 0
matrix = []
matrix2 = []

def stop():
    for l in matrix2:
        for c in l:
            if c == '1':
                return True
    return False

def search(pos):
    # my base case
    if stop():
        return

    global matrix2
    # matrix2 keeps track of the visited elements of matrix
    matrix2[pos[0]][pos[1]] = 1

def main():
    # create the matrix from string
    string_matrix_l = string_matrix.strip()
    splited = string_matrix_l.split('\n')

    global rows
    global columns
    global matrix
    global matrix2

    rows = len(splited)
    columns = len(splited[1])

    # initialize matrix with 0
    matrix = [[0 for x in range(columns)] for x in range(rows)]
    matrix2 = [[0 for x in range(columns)] for x in range(rows)]

    # print some info
    print 'Given matrix: ' + str(matrix) + '\n'
    print 'Start position: ' + str(pos)

    # set matrix from string
    i = 0
    for s in splited:
        s = s.strip()
        if s == '':
            continue

        j = 0

        for c in s:
            try:
                matrix[i][j] = c
                #print 'ok: ' + str(i) + ' ' + str(j) + ' ' +  c
            except:
                print 'fail: index out of range matrix[' + str(i) + '][' + str(j)+'] ' + c
            j = j + 1

        i = i + 1

        #print s
        #print matrix

    # get the result
    search(pos)

if __name__ == "__main__":
    main()

What my program does (for now), is converting a string into a matrix, and creating another matrix, called matrix2, which will keep track of the elements visited from matrix by the search (recursive) function.
Any advice will be appreciated.

A: First, this problem is hard to solve, and there is no known efficient solution to it, it is called the Longest Path Problem
To find longest path from one cell, you can use a DFS to solve it, which is recursive algorithm by nature.
Python like pseudo-code:
DFS((x,y),visited):
   maxPathLength = -1
   for each neighbor (x1,y1) of (x,y):
        #skip visited nodes, or nodes that are not the same character:
        if (x1,y1) in visited of arr[x][y] != arr[x1][y1]:
           continue
        #node is not visited and same character.
        #mark it as visited:
        visited.add((x1,y1))
        #recurse and store what the longest path found by recursion:
        currLength = DFS((x1,y1),visited)
        #set the max out of all paths:
        maxPathLength = max(maxPathLength, currLength)
   #clean up
   visited.remove((x,y))
   #return an answer:
   return maxPathLength  + 1

It follows your 3 points for recursive algorithms because:

*

*The stop clause in the code: If there are no "unvisited" nodes, the
algorithm will return 0 without invoking the recursive call.

*The algorithm changes the state of the visited nodes, and moves on to the next neighbor, until there is no possible path left, which will be the stop clause.

*The algorithm calls itself recursively for each possible "neighbor" of the current cell.

This algorithm will yield you the longest path from some source cell. You can repeat it for all cells to find the "global" longest path.
This algorithm only provides the length of the longest path, but it is pretty easy to modify it to also remember the path itself, by returning a tuple (length,list) - where list is the cells visited in this path.


text:
Q: Finding list item from javascript generated html Here is all the code I am using for this multiselect box which I found at multiselect page
HTML:
<link href="jquery-ui.css" rel="stylesheet" />
<link href="ui.multiselect.css" rel="stylesheet" />

<form runat="server">
    <select class="multiselect" multiple="true" style="width:460px; height:200px;">
        <option value="AA">AA@gmail.com</option>
        <option value="AB">AB@gmail.com</option>
        <option value="AC">AC@gmail.com</option>
        <option value="AD">AD@gmail.com</option>
        <option value="AE">AE@gmail.com</option>
        <option value="AF">AF@gmail.com</option>
   </select>

    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</form>

C#:
protected void Button1_Click(object sender, EventArgs e)
{
    String[] emailList = new String[1000];
    //find the ul in the html and loop through each li
}

What this all translates into on the client side is this (I'm not sure all of this is 100% correct as I did just copy and paste if from the browser, however all of the relevant information is here):

ev

ev

ev

Now for the question, I need to find and loop through each of those list items in the unordered list, get the title attribute and store it in a string array when the button is clicked. I have already tried to find the control using Form.Request["multiselect"] and Page.FindControl["mutliselect"] but non of those worked. As always any help is welcome, thanks.
EDIT #1:
I looked and searched but there apparantly isn't a way to do this, however, instead of creating a new almost identical question, I'll just edit this one... Is there a way to modify the javascript file from the multiselect box I linked above? I thought if it is possible then it might be easier to just let the javascript add an attribute to the  control within the select... I'm just not sure where in the javascript I can add this, so heres the updated question... Where in this multiselect javascript file must I edit in order to make it add an attribute to the correctly selected option?

A: you can do giving runat="server" and id tags to your html select element
   <select runat="server" Id="SelectList" class="multiselect" multiple="true" style="width:460px; height:200px;">
            <option value="AA">AA@gmail.com</option>
            <option value="AB">AB@gmail.com</option>
            <option value="AC">AC@gmail.com</option>
            <option value="AD">AD@gmail.com</option>
            <option value="AE">AE@gmail.com</option>
            <option value="AF">AF@gmail.com</option>
       </select>

    ***

protected void Button1_Click(object sender, EventArgs e)
{
    (System.Web.UI.HtmlControls.HtmlSelect)SelectList.SelectedIndices..
    String[] emailList = new String[1000];
    //find the ul in the html and loop through each li
}

A: One way, certainly not the most elegant, is to use the HtmlAgiliyPack to scrape your code for the
 elements and extract the title
var doc = new HtmlAgilityPack.HtmlDocument();
//Path to the file on the filesystem
doc.LoadHtml("patch to your htmlfile");

if (!doc.DocumentNode == null)
{
   foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//li[@class='email']"))
   {
       //add title to your array
       //I recommend using a List<string> instead
       //list.Add(node.innerHtml);
   }

}

If you want to load resources from the web you need to use a slightly different code:
var web = new HtmlAgilityPack.HtmlWeb();
var doc = web.Load("http://www.path.com/to/your/file.html");
foreach(var node in doc.DocumentNode.SelectNodes("//li[@class='email']"))
{
  //...
}


text:
Q: MongoDB aggregation via db.runCommand(): $match by date I need to match documents by date in an aggregation query executed in "strict JSON" mode via db.runCommand(). These requirements are dictated by the way JasperReports communicates with MongoDB
Document schema:
{
    "_id" : ObjectId("5a6fca214420c2302a6f8985"),
    "report_date" : ISODate("2018-01-23T00:00:00.000+0000"),
    ...
}

This works in MongoDB console (returns matching documents), but it doesn't work in JasperReports (throwing com.mongodb.util.JSONParseException in the line containing the "ISODate()" command). I'm showing only the first stage of the pipeline for clarity:
db.runCommand(
{
    "aggregate" : "reports",
    "pipeline" : [
        {
            "$match": {
                "report_date": {
                    "$gte": ISODate("2017-01-23")
                }
            }
        }
    ],
    "cursor": {}
})

The same query using $date executes well in both MongoDB and JasperReports, but does not return any documents (0 matches in both scenarios):
db.runCommand(
{
    "aggregate" : "reports",
    "pipeline" : [
        {
            "$match": {
                "report_date": {
                    "$gte": {"$date": "2017-01-23T00:00:00.000Z"}
                }
            }
        }
    ],
    "cursor": {}
})

Here goes a response example for the second query:
{
    "cursor" : {
        "firstBatch" : [ ],
        "id" : NumberLong(0),
        "ns" : "reports"
    },
    "ok" : 1
}

I observe the same behavior in range queries, like in the following snippet:
...
"$gte": {"$date": "2017-01-29T00:00:00.000Z"},
"$lt": {"$date": "2019-01-29T00:00:00.000Z"}
...

I also tried using $dateFromString instead of $date(interestingly, using this one in MongoDB 3.2 didn't result in any exceptions being thrown) - same result.
How can I run queries by date or date ranges in the "match" stage of aggregation pipeline and strict-JSON mode?
Tested versions: MongoDB 3.2.12 and 3.6.2, JasperReports Studio: 6.5.1 final
For any suggestions thanks in advance!


text:
Q: Is there a Social Security Number reserved for testing/examples? Is there a canonical "test SSN" that is used by convention, so is understood by all who see it that it is not a real SSN?

A: I used this 457-55-5462 as testing SSN and it worked for me. I used it at paypal sandbox account. Hope it helps somebody

A: There are multiple number groups and some particular numbers that will never be allocated:

*

*Numbers with all zeros in any digit group (000-xx-####, ###-00-####, ###-xx-0000).

*Numbers with an area group (first three digits) of 666 or any of 900-999.

*Numbers that have been misused in any way, such as the well known 078-05-1120.

Consider using one of these (the obviously invalid 000-00-0000 would be a good one IMO).
(Answer has been updated to provide source information beyond Wikipedia and remove information that is no longer accurate after the SSA made its randomization change in mid 2011.)

A: all zeros would probably be the most obvious that it wasn't a real SSN.

A: To expand on the Wikipedia-based answers:
The Social Security Administration (SSA) explicitly states in this document that the having "000" in the first group of numbers "will NEVER be a valid SSN":

*

*http://www.socialsecurity.gov/employer/stateweb.htm
I'd consider that pretty definitive.
However, that the 2nd or 3rd groups of numbers won't be "00" or "0000" can be inferred from a FAQ that the SSA publishes which indicates that allocation of those groups starts at "01" or "0001":

*

*http://ssa-custhelp.ssa.gov/cgi-bin/ssa.cfg/php/enduser/std_adp.php?p_faqid=87
But this is only a FAQ and it's never outright stated that "00" or "0000" will never be used.
In another FAQ they provide (http://www.socialsecurity.gov/employer/randomizationfaqs.html#a0=6) that "00" or "0000" will never be used.
I can't find a reference to the 'advertisement' reserved SSNs on the SSA site, but it appears that no numbers starting with a 3 digit number higher than 772 (according to the document referenced above) have been assigned yet, but there's nothing I could find that states those numbers are reserved. Wikipedia's reference is a book that I don't have access to. The Wikipedia information on the advertisement reserved numbers is mentioned across the  web, but many are clearly copied from Wikipedia. I think it would be nice to have a citation from the SSA, though I suspect that now that Wikipedia has made the idea popular that these number would now have to be reserved for advertisements even if they weren't initially.
The SSA has a page with a couple of stories about SSN's they've had to retire because they were used in advertisements/samples (maybe the SSA should post a link to whatever their current policy on this might be):

*

*http://www.ssa.gov/history/ssn/misused.html

A: If your testing requires pulling quasi-real credit reports from the bureaus, the inactive SSNs of other answers won't work and you'll need designated test numbers.
I found this site Which appears to contain test social security numbers with associated test names and credit card numbers.
Transunion has a test environment you can link and send data to, including associated dummy credit reports. Sending a SSN to them with certain numbers in certain positions will automatically route the inquiry to their test environment Other credit bureaus will have similar systems in place.

A: Numbers from 987-65-4320 to 987-65-4329 are reserved for use in advertisements.

A: Please look at this document
http://www.socialsecurity.gov/employer/randomization.html
The SSA is instituting a new policy the where all previously unused sequences are will be available for use.
Goes into affect June 25, 2011.
Taken from the new FAQ:
What changes will result from randomization?
The SSA will eliminate the geographical significance of the first three digits of the SSN, currently referred to as the area number, by no longer allocating the area numbers for assignment to individuals in specific states. The significance of the highest group number (the fourth and fifth digits of the SSN) for validation purposes will be eliminated. Randomization will also introduce previously unassigned area numbers for assignment excluding area numbers 000, 666 and 900-999.
Top
Will SSN randomization assign group number (the fourth and fifth digits of the SSN) 00 or serial number (the last four digits of the SSN) 0000?
SSN randomization will not assign group number 00 or serial number 0000. SSNs containing group number 00 or serial number 0000 will continue to be invalid.


text:
Q: Restart VMs with PowerCLI .net C# I have been running into a wall with this one. The goal is to restart VMs utilizing PowerCLI's API with C#. This will be a MVC framework. The user logs in and on the landing page are given a list of servers to restart. Selects server, and restarts one or many of them (checkbox).
My problem is understanding PowerCLI, and what I need. Currently, I have VMware.Vim referenced and that can allow me to connect, get a list of servers. However, I am unsure on how to restart the server via the API. Below are the libraries I installed. I am unsure what else I need other than VMware.Vim to achieve this.
https://code.vmware.com/web/tool/12.0.0/vmware-powercli
I am currently using this youtube video as a starting point. However, any documentation, code examples, or any guidance would be greatly appreciated. This is a bit out of my level, and am completely unfamiliar with PowerCLI.
More documentation.
Thank you very much for your time,
PowerCLINooby

A: This is the code i use in .net to restart the VMs. Only library you need is the VMware.Vim.

*

*First, Get Client thats connected to your vcenter

public static VimClient ConnectToVCenter(string vCenterUrl, string username, string password)
{
    ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

    VimClient client = new VimClientImpl();
    try
    {
        client.Connect($"https://{vCenterUrl}/sdk");
    }
    catch (Exception ex)
    {
        throw new ApplicationException($"Unable to connect to [{vCenterUrl}]. Exception: [{ex.Message}]");
    }
    client.Login(username, password);
    return client;
}

*Get VM

public static VirtualMachine GetVM(VimClient client, string guestVM, ManagedObjectReference parentMoRef = null)
{
    // Lookup VM in vCenter.
    NameValueCollection Filter = new NameValueCollection
    {
        { "name", guestVM }
    };

    List<VirtualMachine> virtualMachines = GetEntities<VirtualMachine>(client, parentMoRef, Filter, null);

    // Do some error checking to make sure your VM was found.
    return virtualMachines.FirstOrDefault();
}

// Helper function that can be used to look up various objects like VirtualMachine, Datastore, etc.
public static List<T> GetEntities<T>(VimClient vimClient, ManagedObjectReference beginEntity, NameValueCollection filter, string[] properties)
{
    return vimClient.FindEntityViews(typeof(T), beginEntity, filter, properties)?.Cast<T>().ToList();
}

*Power up or down or restart the VM

// Use enum for power operations
public enum PowerOp
{
    suspend,
    reset,
    powerOff,
    gracefulOff,
    powerOn,
    powerOnWaitForTools,
    gracefulReboot,
    standby
}

public static void PowerOperation(VimClient client, VirtualMachine vm, PowerOp operation)
{
    switch (operation)
    {
        case PowerOp.suspend:
            if (vm.Runtime.PowerState != VirtualMachinePowerState.suspended)
                client.WaitForTask(vm.SuspendVM_Task());
            break;

        case PowerOp.reset:
            client.WaitForTask(vm.ResetVM_Task());
            break;

        case PowerOp.powerOff:
            if (vm.Runtime.PowerState != VirtualMachinePowerState.poweredOff)
            {
                client.WaitForTask(vm.PowerOffVM_Task());
            }
            break;

        case PowerOp.powerOn:
            if (vm.Runtime.PowerState != VirtualMachinePowerState.poweredOn)
            {
                client.WaitForTask(vm.PowerOnVM_Task(vm.Runtime.Host));
            }
            break;

        case PowerOp.powerOnWaitForTools:
            if (vm.Runtime.PowerState != VirtualMachinePowerState.poweredOn)
            {
                client.WaitForTask(vm.PowerOnVM_Task(vm.Runtime.Host));
            }
            vm.WaitForTools(client);
            break;

        case PowerOp.gracefulReboot:
            vm.RebootGuest();
            Thread.Sleep(10000); // Wait at least 10 seconds to let the server start with reboot.
            vm.WaitForTools(client);
            Thread.Sleep(5000); // Just a precaution.
            break;

        case PowerOp.gracefulOff:
            if (vm.Runtime.PowerState != VirtualMachinePowerState.poweredOff)
                vm.ShutdownGuest();
            vm.WaitForPowerState(client, VirtualMachinePowerState.poweredOff);
            break;

        case PowerOp.standby:
            vm.StandbyGuest();
            break;

        default:
            throw new ApplicationException($"Error: Unknown power operation requested");
    }
}


text:
Q: Can a User resume the chat on different channels(Facebook messenger or Skype) ? where the session should not be lost I want to make one bot by joining multiple channels like Facebook messenger , Alexa,Native app , Web chat to have a seamless and friction less experience.
User should be able to open and initiate a chat session in-app and close it but not lose the session So that I can easily instigate a chat session with a bot or agent from within the app.
For an instance If I am a user chatting on Facebook messenger bot and after sometime i close it and open the chat bot on the webpage So I should be able to resume the same chat on that channel means session of the user's chat should not be lost.

A: First of all, bot application connects to mulitiple channels and each channel has its distinct users from others. So as @christophe-willemsen said, you need to build up your own account system and link to all the channels your bot connect. With which, you need to pair the session data with the user.
Then, you can leverage Manage state data to store and access user data. And leverage Advance the waterfall to manage the waterfall steps inside the dialogs.
For quick reference:
let savedSession;
var bot = new builder.UniversalBot(connector, [(session) => {
    if (savedSession) {
        var [savedDialog] = savedSession.dialogStack().slice(-2, -1);
        console.log(savedDialog);
        session.replaceDialog(savedDialog.id, savedDialog.state)
    } else {
        savedSession = session;
        session.beginDialog('form');
    }
}]);

bot.dialog('form', [...waterfall steps...])


text:
Q: I can't figure out the bug in this jQuery The page having problems is...
http://schnell.dreamhosters.com/index.php?page=gallery#
I use Firebug to debug my jQuery and other code tidbits and it's been proving very useful for Javascript/jQuery debugging.  However, at the same time, it's been one of the most frustrating debugging experiences I've ever gone through.  I'm not sure why but sometimes it seems like I can copy someone else's methodology from a tutorial, character for character, and yet still come up with errors.
In any case, the problem here is that Firebug claims there is a bug on line 20 of the source.
missing : after property id
[Break on this error] $('#table').animate({"left: " + attr + "px"}, 2000);\n
This bug seems like a huge load to me because the colon is right there!  And this is why debugging jQuery/Javascript is such a pain sometimes.  The error messages are rather convoluted and sometimes don't even make a lick of sense to me. Or maybe that's just Firebug.
Either way, the goal I'm going for here is that I'm trying to dynamically change the animate function such that the more you click the left arrow, the further left the grid of images is shifted (due to the nature of the CSS 'left' property).  I have Javascript variables and a hidden input tag to help hold essential values, but the major hurdle is getting the animate function to recognize these variables.  Near as I can tell it will only accept string literals for arguments on how to animate and the documentation doesn't help me because it doesn't discuss the use of variables with animate, as if it's impossible.
Well, let's just say I don't like impossible, he likes to get in my way a lot.

A: The object literal passed to the animate function is not well formed, it should be:
$('#table').animate({left: attr + "px"}, 2000);

Edit: Looking closely to your code, you are also trying to get a value from an input with id = "count", and you have a missing # character to have an ID selector:
var count = +$('#count').val(); // get #count value as Number

You are also incrementing this count variable, but you should first convert it to Number, because  the value attribute of input elements are string. (I did it using the unary plus operator on the right-hand side of the assignment).
You have to convert it to a number, because if you add two variables and one of them is a string, concatenation will take place:
 "1" + 1 == "11"

A: Try:
$('#table').animate({left: attr}, 2000);

The "px" units of measurement here aren't necessary. That aside, the above is the correct creation of an anonymous object. You were just putting a string inside curly braces.


text:
Q: Uniformly convergence question I have the following exercise:
Let $\varphi:[0,+\infty)\to \mathbb{R}$ an increasing continuous function that satisfies that $1/2\leq \varphi(x) <1$ for all $x>0$. Let $f_0:[0,+\infty)\to \mathbb{R}$ an increasing function (not necessarily continuous) such that $f_0(0)>0$. For all $x \in[0,+\infty)$, define:
$f_{n+1}(x)=\varphi(x)f_n(x)+\frac{1}{\varphi(x) f_n(x)}$, $n \geq 1$. Show that $(f_n)_{n \in \mathbb{N}}$ converges uniformly in all bounded interval $[0,R]$
I know that if $(f_n)$ is monotone for all n, $(f_n) \to f$ and $f$ is continuous, then $(f_n)$ converges uniformly. By definition of $f_n$, I notice that I only need to prove that $(f_n) \to f$ pointwise. I know that every increasing and bounded sequence converges (Theorem of monotone convergence). My question is, can I use that theorem in a sequence of functions? Is there an easier way to prove the exercise?


text:
Q: mdadm array is active but is not listed I am running Ubuntu Server 12.04. I did apt-get upgrade and received a warning from mdadm.
update-initramfs: Generating /boot/initrd.img-3.11.0-24-generic
W: mdadm: the array /dev/md3 with UUID e3d153f0:6edf1702:1f51fb89:78ee93fe
W: mdadm: is currently active, but it is not listed in mdadm.conf. if
W: mdadm: it is needed for boot, then YOUR SYSTEM IS NOW UNBOOTABLE!
W: mdadm: please inspect the output of /usr/share/mdadm/mkconf, compare
W: mdadm: it to /etc/mdadm/mdadm.conf, and make the necessary changes.
W: mdadm: the array /dev/md1 with UUID 76492e25:648c4dcd:1f51fb89:78ee93fe
W: mdadm: is currently active, but it is not listed in mdadm.conf. if
W: mdadm: it is needed for boot, then YOUR SYSTEM IS NOW UNBOOTABLE!
W: mdadm: please inspect the output of /usr/share/mdadm/mkconf, compare
W: mdadm: it to /etc/mdadm/mdadm.conf, and make the necessary changes.

My current mdadm.conf is:
# mdadm.conf
#
# Please refer to mdadm.conf(5) for information about this file.
#

# by default, scan all partitions (/proc/partitions) for MD superblocks.
# alternatively, specify devices to scan, using wildcards if desired.
DEVICE partitions

# auto-create devices with Debian standard permissions
CREATE owner=root group=disk mode=0660 auto=yes

# automatically tag new arrays as belonging to the local system
HOMEHOST <system>

# instruct the monitoring daemon where to send mail alerts
MAILADDR root

# definitions of existing MD arrays

# This file was auto-generated on Tue, 11 May 2010 20:53:30 +0200
# by mkconf $Id$

ARRAY /dev/md1 level=raid1 num-devices=2 devices=/dev/sda1,/dev/sdb1
ARRAY /dev/md3 level=raid1 num-devices=2 devices=/dev/sda3,/dev/sdb3

The config generated by /usr/share/mdadm/mkconf is:
# mdadm.conf
#
# Please refer to mdadm.conf(5) for information about this file.
#

# by default (built-in), scan all partitions (/proc/partitions) and all
# containers for MD superblocks. alternatively, specify devices to scan, using
# wildcards if desired.
#DEVICE partitions

# auto-create devices with Debian standard permissions
CREATE owner=root group=disk mode=0660 auto=yes

# automatically tag new arrays as belonging to the local system
HOMEHOST <system>

# instruct the monitoring daemon where to send mail alerts
MAILADDR root

# definitions of existing MD arrays
ARRAY /dev/md1 UUID=76492e25:648c4dcd:1f51fb89:78ee93fe
ARRAY /dev/md3 UUID=e3d153f0:6edf1702:1f51fb89:78ee93fe

The warning says that /dev/md1 and /dev/md3 are not listed even though they are in the config. Is it okay change the config to the second one or will this cause problems?

A: The only difference I see is this line:
#DEVICE partitions
This is commented out in the generated config file but not yours. I'd just uncomment that and commit the changes. Warnings like that tend to be a "head's up" thing rather than an actual problem if the configurations line up.


text:
Q: Where does the default numa setting come from? when we run:
numactl --hardware

we can see the current status of numa setting.
However, it seems not set by Linux ( at least, I didn't add a parameter to set it ).
Did it set by BIOS?

A: https://github.com/torvalds/linux/blob/59fc453b21f767f2fb0ff4dc0a947e9b9c9e6d14/arch/x86/mm/numa.c#L649
should parse SRAT which from BIOS.


text:
Q: Flutter :- Issues in model i've accessed img_path but not able to access image because want to concatenate (img_path+image) to display in home page? I  want to fetch images from API. I've created a model class but the problem is I have accessed the img_path from the model class but am not able to access the image from the model class because I want to concatenate img_path+image to display on the home page. Below I've mentioned the model class and home page code. please find and check the below classes.
Home Page :-
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'NavDrawer.dart';
import 'package:carousel_slider/carousel_slider.dart';

import 'banner_model.dart';

var paddingBottom = 48.0;
var androidDeviceInfo;
var identifier;
var token = "debendra";
var token1;

class HomePage extends StatelessWidget {
  final String apiUrl1 = "https://newbharatbiz.in/mobile_api/v4/all_banner.php";

  Future<BannerModel> fetchAlbum() async {
    final response = await http.get(Uri.parse(apiUrl1));

    if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.
      return BannerModel.fromJson(jsonDecode(response.body));
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load album');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        drawer: NavDrawer(),
        appBar:
            AppBar(title: Text('New Bharat Biz'), centerTitle: true, actions: [
          IconButton(
            onPressed: () async {},
            icon: Icon(Icons.search),
          ),
        ]),
        body: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
          FutureBuilder<BannerModel>(
            future: fetchAlbum(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                final List<String> imagesList = [
                  snapshot.data!.imgPath + "1542696267.png"
                ];
                return Container(
                  child: CarouselSlider(
                    options: CarouselOptions(
                      height: 330,
                      aspectRatio: 16 / 9,
                      viewportFraction: 0.8,
                      initialPage: 0,
                      enableInfiniteScroll: true,
                      reverse: false,
                      autoPlay: true,
                      autoPlayInterval: Duration(seconds: 3),
                      autoPlayAnimationDuration: Duration(milliseconds: 800),
                      autoPlayCurve: Curves.fastOutSlowIn,
                      enlargeCenterPage: true,
                    ),
                    items: imagesList
                        .map(
                          (item) => Container(
                            child: Center(
                                child: Image.network(item,
                                    fit: BoxFit.cover, width: 1000)),
                          ),
                        )
                        .toList(),
                  ),
                );
              }
              // By default, show a loading spinner.
              return Center(
                child: SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation(Colors.blue),
                  ),
                ),
              );
            },
          )
        ]));
  }
}

Model Class :
// To parse this JSON data, do
//
//     final bannerModel = bannerModelFromJson(jsonString);

import 'dart:convert';

BannerModel bannerModelFromJson(String str) => BannerModel.fromJson(json.decode(str));

String bannerModelToJson(BannerModel data) => json.encode(data.toJson());

class BannerModel {
  BannerModel({
    required this.status,
    required this.imgPath,
    required this.banner,
  });

  int status;
  String imgPath;
  List<Banner> banner;

  factory BannerModel.fromJson(Map<String, dynamic> json) => BannerModel(
    status: json["status"],
    imgPath: json["img_path"],
    banner: List<Banner>.from(json["Banner"].map((x) => Banner.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "status": status,
    "img_path": imgPath,
    "Banner": List<dynamic>.from(banner.map((x) => x.toJson())),
  };
}
 class Banner {
  Banner({
    required this.id,
    required this.type,
    required this.parentId,
    required this.title,
    required this.caption,
    required this.image,
    required this.link,
    required this.status,
    required this.sliderOrder,
    required this.entryTime,
  });

  String id;
  String type;
  String parentId;
  String title;
  String caption;
  String image;
  String link;
  String status;
  String sliderOrder;
  DateTime entryTime;

  factory Banner.fromJson(Map<String, dynamic> json) => Banner(
    id: json["id"],
    type: json["type"],
    parentId: json["parent_id"],
    title: json["title"],
    caption: json["caption"],
    image: json["image"],
    link: json["link"],
    status: json["status"],
    sliderOrder: json["slider_order"],
    entryTime: DateTime.parse(json["entry_time"]),
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "type": type,
    "parent_id": parentId,
    "title": title,
    "caption": caption,
    "image": image,
    "link": link,
    "status": status,
    "slider_order": sliderOrder,
    "entry_time": entryTime.toIso8601String(),
  };
}

A: If my understanding is correct, you want to show images in the Banner. So you should populate your imagesList like this:
List<String> imagesList = [];
snapshot.data!.banner.foreach((e) {
   imagesList.add(snapshot.data!.imgPath+"/"+e.image);
});


text:
Q: How to add javascript string value to a value in hidden field in ASP The closest I got to using in webpage was as follows:

It works with lets say:

However I would like it to be used in the value in asp hidden field
eg
<asp:HiddenField ID="name" runat="server" Value="title" />

I am new to asp and javascript and jquery so any advice greatly appreciated.

A: Try to use:
$("[id$='name']").val(movie.title);

A: With jquery:
$('#name').val(movie.title);

OR
$('#<%= name.ClientId %>').val(movie.title)

With javascript
document.getelementid('name').value=movie.title;

A: You need to use Control.ClientID to get the Client ID of ASP.NET Control. After that you can simply use ID Selector and .val()
Use (jQuery)
$('#<%= name.ClientId %>').val(movie.title);

With Vanilla JS
document.getElementById('<%= name.ClientId %>').value=movie.title;

A: Try this..You have to set clientidmode property to static..
<asp:HiddenField ID="name" runat="server" Value="title" clientidmode="static"/>

After that set..
document.getelementid('name').value=movie.title;


text:
Q: Google Play Alpha Version needs unintall first I have a published app and just uploaded an alpha version with higher version no. I have  also defined a google group as a tester group.
The members in this group should unistall and install again my app in order to get the new alpha version?
Or this is done automatically?


text:
Q: Populate DropDownList in ASP.NET MVC from database table using Entity Framework 6 and ViewModel I have been scratching my head for a whole night on an issue I can do quickly using ajax/jquery and stored procedures. I want to
1) Populate a drop down list from values obtained from a database table using Entity Framework and view model. I DO NOT WANT TO USE VIEWBAG OR VIEWDATA. Any help appreciated.
2) How can I generate a Create View using the View Model with the all the default fields ? The scaffholding works on a model but not on a view model ?
MY MODELS
public class Employee
{
    public int EmployeeID { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public string City { get; set; }
    public string Level { get; set; }
    public int DepartmentId { get; set; }
}

public class Grade
{
    public int ID { get; set; }
    public string Level { get; set; }
}

View Model
public class GradeSelectListViewModel
{

    public Employee Employee { get; set; }
    public IEnumerable<SelectListItem> Grades { get; set; }
    public GradeSelectListViewModel(Employee employee, IEnumerable grades)
    {
        Employee = employee;
        Grades = new SelectList(grades, "Grade", "Name", employee.Level);
    }
}

MY CONTEXT CLASS
public class EmployeeContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<Grade> Grades { get; set; }
}

MY CONTROLLER
public ActionResult Edit (int? id)
{
    using (var db = new EmployeeContext())
    {
        var model = new GradeSelectListViewModel(db.Employees.Find(id), db.Grades);
        //model.Employee = db.Employees.Single(x => x.EmployeeID == id);
        model.Grades = db.Grades.ToList().Select(x => new SelectListItem
        {
            Value = x.ID.ToString(),
            Text = x.Level
        });
        return View(model);
    }
}

MY RAZOR PAGE CSHTML
@model MVCDemo.ViewModels.GradeSelectListViewModel
....
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    ....
    @Html.DropDownListFor(x => Model.Employee.Level,
        new SelectList(Model.Grades, "ID", "Level"),
        "Select Level")
    ....
    <input type="submit" value="Create" class="btn btn-default" />
}

A: The main issue is that in the view you have new SelectList(Model.Grades, "ID", "Level") but Grades is IEnumerable<SelectListItem> and SelectListItem does not contain properties named ID and Level.
However there are a a few other issues with your code. First a view model should not contain a data model, and instead your view model should be
public class GradeSelectListViewModel
{
    public int? ID { get; set; } // make this ID so you do not need an input for it
    public string Name { get; set; }
    .... // other properties of Employee that your editing
    [Required(ErrorMessage = "..")]
    public int? Level { get; set; } // make value types nullable to protect against under-posting attacks
    public IEnumerable<SelectListItem> Grades { get; set; }
}

and add display and validation attributes as required. Note that I deleted the constructor (you don't seem to be using it, but if you did, then you also need to include a parameter-less constructor, otherwise an exception will be thrown when submitting to the POST method. I also assume that Level should be typeof int since you binding to the int ID property of Grade.
The the code in your GET method should be
Employee employee = db.Employees.Find(id);
var model = new GradeSelectListViewModel()
{
    ID = employee.EmployeeID,
    Name = employee.Name,
    Level = employee.Level, // convert to int?
    ....
    Grades = db.Grades.Select(x => new SelectListItem
    {
        Value = x.ID.ToString(),
        Text = x.Level
    })
};
return View(model);

and in the view
 @Html.DropDownListFor(x => Model.Level, Model.Grades, "Select Level")

Note also that in the POST method, your need to reassign the SelectList if you return the view because ModelState is invalid.

A: You can use the following approach that populates three DropDownListFor at the same View:
ViewModel:
public class GroupViewModel
{
    public IEnumerable<SelectListItem> Schedules { get; set; }
    public int ScheduleId { get; set; }

    public IEnumerable<SelectListItem> Labs { get; set; }
    public int LabId { get; set; }

    public IEnumerable<SelectListItem> Terms { get; set; }
    public int TermId { get; set; }
}

Controller:
public ActionResult Create()
{
    //Populate DropDownList binding values
    var model = new GroupViewModel
    {
        //Preselect the Lab with id 2
        //LabId = 2,

        Labs = repository.Labs.Select(c => new SelectListItem
        {
            Value = c.Id.ToString(),
            Text = c.Name
        }),
        Terms = repository.Terms.Select(c => new SelectListItem
        {
            Value = c.Id.ToString(),
            Text = c.Name
        }),
        Schedules = repository.Schedules.Select(c => new SelectListItem
        {
            Value = c.Id.ToString(),
            Text = c.Name
        })
    };
    return View("Create", model);
}

View:
@Html.DropDownListFor(m => m.LabId, new SelectList(Model.Labs, "Value", "Text"),
    "Select", new { @class = "selectpicker" })

@Html.DropDownListFor(m => m.ScheduleId, new SelectList(Model.Schedules, "Value", "Text"),
    "Select", new { @class = "selectpicker" })

@Html.DropDownListFor(m => m.TermId, new SelectList(Model.Terms, "Value", "Text"),
    "Select", new { @class = "selectpicker" })


text:
Q: TA-Lib as layer in AWS Lambda I have spent many, many hours to try to find out how to create a layer with TA-Lib in AWS Lamda. I'm a newbie using AWS Lambda but I have managed to create layers for pandas etc. using Docker but not for TA-Lib. I'm using Python 3.7. See below:
pip3 install ta-lib -t /layer_dir/python

error: command 'gcc' failed: No such file or directory: 'gcc'
Failed to build ta-lib
    ERROR: Could not build wheels for ta-lib, which is required to install pyproject.toml-based projects

Is there an easier way? I just want to be able to use TA-lib. Thanks!


text:
Q: Are java global variables guaranteed to initialize first? Not actually global variables, but just variables that are class-wide.
For example, I have this initialization:
MyObj obj = new MyObj();

And then I have this method:
public void Foo(){
    obj.doSomething;
}

Let's say that I'm not able to use a constructor(this is pertaining to android). Will the variable be guaranteed to always be initialized before any methods in the class is called?

A: (To be clear: 1) Java doesn't have global variables. 2) Java has class (i.e. static) fields and instance fields, as well as local variables.  3) The example appears to show an instance field, so I am assuming that is what you are asking about.)

Are java global variables guaranteed to initialize first?

Yes.  Except in pathological cases that I will explain below.
When an object is created, the following things are done in the following order:

*

*The object is allocated on the heap with the correct object type, and all instance fields are "default initialized" to zero, false or null.

*The expressions in the super(...) or this(...) are evaluated and the constructor for the next class up the chain is called.  (This recurses up the chain constructor, so that the Object constructor gets executed first.)

*The instance variable initializers and any instance initializer blocks are executed in order.

*The body of the constructor is executed.

*The constructor returns.
All of this happens when you execute new SomeClass(...).
So, in your example (as written), you can sure that the instance variable obj will be initialized before your method is called.

Now for the pathological cases.  Consider this:
public class Foo {

    private int a = someMethod();
    private int b = 42;

    public Foo() {
    }

    private int someMethod() {
        return this.b;
    }
}

In this case, the initializer for a will call someMethod before b has been initialized, and hence someMethod will return the default initial value of b ... zero.  You could also "implement" the pathological example using an instance initialize block.  However, if you called someMethod within the Foo constructor, you can be sure that the instance variable's initializer will have been executed.
Indeed there are other pathological cases to consider.  If  the implementation of someMethod in the above were to call a method in another class, passing this as an argument, then the other class could call methods on the partially initialized Foo instance.  (This is called unsafe publication.  It is particularly insidious if the partially initialized instance can be accessed by another thread, because that invalidates various Java memory model guarantees.)

A:
Will the variable be guaranteed to always be initialized before any methods in the class is called?

Yes. You are correct. It's already initialized since it's declared even on top of constructor and ready for the use later.
And it's up to you, where you are going to use that instance member, weather in constructor or in methods later, but it's guaranteed to initialize before the constructor called.

A: First of all, it's not a global variable. It's an instance variable. It is guaranteed to be initialized before the constructor is called, so it is guaranteed to be initialized when Foo is called.

A: That is what Myobj() is. It is a default constructor and it gets overridden if you explicitly define a constructor in your class.
All variables gets its memory as soon as You make its Object (Reference Variable) and class get its space as soon as the new keyword gets compiled even before your statement MyObj obj = new MyObj(); gets compiled.


text:
Q: Stanford NLP caseless models via maven Are the caseless models available via maven? If so, how? Are they just for English? I've tried various options, including:
<dependency>
    <groupId>edu.stanford.nlp</groupId>
    <artifactId>stanford-corenlp</artifactId>
    <version>${corenlp.version}</version>
</dependency>
<dependency>
    <groupId>edu.stanford.nlp</groupId>
    <artifactId>stanford-corenlp</artifactId>
    <version>${corenlp.version}</version>
    <classifier>models</classifier>
</dependency>
<dependency>
    <groupId>edu.stanford.nlp</groupId>
    <artifactId>stanford-corenlp</artifactId>
    <version>${corenlp.version}</version>
    <classifier>models-caseless</classifier>
</dependency>

Thanks.

A: Unfortunately at this time the caseless models are not in Maven.  I will note your request and I'll see if we can get the caseless models into future Maven releases.


text:
Q: angular-translate translate in translation file Is it possible to pass a variable into a translation file, and have it translated inside the translation file?
// translation.json
"country":{
    "CHINA":"中国",
    "US":"United States"
}

"text":"I live in $translate('country.{{country}}'), {{ someOtherVar }}.

A: I believe this structure below would help for you to achieve what you want.
In the English translation file
"country": {
    "CHINA": "China",
    "US": "United States",
    ...
},
"text":"I live in {{country}}, {{ someOtherVar }}."

In the Chinese translation file
"country": {
    "CHINA": "中国",
    "US": "美国",
    ...
},
"text":"我住在{{country}}, {{ someOtherVar }}."

In HTML

In controller
$scope.someothervar = // some value
var countrykey = //CHINA or US...
$translate('country.' + countrykey).then(function(trans){
    $scope.translated_country_name = trans;
})

A: You could always preprocess the translation file (e.g. by $httpProvider.interceptors).
But you have the country variable available for you from (probably) the scope.
So you should write something like this:
var country = ...;
country = $translate(country);
$scope.translatedText = $translate('text', { country: country, someOtherVar: 'value' });

where your text should be:
"text":"I live in {{country}}, {{ someOtherVar }}."

Here you've got the documentation for dynamic translation.


text:
Q: Continuously differentiable functions are weakly differentiable Let $\Omega\subseteq\mathbb R^n$ be a bounded domain and $u\in C^1(\Omega)$. I want to show, that $u$ is weakly differentiable, i.e. $$\int_\Omega\psi\frac{\partial u}{\partial x_i}d\lambda^n=-\int_\Omega u\frac{\partial \psi}{\partial x_i}d\lambda^n\;\;\;\text{for all }\psi\in C_c^1(\Omega)\;.$$ It doesn't seem to be elementary provable. Do we need to approximate $u$ or $\partial_iu$ in some way?

A: The proof that you are looking for can be found in the page 258 of the Evans book:


text:
Q: How does git generate diff in files? What mechanism does git follow while diffing files? How is git able to tell me the difference between the two files(two commits, etc)?
Does it follow any key-value pair mechanism where line number is the key and value is the hash and if the hash changes, the line is marked as the changed line?

A: Your original question asked about binary files, which in Git, means "files that Git has decided are not text".  For such files, unless you provide a special diff driver, Git does not attempt to generate a diff, it only says "these two files are the same" or "these two files are different".  (A diff driver is an external program: you can instruct Git to run this program instead, and this program can do whatever it wants to do with the pair of files, to generate a useable diff.)
Your updated question, at least as of this time, asks about diffing text files.  Git has built into it a modified version of LibXDiff.  The main algorithm here is due to Eugene Myers.  See also Myers diff algorithm vs Hunt–McIlroy algorithm.  For a somewhat more user-friendly introduction to diff algorithms, see the last section of chapter 3 of my stalled book.  You are in fact onto something with the idea of line hashes: these diff algorithms compare symbols, and using a line-hash as the symbols in the diff matrix is how they find line-by-line diffs.

A: Probably it generates a checksum of the file and compare those, if they are different the file will be marked as modified, but it will not tell you the difference because simply it doesn't know it.


text:
Q: how can i install shield project how can i create setup for my program that i wrote by c# and used sql server 2005 and used designer report....
this program that i write with c# has a folder include pictures audio and sub folders that need to install on another pc that want to use this program  .
how can i create setup for it with install shield ... i have install shield application on version 10   that doesn't support .net4 . please help me .
when i create setup .. my program can be run by all information like data base and pictures and ..... can't be perform . i can upload my program if you want to help me . thanks all;

A: Perhaps use an alternative? Microsoft seem to be putting a lot of weight behind WiX http://wixtoolset.org/ for building installers (it's used for Visual Studio and Office).
There is also a tutorial at http://wix.tramontana.co.hu/ , and a lot of knowledge here on Stack Overflow: https://stackoverflow.com/questions/tagged/wix?sort=newest


text:
Q: No indentation after theorem environment with amsthm I use the amsthm package and dont want lines which start right after the theorem environment to be indented. I consulted the manual of the package and it said to define a new theorem style. I expected the following MWE to accomplish this task.
\documentclass[12pt,a4paper]{scrreprt}

\usepackage{amsthm}
\newtheoremstyle{abcd}% name
  {}%      Space above, empty = `usual value'
  {}%      Space below
  {\itshape}% Body font
  {}%         Indent amount (empty = no indent, \parindent = para indent)
  {\bfseries}% Thm head font
  {.}%        Punctuation after thm head
  {.5em}% Space after thm head: \newline = linebreak
  {}%         Thm head spec
\theoremstyle{abcd}

\newtheorem{defn}{Definition}
\begin{document}
\begin{defn}
Some defintion
\end{defn}
This sentence shouldn't be indented.
\end{document}

However, I end up with this

That is what I would expect (obtained using a noindent right after the theorem environment ends)

A: You can fix this on a single theorem type basis by patching \end<name>:
\documentclass{article}

\usepackage{etoolbox}
\usepackage{amsthm}

\newtheoremstyle{abcd}% name
  {}%      Space above, empty = `usual value'
  {}%      Space below
  {\itshape}% Body font
  {}%         Indent amount (empty = no indent, \parindent = para indent)
  {\bfseries}% Thm head font
  {.}%        Punctuation after thm head
  {.5em}% Space after thm head: \newline = linebreak
  {}%         Thm head spec

\theoremstyle{abcd}
\newtheorem{defn}{Definition}

\makeatletter
\patchcmd{\enddefn}{\@endpefalse}{}{}{}
\makeatother

\begin{document}

\begin{defn}
Some definition
\end{defn}
This sentence shouldn't be indented.

\begin{defn}
Some definition
\end{defn}

This sentence should be indented.

\end{document}

The style choice has no influence.
In order to get the same behavior for all theorem environments, change the definition of \@endtheorem.
\documentclass{article}

\usepackage{amsthm}

\makeatletter
\def\@endtheorem{\endtrivlist}
\makeatother

\newtheoremstyle{abcd}% name
  {}%      Space above, empty = `usual value'
  {}%      Space below
  {\itshape}% Body font
  {}%         Indent amount (empty = no indent, \parindent = para indent)
  {\bfseries}% Thm head font
  {.}%        Punctuation after thm head
  {.5em}% Space after thm head: \newline = linebreak
  {}%         Thm head spec

\theoremstyle{abcd}
\newtheorem{defn}{Definition}

\begin{document}

\begin{defn}
Some definition
\end{defn}
This sentence shouldn't be indented.

\begin{defn}
Some definition
\end{defn}

This sentence should be indented.

\end{document}

Another example, showing this doesn't add unwanted space when two theorem environments follow each other.
\documentclass{scrbook}

\usepackage{amsthm}
\makeatletter
\def\@endtheorem{\endtrivlist}
\makeatother

\theoremstyle{plain}
\newtheorem{thm}{Theorem}[chapter]
\newtheorem*{thm*}{Theorem}

\begin{document}

\chapter{Chapter}

\section{Section}

Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.

\begin{thm}
    Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem.
\end{thm}
No indentation. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.

\begin{thm}
    Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem.
\end{thm}

\begin{thm}
    Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem. Theorem.
\end{thm}

Indentation. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.

\end{document}

A: \documentclass[12pt,a4paper]{scrreprt}
\usepackage{amsthm}
\usepackage{etoolbox}

\newtheorem{defn}{Definition}
\AfterEndEnvironment{defn}{\noindent\ignorespaces}

\begin{document}
\begin{defn}
Some definition.
\end{defn}
This sentence isn't indented.
\end{document}

However this goes against intuition; the sentence after a definition (or any other theorem-like structure) logically starts a new paragraph, so its first line should be treated as any other first line of a new paragraph.


text:
Q: preg_replace_callback not applied to every html string hello i've edited a simple function to change characters with their greec similar look .here the code
function homographit($string){

$alphabet = array("A", "B", "C", "E", "H", "J", "K", "M", "N", "O", "P", "S", "T", "X", "Y",
"a", "b", "c", "e", "i", "j", "k", "o", "p", "r", "s", "v", "x", "y");

$Greec   = array("\u0391", "\u0392", "\u0421", "\u0395", "\u0397", "\u0408", "\u039A", "\u039C", "\u039D", "\u039F", "\u03A1", "\u0405",
"\u03A4", "\u03A7", "\u03A5", "\u0430", "\u042C", "\u0441", "\u0435", "\u0456", "\u0458", "\u03BA", "\u03BF", "\u03C1", "\u0433", "\u0455",
"\u03BD", "\u03C7", "\u0443");

$newstring = str_replace($alphabet, $Greec, $string);
return json_decode('"'.$newstring.'"', true);
}

$html = '
 some text i want to replace

some stuff i want to replace
';

$text_to_echo =  preg_replace_callback(
    "/(<([^.]+)>)([^<]+)(<\\/\\2>)/s",
    function($matches){
$text= homographit($matches[3]);
        return $matches[1].$text.$matches[4];
    },
    $html
);
echo $text_to_echo;

for this html string it's ok to change all text:
$html = '
 some text i want to replace

some stuff i want to replace
';

but if i change with this one:
$html = '
 Lina has blueeyes and my bruno has dark green  eyes
';

my fucntion homographit is applied to a party of text .
any nhelp to change the pattern in preg_replace_callback to apply change to any text in html string ?
thx

A: You can change the RegEx to not match a complete html tag of the form <tag>some text</tag>. Instead change it to look for any text between the character > and <. The RegEx should look like this:
/(?<=>)([^>]+)(?=<)/

With the changed RegEx you might need to change the callback function to work with the correct group matches. Also see the example on https://regex101.com/r/xk2kDg/1, notice the green selections in the example input.


text:
Q: Exception throws when insert data into druid via tranquility i'm pushing kafka stream into druid via tranquility.
kafka version is 0.9.1 , tranquility is 0.8 , druid is 0.10.
tranquility is started fine when no message produced,but when producer sending message  i will get JsonMappingException like this:
ava.lang.IllegalArgumentException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
 at [Source: N/A; line: -1, column: -1]
    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:2774) ~[com.fasterxml.jackson.core.jackson-databind-2.4.6.jar:2.4.6]
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:2700) ~[com.fasterxml.jackson.core.jackson-databind-2.4.6.jar:2.4.6]
    at com.metamx.tranquility.druid.DruidBeams$.makeFireDepartment(DruidBeams.scala:406) ~[io.druid.tranquility-core-0.8.0.jar:0.8.0]
    at com.metamx.tranquility.druid.DruidBeams$.fromConfigInternal(DruidBeams.scala:291) ~[io.druid.tranquility-core-0.8.0.jar:0.8.0]
    at com.metamx.tranquility.druid.DruidBeams$.fromConfig(DruidBeams.scala:199) ~[io.druid.tranquility-core-0.8.0.jar:0.8.0]
    at com.metamx.tranquility.kafka.KafkaBeamUtils$.createTranquilizer(KafkaBeamUtils.scala:40) ~[io.druid.tranquility-kafka-0.8.0.jar:0.8.0]
    at com.metamx.tranquility.kafka.KafkaBeamUtils.createTranquilizer(KafkaBeamUtils.scala) ~[io.druid.tranquility-kafka-0.8.0.jar:0.8.0]
    at com.metamx.tranquility.kafka.writer.TranquilityEventWriter.<init>(TranquilityEventWriter.java:64) ~[io.druid.tranquility-kafka-0.8.0.jar:0.8.0]
    at com.metamx.tranquility.kafka.writer.WriterController.createWriter(WriterController.java:171) ~[io.druid.tranquility-kafka-0.8.0.jar:0.8.0]
    at com.metamx.tranquility.kafka.writer.WriterController.getWriter(WriterController.java:98) ~[io.druid.tranquility-kafka-0.8.0.jar:0.8.0]
    at com.metamx.tranquility.kafka.KafkaConsumer$2.run(KafkaConsumer.java:231) ~[io.druid.tranquility-kafka-0.8.0.jar:0.8.0]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [na:1.7.0_67]
    at java.util.concurrent.FutureTask.run(FutureTask.java:262) [na:1.7.0_67]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_67]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_67]
    at java.lang.Thread.run(Thread.java:745) [na:1.7.0_67]

and my kafka.json is :
{
  "dataSources" : {
     "stock-index-topic" : {
      "spec" : {
        "dataSchema" : {
          "dataSource" : "stock-index-topic",
          "parser" : {
            "type" : "string",
            "parseSpec" : {
              "timestampSpec" : {
                "column" : "timestamp",
                "format" : "auto"
              },
              "dimensionsSpec" : {
                "dimensions" : ["code","name","acronym","market","tradeVolume","totalValueTraded","preClosePx","openPrice","highPrice","lowPrice","tradePrice","closePx","timestamp"],
                "dimensionExclusions" : [
                  "timestamp",
                  "value"
                ]
              },
              "format" : "json"
            }
          },
          "granularitySpec" : {
            "type" : "uniform",
            "segmentGranularity" : "DAY",
            "queryGranularity" : "none",
            "intervals":"no"
          },
          "metricsSpec" : [
            {
              "name" : "firstPrice",
              "type" : "doubleFirst",
              "fieldName" : "tradePrice"
            },{
              "name" : "lastPrice",
              "type" : "doubleLast",
              "fieldName" : "tradePrice"
            }, {
              "name" : "minPrice",
              "type" : "doubleMin",
              "fieldName" : "tradePrice"
            }, {
              "name" : "maxPrice",
              "type" : "doubleMax",
              "fieldName" : "tradePrice"
            }
          ]
        },
        "ioConfig" : {
          "type" : "realtime"
        },
        "tuningConfig" : {
          "type" : "realtime",
          "maxRowsInMemory" : "100000",
          "intermediatePersistPeriod" : "PT10M",
          "windowPeriod" : "PT10M"
        }
      },
      "properties" : {
        "task.partitions" : "1",
        "task.replicants" : "1",
        "topicPattern" : "stock-index-topic"
      }
    }
  },
  "properties" : {
    "zookeeper.connect" : "localhost:2181",
    "druid.discovery.curator.path" : "/druid/discovery",
    "druid.selectors.indexing.serviceName" : "druid/overlord",
    "commit.periodMillis" : "15000",
    "consumer.numThreads" : "2",
    "kafka.zookeeper.connect" : "localhost:2181",
    "kafka.group.id" : "tranquility-kafka"
  }
}

i use the kafka-console-consumer to get the data ,it looks like
{"code": "399982", "name": "500等权", "acronym": "500DQ", "market": "102", "tradeVolume": 0, "totalValueTraded": 0.0, "preClosePx": 0.0, "openPrice": 0.0, "highPrice": 0.0, "lowPrice": 0.0, "tradePrice": 7184.7142, "closePx": 0.0, "timestamp": "2017-05-16T09:06:39.000+08:00"}

Any idea why? Thanks.

A: "metricsSpec" : [
            {
              "name" : "firstPrice",
              "type" : "doubleFirst",
              "fieldName" : "tradePrice"
            },{
              "name" : "lastPrice",
              "type" : "doubleLast",
              "fieldName" : "tradePrice"
            }, {
              "name" : "minPrice",
              "type" : "doubleMin",
              "fieldName" : "tradePrice"
            }, {
              "name" : "maxPrice",
              "type" : "doubleMax",
              "fieldName" : "tradePrice"
            }
          ]
        },

it's wrong.The document said :
First and Last aggregator cannot be used in ingestion spec, and should only be specified as part of queries.
So,the issue is solved.


text:
Q: jQuery.load() - Inside External Javascript i load an external page with
 $('#myContainer').load('myfile.html');

in myfile.html theres an
<script type="text/javascript" src="otherscript.js"></script>

Some users report that the otherscript.js is not loaded... i've tested a all common browsers (firefox, ie 6/7, safari, opera etc.) - i cant figure out why this wont work...
an other think is... according to my firebug the browser wont cache the otherscript.js.. it loads with

otherscript.js?_=1234785

(timestamp here :) )
Anyone has an idea why some browsers doesnt support that and.. how can i enable that caching?
MFG
Christopher

A: The .load functions only loads html. Since you are not allowed to load external scripts in to the browser by the browser security protocol. But luckily there's .getScript to get around this. Check it out: http://docs.jquery.com/Ajax/jQuery.getScript
..fredrik

A: to avoid problems with the cache, you can do the following:
$('#myContainer').load('myfile.html?'+(new Date()).getTime());

in myfile.html:
<script type="text/javascript">

var script = document.createElement("script");
script.setAttribute('type','text/javascript');
script.setAttribute('src','otherscript.js?'+(new Date()).getTime());
document.body.appendChild(script);

</script>

accommodating this code to your need.

A: As fredrik pointed out, .load does not load external files, however it will pass the result to html to execute any javascript that's there.
I had a similar issue and I came up with this solution that extracts any script tags from the results that have a src attribute, then use $.getScript to load the attribute value.
$('#exmple').load(url, function(result) {
    $(result).filter('script[src]').each(function () {
        var script = $(this).attr('src');
        $.getScript(script);
    });
});


text:
Q: IOException: write failed: EINVAL (Invalid argument) on UVC FileOutputStream in Kotlin I'm trying to write Android Camera stream frames to the UVC Buffer using FileOutputStream. For context: the UVC Driver is working on the device and it has a custom built kernel.
I get 24 frames per second using imageAnalyzer:
imageAnalyzer = ImageAnalysis.Builder()
.setTargetAspectRatio(screenAspectRatio)
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)
...
imageAnalysis.setAnalyzer(cameraExecutor) { image ->
val buffer = image.planes[0].buffer
val data = buffer.toByteArray()
...
}

Then based on UVC Specifications I build the header of the frame:
val header = ByteBuffer.allocate(26)
val frameSize = image.width * image.height * ImageFormat.getBitsPerPixel(image.format) / 8
val EOH = 0x01
val ERR = 0x00
val STI = 0x01
val REST = 0x00
val SRC = 0x00
val PTS = (System.currentTimeMillis() - referenceTime) * 10000
val endOfFrame = 0x01
val FID = (frameId).toByte()

Add all of the above to the header
header.putInt(frameSize)
header.putShort(image.width.toShort())
header.putShort(image.height.toShort())
header.put(image.format.toByte())
header.put(((EOH shl 7) or (ERR shl 6) or (STI shl 5) or (REST shl 4) or SRC).toByte())
header.putLong(PTS)
header.put(endOfFrame.toByte())
header.put(FID)

Open the FileOutputStream and try to write the header and the image:
val uvcFileOutputStream = FileOutputStream("/dev/video3", true)
uvcFileOutputStream.write(header.toByteArray() + data)
uvcFileOutputStream.close()

Tried to tweak the header/payload but I'm still getting the same error:
java.io.IOException: write failed: EINVAL (Invalid argument)
at libcore.io.IoBridge.write(IoBridge.java:654)
at java.io.FileOutputStream.write(FileOutputStream.java:401)
at java.io.FileOutputStream.write(FileOutputStream.java:379)

What could I be doing wrong? is the header format wrong?

A: I don't know the answer directly, but I was curious to look and have some findings. I focused on the Kotlin part, as I don't know about UVC and because I suspect the problem to be there.
Huge assumption
Since there's no link to the specification I just found this source:
https://www.usb.org/document-library/video-class-v15-document-set
within the ZIP I looked at USB_Video_Payload_Frame_Based_1.5.pdf
Page 9, Section 2.1 Payload Header
I'm basing all my findings on this, so if I got this wrong, everything else is. It could still lead to a solution though if you validated the same things.
Finding 1: HLE is wrong
HLE is the length of the header, not the image data. You're putting the whole image size there (all the RGB byte data). Table 2-1 describes PTS and SCR bits control whether PTS and SCR are present. This means that if they're 0 in BFH then the header is shorter. This is why HLE is either 2, 6, 12.
Confirmation source + the fact that the field is 1 byte long (each row of Table 2-1 is 1 byte/8 bits) which means the header can be only up to 255 bytes long.
Finding 2: all the header is misaligned
Since your putting HLE with putInt, you're writing 4 bytes, from this point on, everything is messed up in the header, the flags depend on image size, etc.
Finding 3: SCR and PTS flag inconsistencies
Assuming I was wrong about 1 and 2. You're still setting the SRC and PTS bit to 0, but pushing a long (8 bytes).
Finding 4: wrong source
Actually, something is really off at this point, so I looked at your referenced GitHub ticket and found a better example of what your code represents:
Sadly, I was unable to match up what your header structure is, so I'm going to assume that you are implementing something very similar to what I was looking at, because all PDFs had pretty much the same header table.
Finding 5: HLE is wrong or missing
Assuming you need to start with the image size, the HLE is still wrong because it's the image format's type, not in connection with SCR and PTS flags.
Finding 6: BFH is missing fields
If you're following one of these specs, the BFH is always one byte with 8 bits. This is confirmed by how the shls are putting it together in your code and the descriptions of each flag (flag = true|false / 1/0).
Finding 7: PTS is wrong
Multiplying something that is millisecond precise by 10000 looks strange. The doc says "at most 450 microseconds", if you're trying to convert between ms and us, I think the multiplier would be just 1000. Either way it is only an int (4 bytes) large, definitely not a long.
Finding 8: coding assistant?
I have a feeling after reading all this, that Copilot, ChatGPT or other generator wrote your original code. This sound confirmed by you looking for a  reputable source.
Finding 9: reputable source example
If I were you I would try to find a working example of this in GitHub, using keyword search like this: https://github.com/search?q=hle+pts+sti+eoh+fid+scr+bfh&type=code the languages don't really matter since these are binary file/stream formats, so regardless of language they should be produced and read the same way.
Finding 10: bit order
Have a look at big endian / little endian byte order. If you look at Table 2-1 in the PDF I linked you can see which bit should map to which byte. You can specify the order you need easily on the buffer BEFORE writing to it, by the looks of the PDF it is header.order(ByteOrder.LITTLE_ENDIAN). I think conventionally 0 is the lowest bit and 31 is the highest. I can't cite a source on this, I seem to remember from uni. Bit 0 should be the 2^0 component (1) and bit 7 is the 2^7 (128). Reversing it would make things much harder to compute and comprehend. So PTS [7:0] means that byte is the lowest 8 bits of the 32 bit PTS number.

If you link to your specification source, I can revise what I wrote, but likely will find very similar guesses.


text:
Q: How to assign a shortcut key to send my system into hibernation? I want to assign a shortcut key for the Hibernate functionality. I have Fn + F11 for hibernation in Windows, but it's not working on Ubuntu. It's getting in sleep mode instead.
I've also tired changing the keyboard shortcut option as Ctrl + H with command pm-hibernate, but still it didn't work. I referred this Ubuntu Forums Thread but couldn't find any solution for this.
Any solution please?

A: If you need to setup hibernation shortcut sequence, you go to Ubuntu System settings (Ctrl+Alt+T and then typing gnome-control-center) and then choosing keyboard settings.

Under that, you will see a tab that says "shortcuts", and there will be an option to set a custom command :

Then you will need to put the command you want to hibernate your computer.

A: Firstly, Hibernate will need to be enabled. Go into console and type
sudo gedit /var/lib/polkit-1/localauthority/50-local.d/hibernate.pkla

In the new gedit window, copy-paste this in:
[Re-enable Hibernate]
Identity=unix-user:*
Action=org.freedesktop.upower.hibernate
ResultActive=yes

Save and close the file, reboot the computer, and then you have it available as a menu option. Assuming you're on a laptop, the fn + F11 shortcut should work afterwards as well, if this is a default option that came with the laptop (i.e. printed on the keyboard, etc.).


text:
Q: React render previous values during conditional fade out animation I am using react-transition-group to fade out various components. I'm converting simple conditional renders such as:
{valueToDisplay && <MyComponent {...valueToDisplay} />}

To transitions such as:
<CSSTransition
    in={!!valueToDisplay}
    unmountOnExit
    classNames="fade"
    addEndListener={(node, done) => node.addEventListener("transitionend", done, false)}
>
    <MyComponent {...valueToDisplay} />
</CSSTransition>

The issue I'm running into is when the "in" property of the transition becomes false, and the exit transition is running, the child component will now have null prop values. This can cause exceptions or cause the child content to flash and change during the exit. What I would like to see instead is that during the exit transition, the content will remain unchanged.
The first solution I came up with was to make child components to cache previous values of their props, and then use those previous values when their props become null. However I don't like this solution because it forces all components which will be transitioned to introduce new and confusing internal logic.
The second attempt I made was to create a wrapper component which cached the previous value of props.children, and whenever "in" becomes false, renders the cached children instead. This essentially "freezes" the children as they were the last time in was true, and they don't change during the exit transition. (If this solution is the general practice, is there a better way of doing this, perhaps with the useMemo hook?)
For such a common use case of fading content out, this solution doesn't seem very intuitive. I can't help but feeling I'm going about this the wrong way. I can't really find any examples of having to cache/memoize content to keep it displaying during fade outs. It seems like something somewhere has to remember the values to display when performing the exit transition. What am I missing?
Here is a minimal example and working example:
import { useRef, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { CSSTransition } from 'react-transition-group';

const Pet = ({ type, age }) => {
  return (

      Your pet {type || 'null'} is age {age || 'null'}

  );
};

const Fade = ({ show, children }) => {
  const nodeRef = useRef(null);

  return (
    <CSSTransition
      nodeRef={nodeRef}
      in={show}
      unmountOnExit
      classNames="fade"
      addEndListener={(done) => nodeRef.current.addEventListener("transitionend", done, false)}
    >

        {children}

    </CSSTransition>
  );
};

const FadeWithMemo = ({ show, children }) => {
  const previousChildren = useRef();

  useEffect(() => {
    previousChildren.current = show ? children : null;
  }, [show, children]);

  return (
    <Fade show={show}>
      {show ? children : previousChildren.current}
    </Fade>
  );
};

const Example = () => {
  const [currentPet, setCurrentPet] = useState(null);

  const getPet = () => {
    return {
      type: (Math.random() > .5) ? 'Cat' : 'Dog',
      age: Math.floor(Math.random() * 15) + 1
    };
  };

  return (
    <>
      <button onClick={() => setCurrentPet(getPet())}>Set</button>
      <button onClick={() => setCurrentPet(null)}>Clear</button>

        The Problem:
        <Fade show={!!currentPet}>
          <Pet {...currentPet} />
        </Fade>

        Potential Fix:
        <FadeWithMemo show={!!currentPet}>
          <Pet {...currentPet} />
        </FadeWithMemo>

    </>
  );
};

const root = createRoot(document.getElementById('root'));
root.render(<Example />);

A: You can detach the visible condition from the pet state so that you have more granular control over whether something is visible and what is actually being displayed.
const Example = () => {
  const [currentPet, setCurrentPet] = useState(null);
  const [showPet, setShowPet] = useState(false);

  const getPet = () => {
    return {
      type: (Math.random() > .5) ? 'Cat' : 'Dog',
      age: Math.floor(Math.random() * 15) + 1
    };
  };

  return (
    <>
      <button onClick={() => {
        setCurrentPet(getPet());
        setShowPet(true);
      }}>Set</button>
      <button onClick={() => setShowPet(false)}>Clear</button>

        <Fade show={showPet}>
          <Pet {...currentPet} />
        </Fade>

    </>
  );
};

or you can have the visible be part of the pet state and only set that part to false.


text:
Q: Is it true that exists a natural number (zero excluded) that is divisible by every natural number? I have the following formula:
$(\exists x)(\forall y) r(x,y)$
Is this formula true in a model where r(x,y) is a binary predicate interpreted as "x is divisible by y" and the universe is all natural numbers except for zero? Why?

A: Why are you excluding $0$?
The statement is true for $0$ (because $x*0= 0$ is true for all $x$).
But for any $y\ne 0$ the statement, which is equivalent to state $\frac xy$ is an integer, is obviously false.  What if $y > x$?  Then if $x>0$ we have $0< \frac xy < 1$. What if $y = 2x$.  The we have $\frac x{2x} = \frac 12$.


text:
Q: JMeter API set content-type I'm introducing in JMeter Pure java, how to set content-type application/json in httpSampler?

// HTTP Sampler
        HTTPSampler httpSampler = new HTTPSampler();
        httpSampler.setDomain("localhost");
        httpSampler.setPort(8080);
  httpSampler.setPath("/posts");
        httpSampler.setMethod("POST");
        httpSampler.setName("API");

  String data = "{\"items\":[{\"stacking_limit\":null,\"id\":\"MLA60428354\",\"weight\":300,\"height\":20,\"only_rotate_axis\":null,\"width\":35,\"length\":45,\"quantity\":1}],\"pack\":{\"weight\":2000,\"height\":100,\"width\":100,\"length\":100}}";
  httpSampler.addNonEncodedArgument("", data, "");
  httpSampler.setPostBodyRaw(true);

  HeaderManager headerManager = new HeaderManager();
  Header h = new Header("Content-Type", "application/json");
  headerManager.add(h);
  httpSampler.setHeaderManager(headerManager);

When I send a post to the server, I check that headers contain application/x-www-form-urlencoded, how to change it?

A: The similar question has been asked in the discussion of the Five Ways To Launch a JMeter Test without Using the JMeter GUI article, here is the essential part of the solution:
// Create Header Manager
HeaderManager manager = new HeaderManager();
manager.add(new Header("Content-Type", "application/json"));
manager.setName(JMeterUtils.getResString("header_manager_title"));
manager.setProperty(TestElement.TEST_CLASS, HeaderManager.class.getName());
manager.setProperty(TestElement.GUI_CLASS, HeaderPanel.class.getName());

// Create HTTP Sampler
HTTPSamplerProxy httpSampler = new HTTPSamplerProxy();
httpSampler.setDomain("localhost");
httpSampler.setPort(8080);
httpSampler.setPath("/posts");
httpSampler.setMethod("POST");
httpSampler.setName("API");
httpSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
httpSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());

//Add HTTP Header Manager to HTTP Sampler
HashTree httpSamplerTree = new HashTree();
httpSamplerTree.add(httpSampler, manager);


text:
Q: Bootstrap Table: sort by date field I am using this Bootstrap table plugin. But sorting by date is not working properly.
Here is the code:

            <?= 'expiry date' ?>

Date is in this format: d/m/y (17/7/14)
How I can fix it in order to sort dates properly?

A: You must use a custom sorter with "data-sorter" attribute like data-sorter="datesSorter"
Then to fit your needs :
function datesSorter(a, b) {
  if (new Date(a) < new Date(b)) return 1;
  if (new Date(a) > new Date(b)) return -1;
  return 0;
}

A: Put at the begining of  content the date translate to number like this
{{strtotime($date)}}

A: I use a function with a short syntax, with the 'data-sorter' option:

      ID
      Item Name
      Item Date

A: You must use a custom sorter with "data-sorter" attribute like data-sorter="datesSorter".
Then to fit your needs:
function datesSorter(a, b) {
    return Date.parse(a) - Date.parse(b);
}

A: I got it working like this....
I added a new column  (numerical) and set it to hidden. You could do that easily by converting that date to a number.
$('#mainTable').bootstrapTable({
    sortStable: true,
    pagination: true,
    pageSize: 100,
    toolbar:"#toolbar",
    search: true,
    searchOnEnterKey: false,
    sortOrder: "desc",sortOrder: "desc",

    // here we determine the column that will sort the table
    sortName: "rel0",
    columns: [
        {
            // this is the hidden numeric column that works as sorter
            field: 'rel0',
            title: 'rel0',
            visible:false,
        },
        {
            // this is the visible column
            field: 'rel',
            title: 'Date / hour',
        },
    ],
    data: objetoData
});


text:
Q: I tried to install ionic but it returns : npm ERR! code E418 I have a serious problem. I tried to install ionic, cordova, angular, react-native-cli, https-status-error and other packages and it always returns:
npm ERR! code E418
npm ERR! 418 I'm a teapot: ionic @ latest

Please note that it may be wrong and I do not understand what is happening. It was fine until 3 days ago.

A: Work for me!
If you set proxy should be unset.
npm config delete proxy
npm config delete https-proxy

Solution resolve npm ^___^
npm cache clean --force
npm cache verify

A: I had the very same issue and managed to fix it.
In my case, I initially had the value of "http://registry.npmjs.org/" and changed it to "https". Below are the set of commands I ran:
npm config set registry https://registry.npmjs.org/
npm cache clean --force
npm cache verify

npm install

A: we have to add proxy information in .npmrc file with userid and password. You will not find any issues. Recently people are getting http 418 - tea pot issues. That we can fix setting up registry with https like below
USE THIS:
proxy=http://<>:<>@<>:8080/
https-proxy=http://<>:<>@<>:8080/
registry=https://registry.npmjs.org

A: Are you behind a coorporate proxy? I was facing the same error when I tried to run npm install. What I did was to remove the proxy configuration from NPM, like so:
npm config rm proxy

npm config rm https-proxy

That did the trick.

A: So, post may 29th '18, this is the common error being faced worldwide by devs working behind corporate proxies. The following tweak fixed the issue for me:

*

*Go to your .npmrc file.
you'll have the following similar content in the file depending upon the configs you are setting up-
strict-ssl=false
registry=http://registry.npmjs.org/
python=C:/Python27/python.exe
msvs_version=2015
http-proxy=<WHATEVER-PROXY-YOU-USUALLY-ADD>:8000

Note: Ignore the extra configs like python variable path.

*Update the registry link to 'https://registry.npmjs.org/'. So your file would look like this now-
 strict-ssl=false
 registry=https://registry.npmjs.org/
 python=C:/Python27/python.exe
 msvs_version=2015
 http-proxy=<WHATEVER-PROXY-YOU-USUALLY-ADD>:8000

*And Viola! you are all set to fire your npm install commands :)

A:
418 I'm a teapot: This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, and is not expected to be implemented by actual HTTP servers.

However, we know at least one implementation does exist now.
It's a bug or weird joke.
As @TomLingham suggested, follow https://github.com/npm/npm/issues/20791 to watch progress resolving the issue and for some workarounds.
For example yarn still healthy.

A: After visiting many sites and testing everything i found,
This Solution finally worked for me. If you are using Windows,

*

*Click windows button and type "run"

*Type .npmrc and open this file using your favorite editor.

*Replace "registry=http://registry.npmjs.org/" with "registry=https://registry.npmjs.org/" and save.

Note: If you have any proxy issues too..you can set your proxy like below in the same file. In my case i have a special symbol "@" in my password.
When i tried changing proxy using npm config set proxy command these special characters got converted to something else :) So you could eliminate all these headaches if you set your proxy along in this file directly.
Your final .npmrc should look like below. you could remove proxy lines if you do not have any issues with proxy and do not forget to replace the port in below example with your proxy port.
registry=https://registry.npmjs.org/
proxy=http://username:password@yourproxy.net:8080/
https-proxy=http://username:password@yourproxy.net:8080/
strict-ssl=false

A: I too ran into the same problem today, It looks like we all are in the same boat.
https://github.com/npm/npm/issues/20791. Some solutions are provided in the link. You might want to look into it if it is a pressing issue.