text:
Q: HDF5 dataset from MATLAB to Pandas DataFrame in Python I have .mat files with HDF5 data and I want to load it into Python (Pandas DataFrame).  I can load the file:
f2 = h5py.File("file.mat")
f2['data']

which is an HDF5 dataset:
<HDF5 dataset "data": shape (9999999, 32), type "<f8">
If I read it with Pandas:
g = pd.read_hdf("file.mat",'data')

I get the following error:
cannot create a storer if the object is not existing nor a value are passed
How do I convert this to a Pandas DataFrame?

A: AFAIK you can't read HDF5 files using Pandas methods, that have NOT been written using Pandas.
You can read them using one of the following approaches:
read matlab v7.3 file into python list of numpy arrays via h5py
Reading ALL variables in a .mat file with python h5py
http://poquitopicante.blogspot.de/2014/05/loading-matlab-mat-file-into-pandas.html
Read .mat files in Python

A: In the first example your file is "file.mat" and in the second "data.mat"


text:
Q: Valuation of a particular element I am tying to compute the valuation of a particular element of $\mathbb{Q}_p$.

I am trying to compute $\operatorname{val}_p(P)$ where $P=\frac{\log(1+p^2)}{\log(1+p)}$ and $\log$ is the $p$-adic $\log$ map.

So $\operatorname{val}_p(P)=\operatorname{val}_p(\log(1+p^2))-\operatorname{val}_p(\log(1+p))$. But I think
$\operatorname{val}_p(\log(1+p^2))=\operatorname{val}_p(1+p^2)=0$ and $\operatorname{val}_p(\log(1+p))=0$, so $\operatorname{val}_p(P)=0$.
Is my solution right?

A: Recall that the logarithm's definition

$$\log(1+x)=\sum_{n=1}^\infty {(-1)^{n+1}x^n\over n}$$

gives the first term in the series for $\log(1+p^k)$ as having (additive) valuation $k$, since
$$\log(1+p^k)=-p^k+O(p^{k+1}), p>2$$
and the strong triangle inequality says this is all you get in this case. If $p=2$ you get $\log(1+p)$ to have valuation $2$ since the first two terms cancel, and the fourth reaches the minimum valuation at ${2^4\over 4}=4$ (valuation $2$) so that $\log\left({1+p^2\over 1+p}\right)$ has (additive) valuation $2-1=1$ in the odd prime case, and (additive) valuation $2-2=0$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to initialize the database in sails.js? How can I initialize my database in Sails.js? I want to parse some big XML files and insert them into the database, so that my Sails-API can handle the requests.
I would like to insert the data via Waterline and not with the REST API. Is there an opportunity to create management commands (like in Django), so I can do something like sails init-database which would run my script that parses the XML and inserts it directly via the Waterline model classes?
I can't use bootstrap.js for this kind of task, because I don't want to create the database contents every time sails is lifted. Is there a command line argument, where I can disable running the bootstrap.js?

A: module.exports.bootstrap = function (cb) {
  Model.count().exec(function (err, count) {
    if (err) return cb(err);
    if (count > 0) return cb();

    Model.create(initdata).exec(cb);
  });
};

A: You can use bootstrap.js for that purpose, simply add some logic in it to test if your XML datas where already inserted. with something like that
module.exports.bootstrap = function(cb) {
  MyModelDefinedInXML.find({Afield : "A value I know"}).exec(function(err,res){
  if(err){ //manage it ;}
  if(res.length>0){
          //skip
          cb();
      }else{
          //perform insert
          cb();
      }
  });
}

For dev you simply don't set sails.config.models.migrate so if you want to reset everything you can choose option "3" in order to wipe/drop everything in your DB.


text:
Q: Messenger Bot: Webview form action I have a chatbot and I want to use webview forms when the "survey" is "non-linear"
I have this form. What to "place" in the action if I want to tell the bot to catch the data?
<form action="I SEARCHING FOR THIS" method="GET">
  <input type="text" name="foo" placeholder="foo" />
  <input type="text" name="bar" placeholder="bar" />
  <button type="submit">SUBMIT</button>
</form>

A: Action should be sent to the URL for your webhook. Also, if you are sending data you should POST not GET.


text:
Q: Batch Files - Error Handling in .bat file I have a .bat file which runs four python files. I need to have some error handling in this .bat file. Basically if any thing goes wrong I want to stop the process.
--Want to stop the process when any of that python script fails.
--Want to run as normal when none of the python fails.
python "C:\EarthSQL-Testing\mckayplod.py" "C:\EarthSQL-Testing"
IF %ERRORLEVEL% EQ 0  GOTO :Next
IF %ERRORLEVEL% NEQ 0 ECHO PYTHON ERROR HAS FOUND ->Error.txt
Copy "C:\EarthSQL-Testing\Error.txt"  "C:\Users\EarthSQL\EarthSQL\Documents - Documents\ErrorLog\" /y
PAUSE

:Next
python "C:\EarthSQL-Testing\mckaypersonnel.py" "C:\EarthSQL-Testing"
IF %ERRORLEVEL% EQ 0  GOTO :Next
IF %ERRORLEVEL% NEQ 0 ECHO PYTHON ERROR HAS FOUND ->Error.txt
Copy "C:\EarthSQL-Testing\Error.txt"  "C:\Users\EarthSQL\EarthSQL\Documents - Documents\ErrorLog\" /y
PAUSE

:Next
python "C:\EarthSQL-Testing\mckaydrilling.py" "C:\EarthSQL-Testing"
IF %ERRORLEVEL% EQ 0  GOTO :Next
IF %ERRORLEVEL% NEQ 0 ECHO PYTHON ERROR HAS FOUND ->Error.txt
Copy "C:\EarthSQL-Testing\Error.txt"  "C:\Users\EarthSQL\EarthSQL\Documents - Documents\ErrorLog\" /y
PAUSE

:Next
python "C:\EarthSQL-Testing\mckactivities.py" "C:\EarthSQL-Testing"
IF %ERRORLEVEL% EQ 0  GOTO :Next
IF %ERRORLEVEL% NEQ 0 ECHO PYTHON ERROR HAS FOUND ->Error.txt
Copy "C:\EarthSQL-Testing\Error.txt"  "C:\Users\EarthSQL\EarthSQL\Documents - Documents\ErrorLog\" /y
PAUSE

Currently the above script, it is running only first python file and then it doesn't run the 2nd python file and onwards files. Any help what is wrong in my batch file ????

A: This may not make a difference but I suggest trying swapping out EQ with == and NEQ with !==!


text:
Q: Twitter Bootstrap inclusion issue I am having some trouble showing Bootstrap components on my page in a Visual Studio using Asp.Net MVC 5. I am using these examples here for the drop down and here for the button groups.
This is what the page looks like:

This is the page source that gets generated
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>NewIndex</title>

    <link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>
<link href="/Content/justified-nav.css" rel="stylesheet"/>

    New Index page

        <button class="btn dropdown-toggle sr-only" type="button" id="dropdownMenu2" data-toggle="dropdown">
            Dropdown

        </button>

Action

Another action

Something else here

Separated link

        <button type="button" class="btn btn-default">Left</button>
        <button type="button" class="btn btn-default">Middle</button>
        <button type="button" class="btn btn-default">Right</button>

All of the referenced files are there in their respective paths. Any idea on what could be wrong?

A: As per my comment :
You should add CSS file with link tag, instead of  block. Script block is used for adding the Javascript.
Adding External Style Sheet (CSS) on your web page:

Each page must include a link to the style sheet with the  tag.
  The  tag goes inside the head section:

<link rel="stylesheet" type="text/css" href="yourstyle.css">

Try this:
<link rel="stylesheet" type="text/css" href="/Content/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="/Content/site.css" />
<link rel="stylesheet" type="text/css" href="/Content/justified-nav.css" />

According to the @cvrebert comment, You must include the Jquery library references (jquery-1.10.2.js) before the other javascript files. the correct order of the Script File is:

As i mentioned above you must put your link tag into head section. So the correct HTML of page look like this -

    <meta name="viewport" content="width=device-width" />
    <title>NewIndex</title>

    <link rel="stylesheet" type="text/css" href="/Content/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="/Content/site.css" />
    <link rel="stylesheet" type="text/css" href="/Content/justified-nav.css" />

        New Index page

Dropdown header

            ...

Dropdown header

            ...

        <button class="btn dropdown-toggle sr-only" type="button" id="dropdownMenu1" data-toggle="dropdown">
            Dropdown

        </button>

Action

Another action

Something else here

Separated link

A: Change your bootstrap.css references from script tags to link tags.. example:
<link href="../Styles/mystyle.min.css" rel="stylesheet" />


text:
Q: Segmentation fault 11: while trying to input B[1] using cin I'm having a problem in running the following code. It is giving me a segmentation fault as a runtime error.
#include <iostream>
using namespace std;

int main()
{
    int n;
    cout << "Enter n: ";
    cin >> n;

    float A[n][n], x[n], B[n], L[n][n], U[n][n], m[n][n], Aug[n][n + 1];

    //Initializing matrix A,L,U
    cout << "Enter A: \n";
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> A[i][j];
            U[i][j] = A[i][j];
            Aug[i][j] = A[i][j];
            if (i == j) {
                L[i][j] = 1;
            }
            else {
                L[i][j] = 0;
            }
        }
    }

    //Initialising matrix B
    cout << "Enter B: \n";
    for (int i = 0; i < n; i++) {
        cin >> B[i];
        cout << "done" << i;
        Aug[i][n] = B[i];
    }

    // ...

    return 0;
}

Input:

n=2, A={2,5,-3,-4}, B={0,0}

The error occurs when I try to input B[1] so done0 gets printed however done1 doesn't. I just can't figure out what the reason of this error is as I don't see any reason for B[1] to be inaccessible.

A: You've misdiagnosed the problem. The segmentation fault occurs after the for loop finishes, in the code you haven't shown us (the // ... part). The done1 doesn't get printed because your code faults before it has a chance to flush the output buffer. Your cout << "done" << i; just puts things in the output buffer, there's nothing there to flush the buffer.


text:
Q: Incompatible types when assigning an empty tuple to a specialised variable I have a variable path, which should be a tuple of strings. I want to start with it set to an empty tuple, but mypy complains.
path: Tuple[str] = ()

The error is:

Incompatible types in assignment (expression has type "Tuple[]", variable has type "Tuple[str]")

How can I assign an empty tuple to a typed variable?
Motivation
The reason I want to do this is: I want to build up the tuple dynamically, and tuples (unlike lists) can be used as dictionary keys. For example (not what I'm actually doing):
for line in fileob:
    path += (line,)
some_dict[path] = some_object

This works well, except that mypy doesn't like the type declaration above. I could use a list and then convert it to a tuple, but it complicates the code.

A: EDIT:
You can define a variable length, homogenous tuple like this:
Tuple[str, ...]

You can also create a "a or b" type variable with typing.Union:
from typing import Union

path: Union[Tuple[()], Tuple[str]] = ()

OLD ANSWER:
By trying to assign an empty tuple to a variable that you have typed to not allow empty tuples, you're effectivly missing the point of typing variables.
I assume that the empty tuple you are trying to assign is just a token value, and that you intend to reassign the variable later in the code (to a tuple that contains only strings.)
In that case, simply let the token value be a tuple that contains a string:
path: Tuple[str] = ('token string')

This should stop the error message.


text:
Q: Formulating the Twin Prime Conjecture as a Language Recognition problem. I'm trying to figure out how to formulate the Twin Prime Conjecture as a language recognition problem. I've got:
A = {p: p is the largest prime such that p + 2 is prime}
B = {p: p and p+2 are both prime}
I believe A is the correct (but not the only) formulation and that A is not decidable while B is. Is my understanding correct?

A: The property $p\in B$ is decidable, just run a Turing machine which tests $p$ and $p+2$ for being prime numbers. This machine will definitely give you a result (either way) and thus decide whether $p\in B$ or $p\notin B$.
For the other set $A$:
If there are infinitely many twin primes, then $A$ would be empty by definition (i.e. there is no largest twin). If there are only finitely many twin primes, then $A$ would be a singleton, containing the smaller number in the biggest twin primes pair.
By definition the empty set and a particular singleton (any finite set) are decidable, i.e. there are Turing machines which can decide (case by case) if an object is in an explicitly given finite set or not.
The problem here is that your definition of $A$ relies on a possibly undecidable property (i.e. it could be that the twin primes problem itself is undecidable), hence the two cases of whether $A$ is empty or a singleton would not be decidable. But even if the twin problem were decidable, it could be decidable in a non-constructive fashion, meaning that the biggest twin prime would not be given explicitly (and neither would there be an upper bound on the biggest twin prime) and then the unique element in the set $A$ would not be known (or computable from the knowledge about the cardinality of existing twin primes alone).


text:
Q: Get "Method Not Allowed" error calling Django SOAP web server I have written a SOAP web server with Django using this tutorial; I used the exact code disscussed in the tutorial and its linked tutorials.
This is my urls.py BTW:
from django.conf.urls import url
from django.contrib import admin
from views import hello_world_service

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello_world/', hello_world_service),
    url(r'^hello_world/service.wsdl', hello_world_service),
]

To call the method 'say_hello' I wrote multiple clients using different libraries:
Implementation with suds:
from suds.client import Client as SudsClient
url = 'http://127.0.0.1:5000/hello_world'
client = SudsClient(url=url, cache=None)

This is error traceback in the client side:
Traceback(most recent call last):
    File "client.py", line 14, in < module > client = SudsClient(url=url, cache=None)
    File "build/bdist.linux-x86_64/egg/suds/client.py", line 112, in __init__
    File "build/bdist.linux-x86_64/egg/suds/reader.py", line 152, in open
    File "build/bdist.linux-x86_64/egg/suds/wsdl.py", line 136, in __init__
    File "build/bdist.linux-x86_64/egg/suds/reader.py", line 79, in open
    File "build/bdist.linux-x86_64/egg/suds/reader.py", line 95, in download
    File "build/bdist.linux-x86_64/egg/suds/transport/https.py", line 60, in open
    File "build/bdist.linux-x86_64/egg/suds/transport/http.py", line 64, in open
suds.transport.TransportError: HTTP Error 405: Method Not Allowed

And this is what I get in the server console:
[24/Jul/2017 08:17:14] "GET /hello_world HTTP/1.1" 301 0
[24/Jul/2017 08:17:14] "GET /hello_world/ HTTP/1.1" 405 0

Another Implementation with suds:
I found it here.
from Tkinter import *
from suds.client import *
class SoapClass:
    def __init__(self, master):
        self.client = Client('http://127.0.0.1:5000/hello_world/', username='', password='', faults=False)
        Button(master, text='Call', command=self.request).pack()
    def request(self):
        methodName = 'getSmsDeliveryStatus'
        params = ['2656565656565']
        MethodToExecute = getattr(self.client.service, methodName)
        try:
            response = MethodToExecute(*params)
        except WebFault as e:
            response = e
        print(response)
root = Tk()
app = SoapClass(root)
root.mainloop()

This client returns the exact stacktrace in the client side as suds implementation does; but the server console shows a different error:
[24/Jul/2017 08:30:27] "GET /hello_world/ HTTP/1.1" 405 0

Implementation with requests:
import requests
target_url = "http://127.0.0.1:5000/hello_world/"
headers = {'Content-type': 'text/xml'}
data = {'id': '322424234234'}
print requests.post(target_url, data=data, headers=headers).text

In the client side, I get an HTML page which in general says CSRF verification failed. Request aborted. In the server side, I get:
Forbidden (CSRF cookie not set.): /hello_world/
[24/Jul/2017 08:44:51] "POST /hello_world/ HTTP/1.1" 403 2857

EDIT 1:
I tried disabling CSRF for this solution; I got this:
<SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:plnk="http://schemas.xmlsoap.org/ws/2003/05/partner-link/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance">
<SOAP-ENV:Body><SOAP-ENV:Fault>
<faultcode>Server</faultcode>
<faultstring>'NoneType' object has no attribute 'startswith'</faultstring>
<detail>Traceback (most recent call last):
    File "/usr/lib/python2.7/dist-packages/soaplib/wsgi_soap.py", line 224, in __call__
        if methodname.startswith('"') and methodname.endswith('"'):
            AttributeError: 'NoneType' object has no attribute 'startswith'
</detail>
</SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>

I think I forgot to fill some parameter in the request; could anyone please help me on that?
What is wrong with my clients getting connection and calling methods from server? Do I have to set some options in the server/client side?


text:
Q: Resources that explain Linux source code Looking for resources that can help getting 'into' the Linux code. Could not get much help on Google. I have no issues  on the distro covered by the book/resource, but will like if Fedora is the base. Also, it would be great if the resource is well maintained and updated.

A: this looks promising:
http://kernelnewbies.org/KernelHacking
Note that you will need to be familiar with Operating Systems concepts to even understand the concepts of how memory is allocated, how processes are scheduled, and whatnot.  Also, the code of the linux kernel is monstrously complex.
You are undertaking a daunting task.  But have fun with it.  You might want to start with a small device driver's code.

A: http://www.makelinux.net/kernel_map may be a good place to start. A clickable map which takes you to the part of the source you clicked. Readable in a browser.

A: If you are talking about the Linux kernel, kernel newbies is absolutely awesome. Besides that, I don't think theres a single resource to recommend.

A: If you are trying to understand the linux kernel source code, then the exact distribution you are using, is not very relevant.
I would recommend the book from Robert Love: Linux Kernel Development, currently in its third edition. It will give you an understanding of the main parts of the kernel.


text:
Q: Displaying KML attributes (Images) on Google My Map
I don't know if i am the right place to ask this question, i want to display images attached with each attribute in the kmz file on GoogleMyMaps. I can view the images on google earth but when i upload the same kmz file on GoogleMyMap other attributes are displayed but it is not displaying the image.

A: You might be using KML tags that can be displayed by Google Earth but cannot be displayed by Google maps.  See:
https://developers.google.com/kml/documentation/kmlelementsinmaps


text:
Q: Sorting nested set by name while keep depth integrity I'm using the nested set model that'll later be used to build a sitemap for my web site. This is my table structure.
create table departments (
    id int identity(0, 1) primary key
    , lft int
    , rgt int
    , name nvarchar(60)
);

insert into departments (lft, rgt, name) values (1, 10, 'departments');
insert into departments (lft, rgt, name) values (2, 3, 'd');
insert into departments (lft, rgt, name) values (4, 9, 'a');
insert into departments (lft, rgt, name) values (5, 6, 'b');
insert into departments (lft, rgt, name) values (7, 8, 'c');

How can I sort by depth as well as name? I can do
select
    replicate('----', count(parent.name) - 1) + ' ' + node.name
    , count(parent.name) - 1 as depth
, node.lft
from
    departments node
    , departments parent
where
    node.lft between parent.lft and parent.rgt
group by
    node.name, node.lft
order by
    depth asc, node.name asc;

However, that does not match children with their parent for some reason.
department      lft     rgt
---------------------------
 departments    0       1
---- a        1        4
---- d        1        2
-------- b    2        5
-------- c    2        7

As you can see, department 'd' has department 'a's children!
Thank you.

A: I think I finally came up with an ANSI SQL solution. The basic gist is that it counts the number of rows that either have parents with a lower valued name on the same level as one of the node's own parent or is itself on the same level as the node and has a lower valued name. You'll need to make a minor adjustment to it in order to add the indenting if you want it. Also, I don't know how performance on a large data set will be due to all of the subqueries:
SELECT
    N1.name
FROM
    dbo.departments N1
ORDER BY
    (
    SELECT
        COUNT(DISTINCT N2.lft)
    FROM
        dbo.departments N2
    INNER JOIN (
                SELECT
                    N.name,
                    N.lft,
                    N.rgt,
                    (SELECT COUNT(*) FROM dbo.departments WHERE lft < N.lft AND rgt > N.lft) AS depth
                FROM
                    dbo.departments N) SQ1 ON
        SQ1.lft <= N2.lft AND SQ1.rgt >= N2.lft
    INNER JOIN (
                SELECT
                    N3.name,
                    N3.lft,
                    N3.rgt,
                    (SELECT COUNT(*) FROM dbo.departments WHERE lft < N3.lft AND rgt > N3.lft) AS depth
                FROM
                    dbo.departments N3) SQ2 ON
        SQ2.lft <= N1.lft AND SQ2.rgt >= N1.lft AND
        SQ2.depth = SQ1.depth AND
        SQ2.name > SQ1.name
    )

Let me know if you come up with any situations where it breaks.

A: The below will work with your example, although if a name contains the "-" character then it might break down. It might serve as a starting point though. This uses CTEs, which are specific to SQL Server I believe. If I think of a more generic ANSI SQL method, I'll post that as well.
;WITH Tree_Path AS (
    SELECT
        lft,
        rgt,
        name,
        CAST(name + '-' AS VARCHAR(MAX)) AS tree_path,
        1 AS depth
    FROM
        dbo.departments
    WHERE
        lft = 1
    UNION ALL
    SELECT
        c.lft,
        c.rgt,
        c.name,
        CAST(tp.tree_path + c.name + '-' AS VARCHAR(MAX)),
        tp.depth + 1
    FROM
        Tree_Path tp
    INNER JOIN dbo.departments AS c ON
        c.lft > tp.lft AND
        c.lft < tp.rgt AND
        NOT EXISTS (SELECT * FROM dbo.departments d WHERE d.lft < c.lft AND d.rgt > c.lft AND d.lft > tp.lft AND d.lft < tp.rgt))
SELECT
    REPLICATE('----', depth - 1) + name,
    depth - 1,
    lft
FROM
    Tree_Path
ORDER BY
    tree_path,
    name

A: There is a mismatch in the question.  The query returns: node.name, depth, and node.lft -- yet the results table is labeled with:
department      lft     rgt

Anyway, that query is returning the correct results for department level -- which is apparently not what you want depth to mean in this case.  Both a and d are top-level departments.
If you want the number of sub-departments, and the nested-set is kept properly maintained, then the query is simply:
SELECT
    D1.name,
    (D1.rgt - D1.lft - 1) / 2    AS SubordinateDepartments
FROM
    departments AS D1
ORDER BY
    SubordinateDepartments DESC,
    D1.name


text:
Q: Composer Install Package Dependencies I have created a custom package which is set up in a GIT repo. Composer is successfully pulling the files into a directory in the vendor directory, but I need to pull in the nested dependencies, which I cannot find the answer on how to make this happy.
This the Composer file for the main site pulling the package:
{
    "name": "development/project",
    "type" : "project",
    "repositories": [
        {
            "type":"composer",
            "url":"https://wpackagist.org"
        },
       {
           "type": "package",
           "package": {
               "name": "development/package",
               "version": "0.0.1",
               "source": {
                   "type": "git",
                   "url": "https://developer@bitbucket.org/development/package.git",
                   "reference" : "v0.0.1"
               }
           }
        },
     ],

     "require": {
         "php": ">=5.4",
         "composer/installers": "~1.0",
     },

     "require-dev": {
         "development/package": "~0.0"
    }
}

And here is the Composer file local to the package itself:
{
  "name": "development/package",
  "type" : "project",

  "require": {
    "php": ">=5.4",
    "composer/installers": "~1.0"
  },

  "require": {
    "ellislab/codeigniter": "~3.0"
  },
}

So what I would like to have happen is that when I run Composer on the main site it pulls in the 'development/package' (which it is currently doing), but also pull in the package dependencies 'ellislab/codeigniter'. Thanks for any help on this.

A: You have invalid composer json in your local package, it should be like this (no double require node):
{
  "name": "development/package",
  "type" : "project",

  "require": {
    "php": ">=5.4",
    "composer/installers": "~1.0",
    "ellislab/codeigniter": "~3.0"
  }
}

Composer automatically pulls all packages defined in require node of root package, and in require node of each dependent packages, including your ellislab/codeigniter in your development/package.


text:
Q: Incomplete responses being received from BLE device flutter I am not able to received complete responses from my BLE device which I am supposed to receive for the commands written to characteristics using flutter_blue. What I am receiving in response is the command itself which I sent for write. The responses received are being decoded properly.
The commands which I'm trying to write are OBDII protocols which are
AT Z
AT H0
AT H0
AT L0
AT S0
01 0C

Surprisingly the command "AT Z" gives response "ELM 327v1.5" which is correct. This is the only command from which I am receiving the correct response. All other commands are returning the command itself which is partially correct because most of the times the actual responses are received along with the command name.
The response reading and decoding is implemented in the following way
await read_CX.setNotifyValue(true);

read_CX.value.listen((response) {
  print(utf8.decode(response));
}

Has anyone faced similar issue of receiving incomplete data? Can anyone please help me out?
Thanks!!

A: First, add ATE0\r to your init sequence, this will stop the adapter from echoing back what you send.
Then, familiarize yourself with the AT commands provided by the ELM327, e.g. by reading https://www.elmelectronics.com/wp-content/uploads/2016/07/ELM327DS.pdf.


text:
Q: How to start again Quartz jobs that are created dynamically after a server shutdown I'm using spring mvc 4.2.5.RELEASE and quartz 2.2.1 quartz-jobs 2.2.1
I have a user interface when the user inputs the name and the cron expression of a quartz job, and then I create the job like this
SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();

schedFact.getScheduler().getContext().put("externalInstanceEstatus", myObject);
Scheduler sched = schedFact.getScheduler();
sched.start();

JobDetail job = null;
job = newJob(MyTask.class)
.withIdentity((String) String.valueOf(myUniqueId), "group1")
.build();

Trigger triggerCron = TriggerBuilder
.newTrigger()
.withIdentity(String.valueOf(myUniqueId), "group1")
.withSchedule(
    CronScheduleBuilder.cronSchedule(myObject.getExpresionCron()))
.build();

sched.scheduleJob(job, triggerCron);

Everytime that the user goes that interface he can create a job this works fine
but when I turn off the server all of my Jobs are lost. I solved this by saving the Job name and cron expression in a database and I created a method that fetch all the records from that table and I re-create the Jobs like this
public void reCreateJobs() {

        ArrayList<MyJob> listOfJobs = searchAllJobsInDB();

        SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
        Scheduler sched = schedFact.getScheduler();

        //I loop the lsit and I delete all the jobs in the scheduler just in case
        for (MyJob myJob : listOfJobs) {
            for (String group : sched.getJobGroupNames()) {
                for (JobKey jobKey : sched.getJobKeys((GroupMatcher<JobKey>) groupEquals(group))) {
                    if (jobKey.getName().equals(String.valueOf(myJob.getIdMyJob()))) {
                        sched.deleteJob(jobKey);
                    }
                }
            }
        }

        sched.start();

        //THIS IS WHERE I CREATE ALL THE JOBS AGAIN
        for (MyJob myJob : listOfJobs) {

            JobDetail job = newJob(TareaImprimir.class)
                    .withIdentity((String) String.valueOf(myJob.getIdMyJob()), "group1")
                    .build();

            JobDetail job = null;

            Trigger triggerCron = TriggerBuilder
                    .newTrigger()
                    .withIdentity(String.valueOf(myJob.getIdMyJob()), "group1")
                    .withSchedule(
                            CronScheduleBuilder.cronSchedule(myJob.getExpresionCron()))
                    .build();

            sched.scheduleJob(job, triggerCron);
        }
    }

This also works fine I can create the Jobs again and they run fine,
My problem is that I need to pass a value to the Task Class and I don't know how to pass it, I know how to pass it when I create the job for the first time like this
schedFact.getScheduler().getContext().put("externalInstance", myObject);

and then I get it in my task Class like this
 SchedulerContext schedulerContext = null;
    try {
        schedulerContext = context.getScheduler().getContext();

    } catch (SchedulerException ex) {
        ex.printStackTrace();
    }
    MyObject externalInstance
            = (MyObject) schedulerContext.get("externalInstance");

My Problem is that I don't know how to do this when I'm recreating the Jobs in my method reCreateJobs() where I get them from the DataBase
How can I set that externalInstance inside my method reCreateJobs() for every Job or How can I pass that value to the MyTask class inside that loop
this is my Task Class
public class MyTask implements Job {

@Autowired
SomeDAO someDAO;

public void execute(JobExecutionContext context)
        throws JobExecutionException {

    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

    SchedulerContext schedulerContext = null;
    try {
        schedulerContext = context.getScheduler().getContext();
    } catch (SchedulerException ex) {
        Logger.getLogger(MyTask.class.getName()).log(Level.SEVERE, null, ex);
    }
    MyObject externalInstance
            = (MyObject) schedulerContext.get("externalInstance");

    someDAO.doSomething(externalInstance.getSomething());
}

}

A: Since i cant comment, adding it as an answer
Any reason why you are you not using JDBC-JobStoreTX

JDBCJobStore is used to store scheduling information (job, triggers and calendars) within a relational database. There are actually two seperate JDBCJobStore classes that you can select between, depending on the transactional behaviour you need.
JobStoreTX manages all transactions itself by calling commit() (or rollback()) on the database connection after every action (such as the addition of a job). JDBCJobStore is appropriate if you are using Quartz in a stand-alone application, or within a servlet container if the application is not using JTA transactions.

That way you can persist the data you want to JobDataMap

Holds state information for Job instances.
JobDataMap instances are stored once when the Job is added to a scheduler. They are also re-persisted after every execution of jobs annotated with @PersistJobDataAfterExecution.
JobDataMap instances can also be stored with a Trigger. This can be useful in the case where you have a Job that is stored in the scheduler for regular/repeated use by multiple Triggers, yet with each independent triggering, you want to supply the Job with different data inputs.
The JobExecutionContext passed to a Job at execution time also contains a convenience JobDataMap that is the result of merging the contents of the trigger's JobDataMap (if any) over the Job's JobDataMap (if any).


text:
Q: javascript not running onBlur The function to validate the date field is not executing onBlur below. I'm not sure what I'm missing here.  Just trying to test a simply validation.

   DOB

   <input id="dob" type="text" placeholder="01/01/1980" onBlur="checkForm(this.value);">


text:
Q: Unsafe_unretain Vs Weak VS Assign Whats the main difference between these 3 attributes ?? some say Unsafe_Unretain is same as weak but in a non ARC env.
And some say Unsafe_unretain is the same as Assign in ARC env ?
 Whats the actual diff ??

A: From here, next time you can search the question up on google.

Assign is identical to weak except that it does not set pointers to deallocated instances to nil, potentially leaving dangling pointers. Assign and unsafe_unretained are identical in usage.

Use unsafe_unretained in iOS 4 or below, or else, use assign. Weak is different than unsafe_unretained and assign.


text:
Q: NSMutable Dictionary adding objects Is there a more efficient way to add objects to an NSMutable Dictionary than simple iteration?
Example:
// Create the dictionary

NSMutableDictionary *myMutableDictionary = [NSMutableDictionary dictionary];

// Add the entries

[myMutableDictionary setObject:@"Stack Overflow" forKey:@"http://stackoverflow.com"];
[myMutableDictionary setObject:@"SlashDotOrg" forKey:@"http://www.slashdot.org"];
[myMutableDictionary setObject:@"Oracle" forKey:@"http://www.oracle.com"];

Just curious, I'm sure that this is the way it has to be done.

A: Allow me to add some information to people that are starting.
It is possible to create a NSDictionary with a more friendly syntax with objective-c literals:
NSDictionary *dict = @{
    key1 : object1,
    key2 : object2,
    key3 : object3 };

A: NSDictionary *entry = [NSDictionary dictionaryWithObjectsAndKeys:
  [NSNumber numberWithDouble:acceleration.x], @"x",
  [NSNumber numberWithDouble:acceleration.y], @"y",
  [NSNumber numberWithDouble:acceleration.z], @"z",
  [NSDate date], @"date",
  nil];

A: If you have all the objects and keys beforehand you can initialize it using NSDictionary's:
dictionaryWithObjects:forKeys:

Of course this will give you immutable dictionary not mutable. It depends on your usage which one you need, you can get a mutable copy from NSDictionary but it seems easier just to use your original code in that case:
NSDictionary * dic = [NSDictionary dictionaryWith....];
NSMutableDictionary * md = [dic mutableCopy];
... use md ...
[md release];

A: NSMutableDictionary *example = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@5,@"burgers",@3, @"milkShakes",nil];

The objects come before the keys.


text:
Q: How do I "json_decode" a single column data after fetch from database in Laravel? I am saving an array in one column of my database using json_encode as follows and it works:
    $service->description = $request->service_description;
    $service->image = json_encode($url);
    $service->duration = $request->service_delivery_time;

When I fetch the data I get a string. I am fetching using $service = Service::findOrFail($id);. I can decode the individual column as done below and pass it to the view.
    $service = Service::findOrFail($id);
    $images = json_decode($service->image);
    return view('services.show',['service'=>$service , 'images'=>$images]);

What I am asking is, can I decode the images in one query?

A: Well this is a single query, json_decode runs after the SQL query returned your desired result.
What you can do is add a $casts property to your Service model so Laravel encodes/decodes it automatically for you, then you don't need to store these values with json_encode, just do $service->image = $url, and when you run findOrFail, the image property will already be a decoded json.
protected $casts = [
    'image' => 'array',
];

Here's the documentation

A: You can use $cast or Accessor
1: $cast:
protected $casts = [
'image' => 'array'];

2: Accessor:
public function getImageAttribute()
{
    return json_decode($this->attributes['image']);
}


text:
Q: laravel 9 with cpanel database not connected
QueryException
PHP 8.1.10
9.34.0
SQLSTATE[HY000] [1045] Access denied for user 'ctsgbcom_cchnorth'@'127.0.0.1' (using password: YES)

I am facing an issue in cpanel The hosting is Hostbreak.
I have tried to fix :
using double for password and usersname in .env
clear cache
but not resolve this.

A: The issue has been resolved.
This issue has just come in only one hosting. the same project deployed into another hosting and domain works fine.
I contacted support and ask him for the scenario of this issue than support asked me for the public IP of my and added my IP to our firewall.
Just contact support for your hosting.
Thanks


text:
Q: Generate a raw preview of files which outputs formatting Building a Raw view of text in my application, like pastebin does:
http://pastebin.com/raw.php?i=nfVT7b0Z
So, I wrote the script which just echos out the $contents, but newlines, spaces, and tabes are not being proceeded. Looking at the pastebin source above, you will notice they don't wrap the text in any HTML tags such as <pre>. How then are they getting the text to format?
Are they using some special header?

A: The content you see is not HTML. It's text. You can use the following header to achieve the same result with output sent by php.
Content-Type: text/plain; charset=utf-8

Example:
<?php
header('Content-Type: text/plain; charset=utf-8');
echo "First Line\nSecond Line";
?>

A: Curl was my friend here. I noticed in the response this header:
Content-Type: text/plain; charset=utf-8

So simply do:
    header("Content-Type: text/plain; charset=utf-8");

Before outputting any text.


text:
Q: Copy a struct to a specific memory location in Rust If I have a struct, for example:
#[derive(Clone, Copy)]
#[repr(C, packed)]
pub struct SomeData {
    a: u16,
    b: u64,
    c: u32,
    d: u16,
}

How do I copy it to a specific location in memory, e.g. to a point 0x1000 in memory efficiently? Would something like this work?
let dst_addr: u64 = 0x1000;
let src = SomeData {a: 1, b: 2, c: 3, d: 4};
unsafe {
    let tmp: &[u8; 10] = transmute(src);
    copy(dst_addr as *mut _, tmp);
}

Please note that the repr(C, packed) part is actually needed here.
The software is running on bare x86_64, ring 0, without operating system or other limitations. Also, I'm programming without the standard library, so this should be achievable with only the core library.
This is, of course, unsafe, but it is not a problem.
Edit: Just clarifying: I'm copying to uninitialized memory.

A: You will want to have a look at the core::ptr module.
Its write function does exactly what you wish:

pub unsafe fn write<T>(dst: *mut T, src: T)

core::ptr::write(dst_addr as *mut_, src);

As noted, it does not drop the value current at dst_addr (you can use read to do so).
I advise against using intrinsics::copy_nonoverlapping as intrinsics will never be stabilized.


text:
Q: Axios interceptors: make sure that global auth header setted im using react and have two pages:

*

*start

*inner

On the start page:

*

*I make get request and grab auth token

*Put in headers via Axios interceptors

*Redirecting to inner page

Code of start page:
  useEffect(() => {
    if (jwt) {
      axios.interceptors.request.use(function (config: any) {
        config.headers.common['Authorization'] = 'Bearer ' + jwt
        return config
      })
      navigate('/')
    }
  }, [jwt])

On the Inner page , while mount, immediately fires get request. But it fires without a auth header because of have not set yet.
So my question is how to make a page redirect to Inner and be sure that  Authorization header is OK and ready to use?


text:
Q: mongo or sql tagging system I have a tagging system in my mind and here are my ideas,
1, I can make a mongodb database and add tags to an embedded field and index them all
2, I can use SQL for it, I can add the tags as a new entry to a table
3, I can create another collection on mongodb and do it like this
for example the tag is "chicken", this is the document
tag:"chicken",
id:"1200000,32555,8787888888"

the tag is the chicken, the id is other documents that relate with the chicken, I think those systems will give me lots of headaches. especially the first one. Do you have any tagging system ideas for my need ?, by the way, there will be more than one million different tags and searched this tagging system before opening this question,
thank you

A: If you're trying to achieve this in mongo, i would create documents that look like
{
    tag: "chicken",
    ids : [ 12345,23456,34567 ]
},
...

then two indexes, one on "tag" and a multikey index on "ids"
(http://docs.mongodb.org/manual/core/indexes/#multikey-indexes).
db.tags.ensureIndex( { "tag": 1 } );
db.tags.ensureIndex( { "ids": 1 } );

depending on what queries you need to do there may be value in creating a compound index on both attributes.
http://docs.mongodb.org/manual/core/indexes/#compound-indexes
e.g.
db.tags.ensureIndex( { "ids": 1, "tag" : 1 } );

1 million tag docs will not be an issue, I have similar collection with ~3m docs each having on avg 15 items in the multikey index and performance is excellent (from dev vm).
i hope this helps

A: MongoDB is great for such tagging thanks to how it indexes lists. Consider a document like this one:
{_id: 42, name: "someName", tags: ["chicken", "parrot", "hovercraft"]}

If you add an index for tags field, you can efficiently perform queries like this:
{tags: "chicken"}

This query will find all documents that contain "chicken" in its tags list - that is, all documents tagged with chicken tag.
I'm not sure if this is what you meant in your first point. If it is then I don't understand why it gives you headaches.


text:
Q: uitableview questions i try to this condition but don't work. If the senderlabel = key@"sender" use the green.png or the grey.png for every rows.
    if (senderLabel.text = [tempMsg objectForKey:@"sender"])
    {
        [cell.msgText setText:[tempMsg objectForKey:@"message"]];

        [messTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

        //[cell setFrame:CGRectMake(0,0, size.width, size.height)];
        [cell.msgText setFrame:CGRectMake(15,3, size.width, result)];

        UIImage* balloon = [[UIImage imageNamed:@"grey.png"] stretchableImageWithLeftCapWidth:24  topCapHeight:15];
        UIImageView *newImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, size.width+10, result+10)];
        UIView *newView =[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.frame.size.width, cell.frame.size.height)];

        [newImage setImage:balloon];
        [newView addSubview:newImage];
        [cell setBackgroundView:newView];

    }else {
        [cell.msgText setText:[tempMsg objectForKey:@"message"]];

        [messTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

        //[cell setFrame:CGRectMake(0,0, size.width, size.height)];
        [cell.msgText setFrame:CGRectMake(15,3, size.width, result)]; //propriété du texte

        UIImage* balloon = [[UIImage imageNamed:@"green.png"] stretchableImageWithLeftCapWidth:24  topCapHeight:15];
        UIImageView *newImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, size.width+10, result+10)];
        UIView *newView =[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.frame.size.width, cell.frame.size.height)];

        [newImage setImage:balloon];
        [newView addSubview:newImage];
        [cell setBackgroundView:newView];

    }

    return cell;

}

A: if (senderLabel.text = [tempMsg objectForKey:@"sender"]) is not correct.  You need to use isEqual in your comparison.
if ([senderLabel.text isEqual:[tempMsg objectForKey:@"sender"]])

A: First of all, here
if (senderLabel.text = [tempMsg objectForKey:@"sender"])

you are making an assignment, not a comparison, comparing would be
if (senderLabel.text == [tempMsg objectForKey:@"sender"])

However, that would compare if it's the exact same object in memory, which is probably not what you want, if you want to check if the string has the same text, you have to use
[string isEqualToString:anotherString]

A: To get indexpath you can use like this:
NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:0];

and for comparison:
if ([string compare:anotherString] == NSOrderedSame)


text:
Q: Sum and Count by Two different group by in SQL Server I want to print the total order and transaction amounts and counts of each account.
When I run the query below I get the following error:

Column 'orders.order_amount' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

How can I fix this?
SELECT
    trans.account_id,
    SUM(trans.amount),
    COUNT(trans.account_id),
    orders.order_amount,
    orders.order_count
FROM
    trans
FULL JOIN
    (SELECT
         [order].account_id,
         SUM([order].amount) as order_amount,
         COUNT([order].account_id) as order_count
     FROM
         [order]
     GROUP BY
         [order].account_id) AS orders ON (trans.account_id = orders.account_id)
GROUP BY
    trans.account_id
ORDER BY
    trans.account_id;

Trans table:
trans_id  account_id  type  amount  balance  account   date
-----------------------------------------------------------------
1              1       a      88      213      75      1995-03-24
7              1       b      156     66       75      1995-02-25

Order table
order_id  account_id  bank_to amount
-------------------------------------
1              1       a      88
7              1       b      156

A: You need to add orders.order_amount and orders.order_count to group by:
select trans.account_id,
       SUM(trans.amount),
       COUNT(trans.account_id),
       orders.order_amount,
       orders.order_count
from trans
        FULL JOIN (
            select  [order].account_id,
                    SUM([order].amount) as order_amount,
                    COUNT([order].account_id) as order_count

            from [order]

            GROUP BY [order].account_id

          ) as orders

          ON (trans.account_id = orders.account_id)

group by trans.account_id, orders.order_amount, orders.order_count
order by trans.account_id;

A: You would be using full join if you thought that accounts could be in either table, but not necessarily in both.  If so, you should fix your query.
I would recommend aggregating both tables before joining.  And then fixing the order by conditions:
select coalesce(t.account_id, o.account_id), t.trans_amount, t.trans_count,
       o.order_amount, o.order_count
from (select t.account_id, sum(t.amount) as trans_amount, count(*) as trans_count
      from trans t
      group by t.account_id
     ) t full join
     (select o.account_id,
             sum(o.amount) as order_amount,
             count(o.account_id) as order_count
      from [order] o
      group by o.account_id
     ) o
     on t.account_id = o.account_id
order by coalesce(t.account_id, o.account_id);

Note that full join is often not needed.  However, if it is needed, you should write the query correctly for it.


text:
Q: Using a corollary of Tutte's theorem to prove a statement I've been asked to prove that any graph $G$ which is $n$-connected, $n$-regular, and has even order has a one-factor.
A hint that we were given for proving this was a corollary to Tutte's theorem, which states that;

If the graph of multigraph $G$ has an even number of vertices, then $G$ has no one-factor if and only if there is some $w$-set $W$ of vertices such that $G-W$ has at least $w+2$ odd components

However, I'm having a lot of trouble actually applying this to the question. I know that I have to use both the connectivity and regularity of the graph to say something about what components we get after removing a certain number of vertices, but I'm really just not confident in applying these two conditions.
I've tried to start a proof by contradiction to the above corollary, but I'm not sure if I'm even doing it correctly.
Firstly, we start with some graph $G$ of even order. We also note that, due to the connectivity of $G$, we must remove at least $n$ vertices to disconnect it into some number of components. So, this means that there exists some $n$-set $W$ of vertices such that $G-W$ has at least $n+2$ odd components.
At this point, I thought it was best to consider the cases in which $n$ was even, and $n$ was odd. If $n$ is even, then we need to remove an even number of vertices to disconnect $G$, which means that the order of $G-W$ would be even. But, at this stage, I'm not sure how to appeal to the connectivity of the graph to say anything of relevance. I'd like to say that, if we've got an even number of vertices, then we've got either an even number of even components, or an even number of odd components, but I'm just not sure.
In a similar way, if we delete an odd number of vertices from $G$, then we necessarily have an odd number of vertices left over, which would imply at least one odd component, but again, I'm not sure how to relate this back to the regularity of the graph, or the corollary itself.
If anyone could provide me with some insight into this, I'd be over the moon. This question is really stressing me out ;-;

A: It's perhaps easier to state Tutte's theorem as follows, which is how I mostly see it anyways.
Tutte's Theorem: Let $G(V,E)$ be a graph. Then $G$ has a perfect matching if and only if for every subset $W\subseteq V$ of vertices, the subgraph induced by $V\backslash W$ has at most $|W|$ odd components. $\square$
It's a simple exercise to prove that these two versions are equivalent; your version is just the negation of mine. Also note that there's no real need to consider multigraphs when finding perfect matchings as a multigraph will have a perfect matching if and only if its underlying simple graph has a perfect matching.
Now onto the proof of the corollary.
Corollary: Let $G(V,E)$ be a $n$-regular and $n$-connected graph. Then $G$ has a perfect matching.
Proof: Let $W\subseteq V$ be an arbitrary subset of the vertices of $G$. The graph induced by $V\backslash W$ contains even and odd components. Remove from $G$ (the original graph) all vertices belonging to the even components and collapse all vertices of each odd component to a single vertex $u_i$. Call the collection of such vertices $U$. Note that $|U|$ is precisely the number of odd components induced by $V\backslash W$.
Remove all multi-edges and loops from the resulting graph and remove all the edges internal to $W$. Note that what remains is a bipartite graph $\tilde{G}$ with vertex bipartition $(W,U)$.
Finally, note that $\deg(u_i) \ge n$ by the $n$-connectivity assumption while $\deg(w_i) \le n$ by the regularity assumption. Summing the degrees over the bipartition of $\tilde{G}$, we have
$$n|U|\le\sum_{u_i\in U}\deg(u_i)=\sum_{w_i\in W} \deg(w_i) \le n|W|$$
Therefore we conclude that $|U| \le |W|$. Since each vertex of $U$ represents an odd component, we conclude that the number of odd components induced by $V\backslash W$ is at most $|W|$. Since $W$ was arbitrary, this means that $G$ satisfies the hypotheses of Tutte's theorem and we have a perfect matching, as needed. $\square$


text:
Q: Convert a column of lists into a column of vector I have a data.table that for some reason has a few columns as list. I need to find a fast way to convert these columns to regular vector columns with integer values.
See reproducible example and my attempt below.
reprex
dt = structure(list(fromId = c("89a901291abffff", "89a901295b7ffff",
      "89a9012809bffff", "89a901285cfffff"), travel_time_p001 = c(45L,
      43L, 38L, 27L), travel_time_p050 = list(54L, 52L, 44L, 35L),
      travel_time_p098 = list(62L, 60L, 55L, 44L)), row.names = c(NA,
      -4L), class = c("data.table", "data.frame"))

head(dt)
>             fromId travel_time_p001 travel_time_p050 travel_time_p098
> 1: 89a901291abffff               45               54               62
> 2: 89a901295b7ffff               43               52               60
> 3: 89a9012809bffff               38               44               55
> 4: 89a901285cfffff               27               35               44

sapply(dt, class)
>     fromId travel_time_p001 travel_time_p050 travel_time_p098
>"character"        "integer"           "list"           "list"

class(dt$travel_time_p098[1])
> [1] "list"

I've found this way to fix a single column, though I'm not sure this could be done faster.
dt[, travel_time_p098 := Reduce(rbind, travel_time_p098)]
Now, the challenge gets harder when I try to do this for multiple columns. This is what I've tried without success. I hope someone could come up with a fast solution, perhaps using a data.table loop with set().

# identify which columns need to be transformed.
colpositions <- sapply(dt, class) == 'list'
colnms <- names(dt)[colpositions]

# failed attempt
dt[, colnms := Reduce(rbind, .SD), .SDcols = colnms]

Any suggestions?

A: If the list elements are of the same length as the number of rows, an option is to loop over all the columns, do a check with if/else and unlist
dt1 <- dt[,  lapply(.SD, function(x) if(is.list(x)) unlist(x) else x)]
str(dt1)
#Classes 'data.table' and 'data.frame': 4 obs. of  4 variables:
# $ fromId          : chr  "89a901291abffff" "89a901295b7ffff" "89a9012809bffff" "89a901285cfffff"
# $ travel_time_p001: int  45 43 38 27
# $ travel_time_p050: int  54 52 44 35
# $ travel_time_p098: int  62 60 55 44

Or without any checks
dt[, lapply(.SD, unlist)]

If we need to use set
for(j1 in seq_along(dt)) {
     cl1 <- class(dt[[j1]])
     if(cl1 == 'list') {
          set(dt, i = NULL, j = j1, value = unlist(dt[[j1]]))
        }
  }

str(dt)
#Classes 'data.table' and 'data.frame': 4 obs. of  4 variables:
# $ fromId          : chr  "89a901291abffff" "89a901295b7ffff" "89a9012809bffff" "89a901285cfffff"
# $ travel_time_p001: int  45 43 38 27
# $ travel_time_p050: int  54 52 44 35
# $ travel_time_p098: int  62 60 55 44


text:
Q: Matplotlib displaying RGB pixels weirdly I have a set of RGB pixels I gathered from an image, but when I try to save them and display them, they come out very weirdly, as 3 separate colors. It seems like it's not reading my array as a list of RGB values.
I have an abbreviated version of my code, with a short list of RGB values:
import matplotlib.pyplot as plt
import numpy as np

img = np.array([[255, 255, 255], [127, 255, 127], [239, 255,  15], [127 ,  0,   0]])

plt.imshow(img)
plt.savefig('testtt.png', dpi=400)

which gives me this:

Does anyone know how to resolve this or what might be wrong? Or alternatively, if anyone knows a better way to display RGB pixels from an array, please let me know. Side note: I am trying to avoid OpenCV

A: So, you created an array of lists
img = np.array([[255, 255, 255],[127, 255, 127],[239, 255,  15],[127 ,  0,   0]])

But nothing tells python to treat this as and RGB image, so instead it created an array with four rows and three columns. Then when you plotted it here:
plt.imshow(img)

It simply applied colors from the viridis color pallet and displayed it as a visual array where each value got a color from that pallet.
As mentioned in the comments, you need to expressly tell python to treat this array as an image:
imshow(img, origin='upper', interpolation='nearest')

For a straight pixel-by-pixel translation

A: A 2D array will be interpreted as values to be color mapped. That's why you see 4 rows of 3 colors.
To interpret the array as 4 rgb values, you can plot a 3D array:
import matplotlib.pyplot as plt
import numpy as np

img = np.array([[255, 255, 255], [127, 255, 127], [239, 255, 15], [127, 0, 0]])
plt.imshow([img]) # note the extra brackets
plt.show()

To illustrate what was happening with the original plot, seaborn's heatmap can automatically add some annotations and a colorbar.
import seaborn as sns

sns.heatmap(img, annot=True, fmt='d', cmap='viridis')
plt.imshow([img])

PS: To display RGB values as an NxM array of pixels, the values should form a 3D NxMx3 array:
img = np.array([[[255, 255, 255], [127, 255, 127]], [[239, 255, 15], [127, 0, 0]]])
plt.imshow(img)


text:
Q: How can I build on top of lakes? My factory is doing great, except for a large lake right in the middle of it.
Is there any way to fill the lake in to reclaim the space it takes up? Or do my conveyors need to detour around it?

A: Before 0.13 there was no way to cross bodies of water in vanilla Factorio. There were a couple of mods with different solutions.
A lot of players argued that building with the lay of the land is a nice challenge and give your factory "character" and makes it unique.
Other guys just wanted to build a massive factory and then use the mods to help them cross it.
Since 0.13, you can research the "land fill" technology and then use it to replace water with soil.

A: With the release of version 0.13, researching the landfill technology will let you construct a landfill item that replaces water with grass. It costs 20 stone to create and builds in half a second.
Unfortunately there is no equivalent item to turn land into water, so be careful not to deprive yourself of locations for water pumps!


text:
Q: How to ignore errors in a module type declaration file There are some errors in a package globby which is not a direct dependency. How can I ignore this?
node_modules/globby/index.d.ts:6:14 - error TS1005: ';' expected.

6       | readonly string[]
                   ~~~~~~

node_modules/globby/index.d.ts:6:21 - error TS1011: An element access expression should take an argument.

6       | readonly string[]

node_modules/globby/index.d.ts:7:23 - error TS1005: ',' expected.

7       | {files?: readonly string[]; extensions?: readonly string[]};
                            ~~~~~~

node_modules/globby/index.d.ts:7:29 - error TS1005: ',' expected.

7       | {files?: readonly string[]; extensions?: readonly string[]};
                                  ~

node_modules/globby/index.d.ts:7:30 - error TS1109: Expression expected.

7       | {files?: readonly string[]; extensions?: readonly string[]};
                                   ~

node_modules/globby/index.d.ts:7:31 - error TS1005: ':' expected.

7       | {files?: readonly string[]; extensions?: readonly string[]};
                                    ~

node_modules/globby/index.d.ts:7:55 - error TS1005: ',' expected.

7       | {files?: readonly string[]; extensions?: readonly string[]};
                                                            ~~~~~~

node_modules/globby/index.d.ts:7:61 - error TS1005: ',' expected.

7       | {files?: readonly string[]; extensions?: readonly string[]};
                                                                  ~

node_modules/globby/index.d.ts:7:62 - error TS1109: Expression expected.

7       | {files?: readonly string[]; extensions?: readonly string[]};
                                                                   ~

node_modules/globby/index.d.ts:7:63 - error TS1005: ':' expected.

7       | {files?: readonly string[]; extensions?: readonly string[]};
                                                                    ~

node_modules/globby/index.d.ts:51:30 - error TS1005: ';' expected.

51      readonly ignore?: readonly string[];
                                   ~~~~~~

node_modules/globby/index.d.ts:51:37 - error TS1011: An element access expression should take an argument.

51      readonly ignore?: readonly string[];

node_modules/globby/index.d.ts:55:1 - error TS1128: Declaration or statement expected.

55 }
   ~

node_modules/globby/index.d.ts:104:31 - error TS1005: ',' expected.

104     patterns: string | readonly string[],
                                    ~~~~~~

node_modules/globby/index.d.ts:104:37 - error TS1005: ',' expected.

104     patterns: string | readonly string[],
                                          ~

node_modules/globby/index.d.ts:118:31 - error TS1005: ',' expected.

118     patterns: string | readonly string[],
                                    ~~~~~~

node_modules/globby/index.d.ts:118:37 - error TS1005: ',' expected.

118     patterns: string | readonly string[],
                                          ~

node_modules/globby/index.d.ts:143:31 - error TS1005: ',' expected.

143     patterns: string | readonly string[],
                                    ~~~~~~

node_modules/globby/index.d.ts:143:37 - error TS1005: ',' expected.

143     patterns: string | readonly string[],
                                          ~

node_modules/globby/index.d.ts:155:31 - error TS1005: ',' expected.

155     patterns: string | readonly string[],
                                    ~~~~~~

node_modules/globby/index.d.ts:155:37 - error TS1005: ',' expected.

155     patterns: string | readonly string[],
                                          ~

node_modules/globby/index.d.ts:169:31 - error TS1005: ',' expected.

169     patterns: string | readonly string[],
                                    ~~~~~~

node_modules/globby/index.d.ts:169:37 - error TS1005: ',' expected.

169     patterns: string | readonly string[],
                                          ~


text:
Q: SWT- How to change ProgressBar color in Windows? Is there a way to change the color of a ProgressBar's bars in SWT?  .setForeground() doesn't seem to work.
If there is not a way to change the color programmatically, is there a way to change ProgressBar's color using the WindowBuilder GUI tools?
Thanks!

A: In SWT there are 3 built-in states, each represented by a color:
progressBar.setState(SWT.ERROR); //Red Fill color. Useful when the task is aborted.

This state does not support an indeterminate progress bar style (SWT.INDETERMINATE).
progressBar.setState(SWT.PAUSED); //Yellow Fill color.

This state will pause the indeterminate progress bar animation.
progressBar.setState(SWT.NORMAL); //Default state and color as controlled by OS.

A: You can't change the color of the progress bar on Windows using SWT.

A: You can now, using JProgressBar.setForeground( Color )


text:
Q: Components cannot be accessed after migrating from ionic3 to ionic4 I have migrated from ionic v3 to ionic v4 with the help of Migration from ionic3 to ionic4 documentation.
As per the documentation i have installed newer version of angular by doing
$npm install @ionic/angular
Now in all my pages if my try to import the following statement
import { IonicPage, NavController, NavParams, ViewController, LoadingController } from '@ionic/angular';

IonicPage and ViewController is underlined with red line suggesting the error as `Module has no exported member
How to overcome this issue, i am not able the revert back to older version of ionic-angular

A: They cant be assessed because ionic 4 does support 'Pages' like they used to. Now they just use angular components which you use the router to jump between. I'd advice generating your pages components using the ionic cli that will make a page like component for you, then migrate your logic over.


text:
Q: Edit plugin's HTML output with Hooks I'm trying to edit the HTML output of a plugin, but I'm not sure how to do it properly.
This is the code
// display the heading
$content .= '<h' . $heading_level . ' class="mbm-book-grid-heading' . ( $l + 1 ) . '">' . esc_html($label) . '</h' . $heading_level .'>';
do_action('mbdb_book_grid_post_heading', $l, $label);

What I want to change is the $label, the new code would look like this
$text_label = explode(':', $label);
$text_label = $text_label[1];
$content .= '<h' . $heading_level . ' class="mbm-book-grid-heading' . ( $l + 1 ) . '">' . esc_html($text_label) . '</h' . $heading_level .'>';

Now, how can I proceed to that by using Wordpress Actions and Filters? I've never done this before, so I'm a bit confused.
Thanks.


text:
Q: Find the median in an unsorted read-only array Given a read-only array with n elements, find the median (the ceiling(n/2)-th element by size) in the array, with O(logn) space and average time O(nlogn).

*

*The elements in the array are different.

*The array is not sorted.

*You can't change any of the values in the array, only read them

I thought about using the idea of Quicksort but it is impossible to perform it without changing the array. And to copy to another array would exceed the required space.

A: You can solve it using divide and conquer approach, find a random element in between the minimum and maximum, check if it's median, if the median is lower or higher than it, and reduce the problem to a smaller size only on a subrange of the array.

*

*Set min as the smallest element in the array, and max as the biggest one.

*Choose a random number mid in range (min < mid < max), if there is no such mid, either min or max is median, find which and you are done.

*Check if either of min, mid or max is the median (linear search, count how many are bigger/smaller).
3.1. If so,you are done.
3.2. Otherwise, the median is in between (min,mid) or (mid,max), and you know where (if more are higher than mid or lower than it).
3.3. If it's in (min,mid), set max = mid, otherwise, set min = mid.
3.4. Return to 2.

Correctness:

*

*If the algorithm finds a number - the stop clause is only due to finding the median.

*For each iteration, the median is still in (min,max) (formal proof with induction..), and the range is guaranteed to shrink in each iteration, so the algorithm is guaranteed to stop and yield some result.

Time complexity:

*

*Step 1: repeats only once and takes O(n) time.

*Step 2: takes O(n) time (finding the distinct numbers in range) and repeats each iteration.

*Step 3: takes O(n) time (going through each range is linear).

There are O(logn) iterations on average case (similar to binary search reasoning).
This gives us O(nlogn) time complexity

Space complexity:
Implementation dependent, but with tail recursion (similar to the above high level pseudo code) can actually be O(1). With regular recursion this is O(logn), for the stack.

A: Here is a simple algorithm. It consists of searching for the median by keeping track of the lower and upper bound of an interval where the median is.
Let E be the list of elements. Set the lower and upper bounds, L and U, of the median to null.
For every element e in E,

*

*If L is not null and e < L, e cannot be the median, skip to next element. If U is not null and e > U, e cannot be the median, skip to next element.

*Scan E and count the number B of elements before e, and the number A of elements after e.

*If A = B, e is the median, terminate. If A = B + 1, there is no single median, but e is immediately before the median point, terminate. If B = A + 1, there is no single median, but e is immediately after the median point, terminate.

*If A > B, the median is after e, set L = e. If B > A, the median is before e, set U = e.

Space complexity is O(1). Time complexity is at most O(n2) and O(nlogn) on average.
Example:
E = [2 4 7 9 0 6 5]
       L,U = null,null  Initial state.
e = 2  L,U = 2,null     Update L.
e = 4  L,U = 4,null     Update L.
e = 7  L,U = 4,7        Update U.
e = 9  L,U = 4,7        Skip 9.
e = 0  L,U = 4,7        Skip 0.
e = 6  L,U = 4,6        Update U.
e = 5  Median is 5      Terminate.


text:
Q: ViewPagerFragments args (System.out.println() and TextView act differently) So I have created a Fragements inside ViewPager and below is my part-code:
(System.out.println(mNum) not printing actual values but TextView is. For example when sliding fragments from left to right, in second fragment, it prints 1 but when sliding right to left it prints 2, although TextView display it properly in both cases.
From Android.Developers http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html
@Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mNum = getArguments().getInt("num");
            viewPager=(ViewPager)getActivity().findViewById(R.id.pager);
        }

        /**
         * The Fragment's UI is just a simple text view showing its
         * instance number.
         */
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
            View tv = v.findViewById(R.id.text);
            ((TextView)tv).setText("Fragment #" + mNum);
            System.out.println(mNum);
            return v;
        }

A: When you are using viewPager:
Lets say you are in screen 1, screen 2 is also loaded into memory by the viewPager but its not visible. Since screen 2 fragment is instantiated , you get the output of screen 2 in 'System.out.println(mNum);'.
For more info setOffscreenPageLimit


text:
Q: How to dinamically add ImageView/textView at the right of others ImageView/textView in a same layout So in my code I have 6 arrays (the 5 last could be empty) of objects. Each objects has a name and the array could have many of each object (every array are sorted so every item are grouped).
First, I have this xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/fond4"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="20dp"
    android:background="@color/white"
    android:gravity="center"
    android:text="@string/commentOpti"
    android:textSize="20sp" />

<Button
    android:id="@+id/choisirTroupe"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="20dp"
    android:onClick="soumission"
    android:text="@string/lancer" />

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:context="${relativePackage}.${activityClass}" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"
            android:background="@color/white"
            android:gravity="center"
            android:text="@string/casernes"
            android:textSize="20sp" />

        <!-- Caserne 1 -->

        <LinearLayout
            android:id="@+id/caserne1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:background="@color/white"
            android:orientation="horizontal" >

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_marginLeft="10dp"
                android:background="@drawable/caserne" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="@string/deuxPoints"
                android:textSize="25sp" />
        </LinearLayout>

        //Then 5 other like this 1st linearLayou
        //The ids are incremented each time like caserne2 for the 2nd etc...

</ScrollView>

It look like this: https://gyazo.com/17a1276dfff5521d540fb6dc953df424
What I want to do is, for each object in each array (one array: one linear layout), to add a textView with the number of Item and an imageView which represent the object.
Next, you will find how I sort everything, that's not really important I think, but if you want to understand everything you'll have to give a look :p
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_optimisation);

    LinearLayout caserne1 = (LinearLayout) findViewById(R.id.caserne1);
    //...Doing this for the 5 others...

    Intent intent = getIntent();

    //Instanciation of my object
    OptiClashOfClans o = new OptiClashOfClans();

    //In fact, the number of linearLayout i'll have to work with
    o.setNbCasernes(this.nbCaserne);

    if (this.nbBarbares > 0)
        o.ajouterFormation(1, this.nbBarbares);
    //...Adding each object in on array...
    o.setAFormer(o.triTroupe());

    //And finally here i'll put each object in the good array
    o.orgaCaserne(o);

Now we go for my problem, this portion of code is just next to the one I put previously, here is how I pick up the number of the same object in each array
for (int cptCaserne = 0; cptCaserne < this.nbCaserne; cptCaserne++) {

        // Here I pick up the array of object I'll work with
        Caserne casTmp = o.getCaserneNum(cptCaserne);

        // Here I pick every object which are in the previous array
        ArrayList<Troupe> enFormTmp = new ArrayList<Troupe>();
        enFormTmp = casTmp.getEnFormation();

        // To count where I am in the array of object
        int cptAFormer = 0;

        //To know if the next object is different from the one I'm working with
        Troupe troupTmp = enFormTmp.get(cptAFormer);

        int cptTroupTmp = 0;

        //For the object t in the array of object
        for (Troupe t : enFormTmp) {
            cptTroupTmp = 0;

            //While the object is the same from the one we're working with
            while (!troupTmp.equals(t)) {
                //Incrementing the previous counter
                cptTroupTmp++;
                cptAFormer++;
            }

And finally here is how I don't really know how to do:
            ImageView iView = new ImageView(Optimisation.this);

            //To know which background i'll add to the image view
            //I'll do this for each different object
            if (t.getNom().equals("Barbare"))
                iView.setImageResource(R.drawable.barbare);
            //...

            //The text view with the number of object I found
            TextView tView = new TextView(Optimisation.this);
            tView.setText("" + cptTroupTmp);

            //And now it's here where I want to add the different views
            switch (cptCaserne) {
            case 0:
                caserne1.addView(tView);
                caserne1.addView(iView);
            case 1:
                caserne2.addView(tView);
                caserne1.addView(iView);
            case 2:
                caserne3.addView(tView);
                caserne1.addView(iView);
            case 3:
                caserne4.addView(tView);
                caserne1.addView(iView);

            }
            troupTmp = enFormTmp.get(cptAFormer);
        }

    }

With this code I have an insane black screen when I'm going on this activity.
Here is what I want to do with in red the textView with the number of objet and in green the imageView of the object...
https://gyazo.com/31b16982ce30b66391bafdd2cd4d86fc
I've found some stuff to do with LayoutInflater but I haven't been successfull with these... Thanks a lot if you could help me.
PS: sorry for the mistakes, I think there are a lot, but in long post like this one, my school english isn't very effective ^^
Thanks again :)

A: Correct me if I'm wrong. But from what I understood you just need to accomplish what is being shown here https://gyazo.com/31b16982ce30b66391bafdd2cd4d86fc?
Base on your code you just have to add an additional LinearLayout having an horizontal orientation on each LinearLayout before adding the TextView and Image View.
Here's an example using your code:
LinearLayout innerLayout = new LinearLayout(Optimisation.this)
innerLayout.setOrientation(LinearLayout.HORIZONTAL);
ImageView iView = new ImageView(Optimisation.this);

        //To know which background i'll add to the image view
        //I'll do this for each different object
        if (t.getNom().equals("Barbare"))
            iView.setImageResource(R.drawable.barbare);
        //...

        //The text view with the number of object I found
        TextView tView = new TextView(Optimisation.this);
        tView.setText("" + cptTroupTmp);

        innerLayout.addView(tView);
        innerLayout.addView(iView);

        //And now it's here where I want to add the different views
        switch (cptCaserne) {
        case 0:
            caserne1.addView(innerLayout);
        case 1:
            caserne2.addView(innerLayout);
        case 2:
            caserne3.addView(innerLayout);
        case 3:
            caserne4.addView(innerLayout);

        }

Feel free to adjust it if the Layout that I'm adding the innerLayout in is wrong. But basically, that's the idea.


text:
Q: Using Process.Start to open explorer Edit: solution found, will note under image at the end of the question
After a bunch of research here on SO, I found that the way to open explorer with a selected file was:
Process.Start("explorer.exe", "/select, " + path);
However when I do this with controlled input, Explorer opens just its main window, however when I harcode the function call to the same value that's in the path variable (In my control test its a text file in C:\Temp) it works. So if I do the above when path is "C:\Temp\test.txt" It does't open explorer in the temp folder, however when I do:
Process.Start("explorer.exe", "/select, C:\\Temp\\test.txt");
It works perfectly, opening explorer and highlighting the file. What is happening here? Is there something wrong with the internal formatting on my string variable or something?
(Additionally, I ran into the same issue using the path variable to open a FileInfo. Hardcoded to the same value would work, but using the variable gave me a "the given path's format is not supported" exception")
Image showing that path and the harcoded value are the same:

The 2 explorer windows (cropped for Security) are the results of the 2 respective calls. The one with the variable shows te basic explorer main page. The one that's hardcoded shows the file selected as expected.
Edit: There was a hidden Left-To-Right Format character hidden in the front of the string.

A:     public static class Program
    {
        static void Main()
        {
            Explore("C:\\Users\\art_g\\Desktop\\Sample.txt");
        }
        static void Explore(string path) =>
            Process.Start("explorer.exe", "/select, " + path);
    }

Works like a charm. Check your path string.


text:
Q: Uncaught SyntaxError: missing ) after argument list error deviceConnect.innerHTML = "<input type='button' value='Connect' onclick='connectSerial("+ device.id +")' />";

What am I doing wrong? I am breaking my head over it and I cannot see why this wouldn't work..
EDIT: device.id has a value of: AA:BB:CC:DD:EE:FF

A: You need to enclose inner value in the double quotes
        deviceConnect.innerHTML = "<input type='button' value='Connect' onclick='connectSerial(\""+ device.id +"\")' />";


text:
Q: What, how to gain from websitespark? I got OS and software licenses from websiteSpark,
I am asking how "from point of view" to gain the most from websitespark.
for example, they give windows server  2008, but i found it useless, because i asked many hosting companies and they told me that getting hosting with its windows is a must, and they don't allow others to install OS.
Can you share how it will help developers, and small start up individual companies?

A: Having Windows Server licenses is only useful if you need dedicated boxes. In which case, hosting providers who participate in the BizSpark/WebsiteSpark program can offer you dedicated boxes for what is essentially the cost of the hardware. This is an even bigger deal with SQL Server, which can get very expensive depending on your configuration.
Or you can host your own boxes. Either way, WebsiteSpark has basically eliminated the licensing costs for a startup using the MS stack. Of course you still have to pay for your hardware, electricity bills, etc - but that doesn't make it useless!


text:
Q: Run 3 threads and wait in Java I'm trying to write a class that can only run X(Let's say 3)threads at one time. I have 8 threads that need to execute but I only want to allow 3 to run at once, then wait.  Once one of the currently running threads stops, then it will start another.  I'm not quite sure how to do this.  My code looks like this:
public class Main {
  public void start() {
    for(int i=0; i<=ALLTHREADS; i++) {
      MyThreadClass thread = new MyThreadClass(someParam, someParam);
      thread.run();

      // Continue until we have 3 running threads, wait until a new spot opens up.  This is what I'm having problems with
    }
  }
}

public class MyThreadClass implements Runnable {
  public MyThreadClass(int param1, int param2) {
    // Some logic unimportant to this post
  }

  public void run() {
    // Generic code here, the point of this is to download a large file
  }
}

As you can see above most of it is stubbed out pseudo-code.  I can post it if anyone would like but it's unimportant to the main question.

A: you should use thread pooling mechanism here to run multiple threads.
to make it easy we can go for thread pool executor in java which is very easy
create a fixed pool of 3 threads using executors method.
write a for loop for 8 iteration and call execute on each thread and it will run only 3 threads at a time.
ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 8; i++) {
             Task task = new Task(someParam, someParam);
            executor.execute(task);
          }
        executor.shutdown();

A: Unless this is homework, you can use Executors.newFixedThreadPool(3) which returns an ExecutorService with a max of 3 threads to perform Runnable tasks.


text:
Q: Symfony2: Disconnect Associations on delete I have two entities - Background and Action.
a Background has many Actions.
When I delete a Background I want to keep the Action but null the foreign key. Effectively orphaning the entity in a way that will satisfy constraints.
I have read so many articles and questions about cascade={"remove"} and orphanRemoval but all of these seem to result either in deleting the orphaned Action (not at all what I want) or doing nothing - which results in an integrity constaint violation.
SQLSTATE[23000]: Integrity constraint violation:
1451 Cannot delete or update a parent row:
a foreign key constraint fails (`Action`, CONSTRAINT
`FK_B7722E25C93D69EA` FOREIGN KEY (`background_id`)
REFERENCES `Background` (`id`))

For now the solution I found was to iterate through the related Actions and null the field and persist. This can't be the best way forward.
foreach ($background->getActions() as $action) {
  $action->setBackground(null);
}

A: You can achieve this with the doctrine ondelete behaviour that can null the references.
Here an example of how I implemented this in an old sf2.3 project:
/**
 * Workaround for circular reference:
 * http://stackoverflow.com/questions/14257004/doctrine2-symfony2-cascading-remove-integrity-constraint-violation-1451
 */

/**
 * @ORM\OneToOne(targetEntity="Acme\DashboardBundle\Entity\AlternativeProposal")
 * @ORM\JoinColumn(name="selected_alternative_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
 */
protected $selectedAlternative;

Hope this helps


text:
Q: Google sheets scripts function UrlFetchApp.fetch does not run from .onEdit(e) but works from editor I have created a google sheet with a lot of info for a beach volleyball cup and I want to call an API I have created when a checkbox is checked in this sheet.
function onEdit(e){
  const ui = SpreadsheetApp.getUi();
  const spreadsheets = SpreadsheetApp.getActive();
  const configSheet = spreadsheets.getSheetByName("Config")
  var tourneyId = String(configSheet.getRange(2,4).getValue())
  var tourneyTitle = String(configSheet.getRange(2,5).getValue())
  var sheet = spreadsheets.getActiveSheet()
  if (sheet.getName() == "LiveScore"){
    var actRng = sheet.getActiveRange();
    var editColumn = actRng.getColumn();
    var rowIndex = actRng.getRowIndex();
    actRng = actRng.getCell(1, 1);
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
    if(editColumn == 7 && rowIndex != 1){
      onStartBroadcastClicked(actRng, ui, sheet, rowIndex, editColumn, tourneyTitle);
    }
  }
}

There is never any problems with this part as I see it. But when i get into the function onStartBroadcastClicked:
function onStartBroadcastClicked(actRng, ui, sheet, rowIndex, editColumn, tourneyTitle){
  var homeTeam = String(sheet.getRange(rowIndex, 14).getValue());
... // more setting variables
  var endTime = new Date(startTime.getTime() + MILLIS_PER_MATCH);

  if(actRng.isChecked()){
    var response = ui.alert("You are about to start a new broadcast. Are you sure?" +
                            "\n Title: " + title, ui.ButtonSet.YES_NO);
    if (response == ui.Button.YES) {
      var httpRequest = "https://someUrl";
      var options =
          {
            'method':'POST',
            'contentType': 'application/json',
            'payload' : JSON.stringify({
              "title" : title,
                  ... // setting all variables
              "description" : description
            }),
            'muteHttpExceptions' : true,
            'headers' : {
              "Authorization": "Basic " + Utilities.base64Encode(USERNAME + ":" + PASSWORD)
            }
          };

      ui.alert("Waiting.......")
      var result = UrlFetchApp.fetch(httpRequest, options);
      ui.alert(result.getContentText())

The issue is that it always gets to the line ui.alert("Waiting......."), but when triggered from the checkbox, it never succeeds the http POST request. If I click play inside the editor, it succeeds and I got the response in the alertbox.
Could it be some timeout or some autosave issues? Does anyone have any idea if where to keep looking? I've been stuck here for some time now and I would be really happy if anyone can point me to the correct direction.

A: The modification point of your issue is to use the installable trigger of OnEdit event. When the methods which are required to authorize used at the simple trigger, the error occurs. This situation makes us think that it seems the script doesn't work.
In order to avoid this error, please use the installable triggers of OnEdit event trigger.
As an important point, before you install the trigger, please rename the function name of onEdit() to other name. And install the renamed function name as the OnEdit event trigger. By this, the duplicate run of onEdit() can be prevented. If onEdit() function is installed as the installable trigger, when a cell is edited, the function is run 2 times. Ref.
By above settings, when the cell is edited, UrlFetchApp.fetch() works.
References:

*

*Simple Triggers

*Installable Triggers

*Asynchronous Processing using Event Triggers

A: I was able to get a script to work with a trigger if I created the script from script.google.com and call the Google Sheet and tab from the script.  I'm manually entered in my API calls per cell within a specified Row:
function fetchUrls() {
    var spreadsheetId = "ENTER GOOGLE SHEET ID";
    var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
    var sheet = spreadsheet.getSheetByName("ENTER SHEET NAME");
    var range = sheet.getRange("ENTER RANGE OR FULL COLUMN"); // specify the range of cells in column B
    var urls = range.getValues(); // get the values of the cells and store them
    in an array

    var cache = CacheService.getScriptCache();

    for (var i = 0; i < urls.length; i++) {
        if(urls[i][0] != "") { // check if the current cell is not empty
            var url = urls[i][0];
            var result = cache.get(url);
            if(!result) {
                var response = UrlFetchApp.fetch(url);
                result = response.getContentText();
                cache.put(url, result, 21600);
            }
            sheet.getRange(i+1,3).setValue(result); // set the value of the current cell to the result of the API call in column C
        }
    }
}


text:
Q: How to create a mutli page Vue.js app without Vue-Cli? I created a Vue.js app without using Vue CLI, so that means I did everything from scratch including setting up Webpack 4. The reason I did this was because I don't like the idea of frameworks concealing the inner workings of things so that I can't fix things myself.
As an SPA, I have got the basic demo site working with an Home and About view. But I am looking to create a multi-page app with Express. The only information on multi-page Vue.js apps seems to be linked to the pages option that only comes with Vue CLI (see here)
Is there a way to have a multi-page app for projects created without Vue CLI?

A: Sure, you could handle routing with Express and have the page rendered server-side.
You can use Vue official package for routing, vue-router and choose between SSR (server-side rendering) or client side.
I suggest you to check this official doc about it: https://ssr.vuejs.org/


text:
Q: Trouble with counting and highlights I am trying to create two functions. One uses two arguments, a filename, and a keyword. It needs to highlight the word and return the highlighted word or words with the line number.
The second function counts the number of times a specific word occurs in a file. Once again this one uses two arguments a filename and a keyword.
This one is called highlight. It needs to look at each line, find the keyword, then returns the line number with the keyword highlighted bracketed by '-->' on the left and '<--" on the right.
def highlight(filename, keyword):
    inpt = open(filename, "r")
    for line in inpt:
        if re.match(keyword, line):
            print ('-->',line,'<--')

This function uses a filename and keyword and counts the number of times a specific word occurs in a file, then returns the count.
def count_word(filename, keyword):
    fname = (filename)
    word= (keyword)
    count = 0
    with open(fname, 'r') as in_file:
        for line in in_file:
            words = line.split()
            for i in words:
                if(i==word):
                    count=count+1
                print (count)

Am I going in completely the wrong direction? Am I close at all?
The text file reads:
I heart Rocket!
Rocket, Rocket, Rocket.
Don't say it.
Rocket, Rocket, Rocket!

Rocket!!!

Right now I am getting:
highlight:
printed:
--> Rocket, Rocket, Rocket.
 <--
--> Rocket, Rocket, Rocket!
 <--
--> Rocket!!!
 <--

expected:
1:   I heart -->Rocket<--!
2:   -->Rocket<--, -->Rocket<--, -->Rocket<--.
4:   -->Rocket<--, -->Rocket<--, -->Rocket<--!
10:  -->Rocket<--!!!

count_word:

printed:
0
0
0
0
0
0
0
0
0
0
0
0
0

expected:
8

A: If you iterate lines from a file, each line ends with a newline '\n'.
If you prepend '-->' and append '<--', the '<--' is added after the newline character. You could change your code, remove the \n and add <-- .. but it can be done far easier:

*

*replace text with str.replace("replace what","replace with what")

*enumerate (iterable, start) your lines

*use f-string formatting

*count using str.count()
Create file:
with open("k.txt","w") as f:
    f.write("""I heart Rocket!
Rocket, Rocket, Rocket.
Don't say it.
Rocket, Rocket, Rocket!

Rocket!!!""")

Process file:
with open("k.txt") as f:

    # read all text
    text = f.read()

    # replace Rocket with -->Rocket<-- and store as text2
    text2 = text.replace("Rocket","-->Rocket<--")

    # split at \n, enumerate result starting at 1, remove any line
    # that does not contain Rocket, join with \n
    text3 = text2.split("\n")
    text4 = [f"{row:2d} {x}" for row,x in enumerate(text3,1) if "Rocket" in x]
    text5 = "\n".join(text4)

    # Count rockets and print replaced text
    print(text.count("Rocket"))
    print(text3)
    print(text4)
    print(text5)

Output:
# the rocket count
8

# text3: all lines
['I heart -->Rocket<--!', '-->Rocket<--, -->Rocket<--, -->Rocket<--.', "Don't say it.",
'-->Rocket<--, -->Rocket<--, -->Rocket<--!', '', '', '', '', '', '-->Rocket<--!!!']

# text4: with enumeration of line number
[' 1 I heart -->Rocket<--!', ' 2 -->Rocket<--, -->Rocket<--, -->Rocket<--.',
 ' 4 -->Rocket<--, -->Rocket<--, -->Rocket<--!', '10 -->Rocket<--!!!']

 # joined together again
 1 I heart -->Rocket<--!
 2 -->Rocket<--, -->Rocket<--, -->Rocket<--.
 4 -->Rocket<--, -->Rocket<--, -->Rocket<--!
10 -->Rocket<--!!!

If you want to confuse yourself you can do it as 4-liner:
with open("k.txt") as f:
    text = "\n".join(
        [f"{row:2d} {x}" for row,x
         in enumerate( f.read().replace("Rocket","-->Rocket<--").split("\n"),1)
         if "Rocket" in x])
    print(text.count("Rocket"))
    print(text)