text:
Q: closing mongodb connection and get correct results with multiple parallel asynchronous query I am new to Mongo and Node. I am currently using Mongoskin and Bluebird to handle the db connection and queries (as suggested here: https://stackoverflow.com/a/23687958/2701348 ).
I have three collections: Users, Binders and Cards.
The Binders collection contains the information about Cards for each User.
Each document in Binders has as properties:
User Id <--- that refers to the User owning the Card
Card Code <--- that refers to a Card
Count <--- that refers to the number of cards owned by the User

I prefer to have a separate Cards collection so that when a Card changes, it changes for all the Users Binders.
Now I am willing to retrieve an array for a given user such as:
[{card: {card document}, count: 4}, ...]

I have the following problems:

*

*the db connection should be closed after all the async db callbacks are called

*the cards array should be returned after the last db.collection('cards').find gives back the results

I know my following code is wrong but can be a starting point for a discussion:
var getAllBinderCards = function(req, res){
    var db = req.db;
    var userId = req.userId;

    var promiseBinders = db.collection('binders').find({userId: userId}).toArrayAsync();

    promiseBinders.then(function(binderCards) {
        if (binderCards) {
            var promiseCards;
            //console.log("------ binderCards: ", binderCards);
            var cards = [];
            for (var i = 0; i < binderCards.length; i++) {
                var binderCard = binderCards[i];

                promiseCards = db.collection('cards').find({Code: binderCard.Code}).toArrayAsync();
                promiseCards.then(function(cardsDB){
                    if(cardsDB){
                        //console.log("Cards found: ",binderCard.Code, cardsDB);
                        for (var i = 0; i < cardsDB.length; i++) {
                            cardsDB[i].count = binderCard.count;
                        };
                        cards.concat(cardsDB);
                    }
                });
            }

            promiseCards.then(function(){
                db.close();
                console.log("Binder Cards: " , cards);
                res.json(cards);
            });
        }
    });
}

I am struggling trying to figure out how to handle the promisfied asynchronous call correctly in order to send back the whole array and close the db connection.
I think I should try to build a promise before the for loop and use it to chain the query on Cards promises and lastly chain the db.close() and res.json(cards) statements.
[EDIT] Maybe the easiest solution is to simply use the $in filter inside a single db.collection('cards').find({Code: {$in: [bindersCodeArray] }}).toArrayAsync(); and avoid that for loop:
var getAllBinderCards = function(req, res){
    var db = req.db;
    var userId = req.userId;

    var promiseBinders = db.collection('binders').find({userId: userId}).toArrayAsync();

    promiseBinders.then(function(binderCards) {
        if (binderCards) {
            var binderCodes = binderCards.map(function(element){
                return element.Code;
            });
            var promiseCards = db.collection('cards').find({Code: {$in: binderCodes} }).toArrayAsync();
            promiseCards.then(function(cards){

                var bindersDictionary = {};

                for (var i = 0; i < binderCards.length; i++) {
                    bindersDictionary[binderCards[i].Code] = binderCards[i].count;
                };

                for (var i = 0; i < cards.length; i++) {
                    cards[i].count = bindersDictionary[cards[i].Code];
                };

                db.close();
                console.log("Binder Cards: " , cards);
                res.json(cards);
            });

        }
    });
}

Still I am curious if there is an elegant way to solve this riddle using promises.

A: I would expect that using $in and array may have constraints on the number of binders you can pass and affect query performance. You can also try doing this with async#map. e.g.:
...

function(binders) {
  async.map(binders, cardsForBinders, function(err, bindersWithCards) {
    // TODO: close connection here.
  }

  function cardsForBinders(binder, callback) {
    // 1. find cards for binder.
    // 2. prepare transformed response: binderWithCards.
    callback(null, binderWithCards);
  }
}

...


text:
Q: JS setInterval() работает только если расписать функцию целиком Обучаюсь по книжке Js for Kids (12 глава). В упражнении нужно сделать машинку, которая "едет" по экрану. Никак не могу понять, почему закомментированная строка не работает? Сама книга этот момент не освящает, а гугл только еще больше запутал.
let Car = function (x, y) {
    this.x = x;
    this.y = y;
};

Car.prototype.draw = function () {
    let carHtml = '<img src="images/car.png">';

    this.carElement = $(carHtml);

    this.carElement.css({
        position: "absolute",
        left: this.x,
        top: this.y
    });

    $("body").append(this.carElement);
};

Car.prototype.moveRight = function () {
    this.x += 5;
    this.carElement.css({
        left: this.x,
        top: this.y
    });
};

let nissan = new Car(100, 200);

nissan.draw();

// nissanMoveTimer = setInterval(nissan.moveRight, 1000); // Cannot read property 'css' of undefined
nissanMoveTimer = setInterval(function () { nissan.moveRight(); }, 1000); // Рабочий код

setTimeout(function () { clearInterval(nissanMoveTimer);}, 5000);

A: Вам правильно указали в комментариях о потери контекста вызова.
Что происходить на самом деле
setInterval(nissan.moveRight, 1000);

это эквивалент
let func = nissan.moveRight;

setInterval(func, 1000);

теперь вызов func() потерял контекст (nissan) так как вызывается напрямую. И this
внутри func() уже window или null в зависимости от мода

A: Потому что setInterval имеет синтаксис:
let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)

где func|code - это
функция или строка кода для выполнения. Обычно это функция. По историческим причинам можно передать и строку кода, но это не рекомендуется.

Надеюсь, понятно

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where does Flutter store the assets in the assets folder on the phone? I am interested in finding out the path where Flutter stores local files, the ones defined in the pubspec.yaml file. Is it a private location that only the app can access, or can I manually find it on the phone?
I want to make some audio files available only for premium users and I would like to store them locally, on the user's phone. I don't know if they can access those audio files without any trouble even if they are not premium users, just by looking them up. Could they find them by browsing the phone's folders?
Is there a storage limit to the Flutter assets folder?
Thanks! :D

A: It cannot be accessed without extracting the APK. As the documentation says that "An asset is a file that is bundled and deployed with your app and is accessible at runtime"
PS: So can exactly do premium and non premium thing it is only available in run time


text:
Q: Setting ServiceHost in VisualStudio when Working with Docker If you create a ASP.NET Core 3 Web API service it makes a file called launchSettings.json under "Properties".  That file has the following setting under docker:
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/index.html",

I am trying to find a way to set the ServiceHost part of this.  (Apparently this defaults to localhost.)  I tried adding
<ServiceHost>mycomputer.mydomain.net</ServiceHost>

to a PropertyGroup in my csproj file, but it had no effect (the default page loaded was still localhost).  (Though it will still work when I enter mycomputer.mydomain.net.
How can I set ServiceHost for my docker run?
NOTE: I would love an answer that includes how to do this with docker-compose as well.  (I tired moving this to docker-compose and only localhost would work (mycomputer.mydomain.net stopped working).


text:
Q: Is there a way of opening Visual Studio Code from MacOS terminal? I am used to opening Jupyter Notebook by simply typing 'jupyter notebook' in the terminal but was wondering whether there is a way of doing the same for for VS Code? (Tried opening it the same way as Jupyter but has not worked). Thank you!

A: Yes, you can open VSCode from the terminal but first, you need to add it to the PATH in MacOS
For zsh shell, run the following
cat << EOF >> ~/.zprofile
Add Visual Studio Code (code)
export PATH="\$PATH:/Applications/Visual Studio Code.app/Contents/Resources/app/bin"
EOF

If you use bash shell change the first line to
cat << EOF >> ~/.bash_profile
Now you can, open VSCode from the terminal by using the following commands

*

*To open VSCode with the previous session - code

*To open VScode in the current directory - code .

*To open a file in VSCode - code filename
More command-line options can be found here VSCode CMD Line


text:
Q: Problem in assign an URL to image tag and show image I have an img tag and I want to get an image from an URL and show in it.This URL specifies an ASPX page that I get the image from database in it's FormLoad and return that image.The problem is that the FormLoad method of page doesn't call.
I should say, I get the image from a database using a Link Server.
This code is my URL assigning:
imgManager.ImageUrl = "~/Portals/AbsencePresent/Form/SignForm.aspx?ManagerId=" +
managerObject.Id.ToString();

I don't get an error in this line of code and the application runs normally.
I try to copy this URL in browser manually, but nothing happened.
could you help me?
UPDATE 1
Here is the SignForm.aspx:
public partial class SignForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["ManagerId"] != null)
            {
                DataTable dt = AbsencePresent.BusinessObjects.Helper.GetSign(Request.QueryString["ManagerId"]);
                if (dt != null && dt.Rows.Count > 0)
                {
                    string signFileName = dt.Rows[0]["Name"].ToString();
                    //string extension = System.IO.Path.GetExtension(signFileName).ToLower();
                    Byte[] bytes = (Byte[])dt.Rows[0]["SrcFile"];
                    string imageFormat = AbsencePresent.BusinessObjects.Helper.GetContentType(bytes).ToString().ToLower();
                    string contentType = string.Empty;
                    if (imageFormat == "bmp")
                        contentType = "image/bmp";
                    else if (imageFormat == "jpeg")
                        contentType = "image/jpeg";
                    else if (imageFormat == "jpg")
                        contentType = "image/jpeg";
                    else if (imageFormat == "gif")
                        contentType = "image/gif";
                    else if (imageFormat == "png")
                        contentType = "image/png";
                    else if (imageFormat == "tiff")
                        contentType = "image/tiff";

                    Response.Buffer = true;
                    Response.Charset = "";
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.ContentType = contentType;
                    Response.AddHeader("content-disposition", "attachment;filename=" + signFileName);
                    Response.BinaryWrite(bytes);
                    Response.Flush();
                    Response.End();
                }
            }
        }
    }


text:
Q: MySQL, two tables displaying information from both tables I am learning SQL currently and I have a question. I have two tables called "vehicul" and proprietate.
The first table (vehicul) looks like this:
   id   nr_vehicul  marca   id_marca    tip     culoare     capacitate_cilindrica
    1   DJ-01-AAA   Mercedes    1       CLK 350 negru       3500
    2   DJ-01-BBB   Mercedes    1       S 500   silver      5000
    3   DJ-01-CCC   Mercedes    1       ML 550  alb         5500
    4   DJ-01-DDD   BMW         2       325     galben      2500
    5   DJ-01-EEE   BMW         2       X5      negru       350

And the second table (proprietate) looks like this:
id serie_buletin    cnp        nr_vehicul data_cumpararii pret
1   AK162332    2006036035087   DJ03AAA     2014-05-01  35000
2   AK162332    2006036035087   DJ03BBB     2014-05-02  90000
3   AK176233    6548751520125   DJ03CCC     2014-05-03  55000
4   BZ257743    6548751520125   DJ03DDD     2014-05-04  25000
5   BZ257743    2006036035087   DJ03EEE     2014-05-05  63000

I want to display the column "marca" from the first table and the column "price" from the second, but like this.
 marca   |  pret
Mercedes | 180000
  BMW    |  88000

Basically I have three Mercedes cars and two BMW cars, how can I display Mercedes one time and the prices of those three summed up?

A: You need to join two tables and GROUP them based on marca field and sum  pret
select marca, sum(pret)
from table1 as t1, table2 as t2
where t1.id=t2.id
group by marca

Here I'm assuming that id field is joining two tables, (but as I can see from your sampel data it isn't relating to each-other actually)
EDIT
I think you are missing id_marca field in table2. If its there then it would join to that column as below example:
select marca, sum(pret)
from table1 as t1, table2 as t2
where t1.id_marca=t2.id_marca
group by id_marca;

A: use this requeste
select marca, sum(pret)
from vehicul as Ve, proprietate as Pr
where Ve.nr_vehicul=PR.nr_vehicul
group by marca

or
select marca, sum(pret)
    from vehicul as Ve
    where Ve.id in(select nr_vehicul from  proprietate)
    group by marca

A: Your tables are not related and hence its impossible to get the desired output as you are looking for.
For the 2nd table I would suggest to add a column called id_marca and store  the value of each id_marca from first table to the 2nd table. So for all Mercedes its 1 and in the 2nd table also store it as 1 and for BMW its 2 and so on.
Now your tables are related and you can join as
select
v.marca
sum(p.pret) as pret
from vehicul v
join proprietate p on p.id_marca = v.id_marca
group by marca


text:
Q: React Redux is not updating component state in real time I have one component ImageGallery, in there I want to load more images after pressing Load More button. And, loadMore() function updates a react-redux globalState.js initialState value limit. But, When I am pressing Load More button I have to press 2 times for the first time to get the first 16 images. After that it's updating value as expected. But, first time I have to press 2 times. But, I want, it will work on first time  click and get 16 items and so on.
globalState.js:
export const globalState = createSlice({
  name: "global",
  initialState: {
  limit: 8
  }
  reducers: {
    // imageGallery
    incrementLimitGallery: (state) => {
      state.limit += 8;
    },
   },
});

Component ImageGallery.jsx:
let API = "https://www.example.com/images/";

export default function ImageGallery() {
  const dispatch = useDispatch();
  const limit = useSelector((state) => state.global.limit);
  const [images, setimages] = useState(null);

  async function fetchImages() {
    const response = await axios.get(API + limit);
    if ("error" in response.data) {
      setimages(null);
    } else {
      setimages(response.data);
    }
  }

  const loadMore = async () => {
    dispatch(incrementLimitGallery());
    await fetchImages();
  };

  return (
    <>
     //implementation of image gallery, long code so hide it

{images ? (imgaes.map(image => (.......))): null}

        <button onClick={() => loadMore()}>Load More</button>

    </>
  );
}

A: Your code will not work because it runs asynchronously so when you call fetchImages state hasn't been updated yet.
What I would propose is to use fetchImages inside a useEffect function which is dependent on limit.
loadMore on the other hand will trigger the redux state update and especially the limit update so then useEffect will run again.
  const loadMore = () => {
    dispatch(incrementLimitGallery());
  };

and something like this
useEffect(() => {
  fetchImages();
}, [limit]);

A: You can modify your loadmore function like this :
const loadMore = async () => {
    dispatch(incrementLimitGallery())
    .then(()=>{
        await fetchImages();
     });
  };

As the problem is, your redux state is not updated when you are fetching the images after the distpatch function(as dispatch is an async task). So you can run fetchImages function when the redux state is updated. Use .then method to implement the logic, as shown above.


text:
Q: SQL Server como agrupar registros por sequências quebradas Bom dia, caros!
Preciso criar um código para trazer registros desta maneira:
[registro de livros][1]
[1]: https://i.stack.imgur.com/ITiTb.jpg
Porém a tabela em que se encontram os registros, está assim:
[tabela de livros][2]
[2]: https://i.stack.imgur.com/fdiUy.jpg
O código desenvolvido até agora é esse:
SELECT
SCERTIFICADO.CODLIVRO, SCERTIFICADO.NUMREGISTRO
FROM SCERTIFICADO (NOLOCK)
WHERE
SCERTIFICADO.TIPO = 'D'
AND SCERTIFICADO.STATUS = 'E'
AND SCERTIFICADO.DTEMISSAO >= '2020-01-01'
AND SCERTIFICADO.DTEMISSAO <= '2022-12-01'
ORDER BY
SCERTIFICADO.CODLIVRO, SCERTIFICADO.NUMREGISTRO

Alguém teria alguma sugestão de como conseguir realizar esse agrupamento por registro, de sequências quebradas?
Desde já, agradeço!

A: Segue uma sugestão para testes onde é utilizada a função Row_Number para numerar as linhas e assim identificar as que estão em uma sequencia continua para fazer o agrupamento:
with CTE_RN as
(
    select
        CODLIVRO,
        NUMREGISTRO,
        ROW_NUMBER() OVER(PARTITION BY CODLIVRO ORDER BY NUMREGISTRO) AS RN
    from Tabela
)

select
    CODLIVRO,
    MIN(NUMREGISTRO) AS DE,
    MAX(NUMREGISTRO) AS ATE
from CTE_RN
group by
    CODLIVRO,
    RN - NUMREGISTRO
order by
    CODLIVRO,
    DE


text:
Q: can I use webapi in a production environment? Recently I was researching the ability to use the new Web Api framework from Microsoft for REST http services in a client's project. However, I believe the API is only in beta and not fully released. My application is currently running on .net 4.0 and using MVC3. Couple questions I have on this:
Does it work with MVC3, .Net 4.0?
What are the license implications of using WebApi in production? My client has in the past been concerned with using beta products in production so I will need to be able convince them that there is no risk or problems with using this.
I hope to use Web Api as it seems to do exactly what I want. Alternatively I will have to consider WCF Data Services. Or is there another alternative to produce REST services.

A: *

*It does work with .NET 4.0.

*Web API is part of MVC4. Although I think it could work in a MVC3 application, I don't think it's officially supported.

*The beta release has a "go live" license, which means that it can be used in production - but it's a beta release, so it's not officially supported. Also, the final framework will definitely change, so a code which works in Beta may not work in the final release. The project is open sourced now, so you can look at the latest bits at http://aspnetwebstack.codeplex.com.

*There are many other alternatives for creating REST services. Plain-old WCF works, WCF Data Services are interesting if you want mostly expose DB-backed data, and there are some non-Microsoft stacks as well.

A: See the EULA at %ProgramFiles(x86)%\Microsoft ASP.NET\ASP.NET MVC 4\eula.rtf
It says this:

If you comply with the rest of these license terms, you may also distribute to third parties or deploy for third parties to access over the Internet the ASP.NET programs that you develop using the software, provided that...

So basically that's a yes.


text:
Q: inside part of fingers What do we call the inside part of a finger?
Like we see in the picture below.
Supposing the hand is facing a door. Can we say?
The inside part of the fingers and palm are facing the door.
Please note that I need to mention both, "inside part of the fingers" and "palms".

A: It's called the flat of the hand when you hit someone with it. What are going to do the door? If it's jammed you'd probably use the flat of your hand to get it open. Describing the photo I'd say, "the hand is raised, its palm towards the door". Or, in a story, "He raised his hand, the palm towards the door." When you do that the fingers tend to face the same way. Do you need to mention them specifically?
In a calmer mood, with no-one to hit and the doors working normally, I might use 'front of the hand' as Jack O'Flaherty suggests, but it's usually only used when you've already mentioned the back of the hand.

A: All of that is the palmar surface of the hand, including the palmar side of the palm, and the palmar side of the fingers. It is also called the front of the hand.
The opposite is the dorsal, or back surface.
eOrthopod Hand anatomy

A: In medicine the ANTERIOR face of the fingers and the palm of the hand is called:
Volar
As opposed to the face considered Dorsal [1,2].
Regarding the fingers, the same reference can be used, but when you want to pay attention to the function or more specifically to the muscular components, you can also call it the flexor face of the fingers.
Firstly, I called the anterior face of the hand because all anatomical references are based on the Vitruvian man [3]
References:

*

*"Volar." Merriam-Webster.com Dictionary, Merriam-Webster, https://www.merriam-webster.com/dictionary/volar. Accessed 24 Apr. 2020 (https://www.merriam-webster.com/dictionary/volar)

*https://www.researchgate.net/figure/Dorsal-and-volar-surfaces-of-the-right-hand-demonstrating-a-wristwatch-imprint-from-the_fig2_278732617

*https://en.wikipedia.org/wiki/Vitruvian_Man


text:
Q: x-forwarded-for header not passed by AWS Application Load Balancer My tomcat application is not receiving X-Forwarded-For header from AWS Application load balancer. The load balancer is configured to offload SSL and connects with the tomcat application over HTTP. I am receiving other headers such as x-forwarded-proto, x-forwarded-port, x-amzn-trace-id. I am trying to find the client ip address but now stuck with it. I have also checked all the headers that I am receiving to find out the client ip address but it's just not there. Can anyone please help me?

A: This could be related to the tomcat configurations. Check whether you got following configs in tomcat to handle both X-Forwarded-For and X-Forwarded-proto headers
<filter>
    <filter-name>RemoteIpFilter</filter-name>
    <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
    <init-param>
      <param-name>protocolHeader</param-name>
      <param-value>x-forwarded-proto</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>RemoteIpFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
  </filter-mapping>

Here's the configuration reference :https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#Basic_configuration_to_handle_'x-forwarded-for'and'x-forwarded-proto'
You can find the configuration file in either $CATALINA_BASE/conf/web.xml or application's WEB-INF/web.xml

Tomcat provides a number of Filters which may be configured for use
  with all web applications using $CATALINA_BASE/conf/web.xml or may be
  configured for individual web applications by configuring them in the
  application's WEB-INF/web.xml.


text:
Q: Collapse and uncollapse not working Post 2. Original post 1 did not post answer I am using jQuery 2.1.4
I found this example on how to create a Webgrid displaying nested data.
http://www.dotnetawesome.com/2014/07/nested-webgrid-with-expand-collapse-in-aspnet-mvc4.html
I also found this post that had the same problem that I am having with a part of the jQuery that I am using.
Did not post the answer.
collaps and uncollaps is not working in my script
var size = $("#main #gridT > thead > tr >th").size(); // get total column
if (size > 0)
{
    $("#main #gridT > thead > tr >th").last().remove(); // remove last column
    $("#main #gridT > thead > tr").prepend("	"); // add one column at first for collapsible column
    $("#main #gridT > tbody > tr").each(function (i, el) {
        $(this).prepend(
                $("	")
                  .addClass("expand")
                  .addClass("hoverEff")
                .attr('title', "click for show/hide")
            );

        //Now get sub table from last column and add this to the next new added row
        var table = $("table", this).parent().html();
        //add new row with this subtable
        $(this).after("
	" + table + "
");
        $("table", this).parent().remove();
        // ADD CLICK EVENT FOR MAKE COLLAPSIBLE

        $(".hoverEff", this).on("click", function () {
            $(this).parent().closest("tr").next().slideToggle(1000);
            $(this).toggleClass("expand collapse");
        });
    });

    **//by default make all subgrid in collapse mode
    $("#main #gridT > tbody > tr td.expand").each(function (i, el) {
        $(this).toggleClass("expand collapse");
        $(this).parent().closest("tr").next().slideToggle(1000);
    });**
}

Once this part of the script is executed.  The nested data is being removed.
    **//by default make all subgrid in collapse mode
    $("#main #gridT > tbody > tr td.expand").each(function (i, el) {
        $(this).toggleClass("expand collapse");
        $(this).parent().closest("tr").next().slideToggle(1000);
    });**

Example of the display - image click here
View:
@model  IEnumerable<SqlApp.ViewModels.OrderDetailVM>

@{
    ViewBag.Title = "Order Detail List";

    WebGrid grid = new WebGrid(source: Model, canSort: false);

}

    @grid.GetHtml(
    htmlAttributes: new { id = "gridT", width = "700px" },
    columns: grid.Columns(
            grid.Column("Order_Detail_Line_ID", "Line ID"),
            //grid.Column(header: "Order Date", format: (item) => string.Format("{0:dd-MM-yyyy}", item.order.OrderDate)),
            grid.Column("Item_Code", "Item Code"),
            grid.Column("Facility_Code", "Facility Code"),
           grid.Column("List_Price_Amt", "List Price"),

            grid.Column(format: (item) =>
            {
                WebGrid subGrid = new WebGrid(source: item.orderDetailDeliveries);
                return subGrid.GetHtml(
                    htmlAttributes: new { id = "subT" },
                    columns: subGrid.Columns(
                            subGrid.Column("Item_Code", "Item Code"),
                            subGrid.Column("Requested_Delivery_Date", "Delivery Date"),
                            subGrid.Column("Delivery_Qty", "Quantity"),
                            subGrid.Column("Delivery_Ext_Price_Amt", "List Price")
                        )
                    );
            })
        )
    )

A: Fixed the problem by changing the style.
.collapse {
    background-image: url(/Images/pm.png);
    background-position-x: -2px;
    background-repeat: no-repeat;
    display: table-cell;
}


text:
Q: what is wrong with function ? (beginner in python)   s='insert 0 5 insert 1 10 insert 0 6 print remove 6 append 9 append 1 sort print'
  y=(s.split())

  i=[]

def commands(str_):
  if str_==[]:
    return[]
  elif str_[0]=='insert':
    return i.insert(int (str_[1]), str_[2]) + commands(str_[3:])
  elif str_[0]=='print':
    print (i) + commands(str_[1:])
  elif str_[0]=='append':
    return i.append(str_[1]) + commands(str_[2:])
  elif str_[0]=='remove':
    return i.pop(1) + commands(str_[2:])
  elif str_[0]=='sort':
    return i.sort() + commands(str_[1:])
  elif str_[0]=='pop':
    return i.pop() + commands(str_[1:])
  elif str_[0]=='reverse':
    return i.reverse()
print(commands (y))

hi, guys, I'm a beginner at python and was playing around with it and making my own function.
this function takes in a list of strings as commands and produces those commands, however, when I try to run this function this shows up
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
what is wrong with my function?

A: Passing an entire list to a function is counter-intuitive to me. One cleaner approach would be to iterate over the list of command values like below
new_list= []
for idx,command in enumerate(y):
    if command == 'insert':
        index = int(y[idx+1])
        value_to_insert = int(y[idx+2])
        new_list.insert(index,value_to_insert)

    elif command == 'print':
        print(new_list)

    elif command == 'append':
        value_to_append = int(y[idx+1])
        new_list.append(value_to_append)

    elif command == 'sort':
        new_list.sort() # inplace sorting

    elif command == 'remove':
        item_index = new_list.index(int(y[idx+1])) #multiple values can be present
        new_list.pop(item_index)

    elif command == 'pop':
        new_list.pop()

    elif command == 'reverse':
        new_list = new_list[::-1]


text:
Q: jquery not send more then 1 values I am working on project that when someone scrolls the page down, it loads more items. The  problem is when I use jquery to send two values via get in the url, it does not work.Wwhen items load then they do not work properly because php is not getting any value via jquery. My code is:
$(document).ready(function(){

function last_msg_funtionc()
{

   var ID=$(".productsc:last").attr("id");
   var CID=$(".productsc").attr("cid");
    $.post("categories.php?action=get&last_msg_id=+ID&cid="+CID,

    function(data){
        if (data != "") {
        $(".productsc:last").after(data);
        }
        $('div#last_msg_loader').empty();
    });
};

$(window).scroll(function(){
    if  ($(window).scrollTop() == $(document).height() - $(window).height()){
       last_msg_funtionc();
    }
});
});

And  when I send a single value this 'last_msg_id' it works fine.
What am I doing wrong?
my php code is
<?php
require_once'config.php';
$last_msg_id=$_POST['last_msg_id'];
$action=$_POST['action'];

if($action <> "get")
{
include_once'categories_first.php';
}
else
{

include'categories_second.php';

        }

amd categorys_first.php is not need to conect with jquery . jquerye get last id from categories_first.php. and now this is categories_second.php jquery send cid to this file
code is
$last_msg_id=$_GET['last_msg_id'];
$get_item=mysql_query('select * from items where cid="'.$_GET['cid'].'" and id < "'.$last_msg_id.'" order by id desc limit 4');
$last_msg_id='';
//another code here

A: Here is your code which has been updated
$.post("categories.php?action=get&last_msg_id="+ID+"&cid="+CID,

Here is how you should be doing this since you are not POSTing
$.get('categories.php', {'action':'get','last_msg_id':ID,'cid':CID}, function(data){ // your code });

A: correct line:
$.post("categories.php?action=get&last_msg_id="+ID+"&cid="+CID,

A: At a glance it looks like the ID var isn't outside of the quoted statement:
"categories.php?action=get&last_msg_id=+ID&cid="+CID
Try this:
"categories.php?action=get&last_msg_id=" +ID +"&cid="+CID

A: Use .get() since you're not actually sending any values through $_POST
var ID=$(".productsc:last").attr("id");
var CID=$(".productsc").attr("cid");
$.get("categories.php",
    {
        action: 'get',
        last_msg_id: ID,
        cid: CID
    },
    function(data){
        if (data != "") {
            $(".productsc:last").after(data);
        }
        $('div#last_msg_loader').empty();
});


text:
Q: Metabox with checkbox is not working true! please help me. i want to show display name of users in a meta box as checkbox. then i can choose many users to display some content in the post by:
if (in_array('special userID', get_post_meta($post->ID, 'U_S_C_users', true)) == true) {
  // Show the content here
  echo "ok";
}

by my code, i see this error:
warning: in_array() expects parameter 2 to be array in string:::: if (in_array($user->ID,$savedusers)){

my codes:
<?php

/* Define the custom box */
add_action('add_meta_boxes', 'User_specific_content_box');

/* Adds a box to the main column on the custom post type edit screens */
function User_specific_content_box() {
    add_meta_box('User_specific_content', __( 'User specific content box'),'User_specific_content_box_inner','class');
}

/* Prints the box content */
function User_specific_content_box_inner() {
    global $post,$wp_roles;
    $savedusers = get_post_meta($post->ID, 'U_S_C_users',true);
    var_dump($savedusers);

    // Use nonce for verification
    wp_nonce_field( plugin_basename(__FILE__), 'User_specific_content_box_inner' );
    echo '
'.__('By User Name:').'
';
    $blogusers = get_users('blog_id=1&orderby=nicename');
    $usercount = 0;
    foreach ($blogusers as $user) {
        echo '<input type="checkbox" name="U_S_C_users" value="'.$user->ID.'"';
        if (in_array($user->ID,$savedusers)){
            echo ' checked';
        }
        echo '>'.$user->display_name.'    ';
        $usercount = $usercount + 1;
        if ($usercount > 5){
            echo '
';
            $usercount = 0;
        }
    }
}

/* Save Meta Box */
add_action('save_post', 'User_specific_content_box_inner_save');

/* When the post is saved, saves our custom data */
function User_specific_content_box_inner_save( $post_id ) {
    global $post;
      // verify this came from the our screen and with proper authorization,
      // because save_post can be triggered at other times

      if ( !wp_verify_nonce( $_POST['User_specific_content_box_inner'], plugin_basename(__FILE__) ) )
          return $post_id;

      // verify if this is an auto save routine.
      // If it is our form has not been submitted, so we dont want to do anything
      if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
          return $post_id;
      // OK, we're authenticated: we need to find and save the data

    $savedusers = get_post_meta($post_id, 'U_S_C_users',true);

    if (isset($_POST['U_S_C_users']) && !empty($_POST['U_S_C_users'])){
        foreach ($_POST['U_S_C_users'] as $u){
            $new_users[] = $u;
        }
        update_post_meta($post_id, 'U_S_C_users', $new_users);
    }else{
        if (count($savedusers) > 0){
            delete_post_meta($post_id, 'U_S_C_users');
        }
    }
}
?>

my problems:
1- i see that error
2- i want to show just users with author role.

thanks to help me

A: That error happened because the $savedusers is not an array — in_array() requires the second parameter be a valid array, and if it's not, that error (or warning) is thrown.
And a simple fix to that is by type-casting the variable to an array like so:
$savedusers = (array) get_post_meta( $post_id, 'U_S_C_users', true );

Or better, use wp_parse_id_list() which makes sure $savedusers is an array of (user) IDs:
$savedusers = wp_parse_id_list( get_post_meta( $post->ID, 'U_S_C_users', true ) );

(You'll make the above change in User_specific_content_box_inner() and User_specific_content_box_inner_save() where get_post_meta() is called.)
Secondly, the checkboxes should be made an array by appending [] to their name like so:
echo '<input type="checkbox" name="U_S_C_users[]" value="'.$user->ID.'"';


text:
Q: Is this SMTP address specification valid? Does the following SMTP From header body represent a valid address specification as received by an SMTP server during an e-mail submission session.
"I robot" <robot@domain.com>[SP]

[SP] is the space character.
Looking at RFC822 https://www.rfc-editor.org/rfc/rfc822#section-3.2 and then https://www.rfc-editor.org/rfc/rfc822#section-6.1 I think the trailing space breaks the specs. Am I right?


text:
Q: Gradle GRPC compilation for Java, JS, C# Gradle protobuf plugin easily compiles .proto files to java classes.
Is it possible to do the proto compilation for javascript (or other languages) with the same plugin as well?
I want to generate ready artefact for several languages, so that other projects don't bother with proto related tasks and just use provided resource... also that will guarantee that every time i make a change to a proto file i get all different language versions compatible with each other...

A: You can generate for any language that protoc supports. Just add it to the "builtins" (or "plugins" if the support is provided by a protoc plugin, which is always the case if you want to generate GRPC services). For example, to generate C++ files for proto files under all sourceSets:
protobuf {
  generateProtoTasks {
    all()*.builtins {
      cpp {}
    }
  }
}

Then you will find all generated C++ sources under "build/generated/source/proto/{main|test}/cpp".
Although the Gradle protobuf plugin adds all the generated files to the input of Java compilation, according to my experimentation, Java compilation just ignores non-Java files, so it shouldn't cause you any trouble.
If you do want to generate GRPC services, you may have to compile the GRPC codegen plugins for the other languages except Java, since we only publish the codegen plugin for Java GRPC to the Maven repository.


text:
Q: Address not contiguous in multiple pointers I am trying to refresh my knowledge on pointers. I don't seem to understand why cout shows me the value of the object rather than address at the line showing ((*alpha+i)+j). The same output is shown when using &((*alpha+i)+j).
The reason I ask is because I thought memory allocation is contiguous but based on the output of the address, its,
Address 0: 0x19d7010
Address 1: 0x19d7018
Address 2: 0x19d7020
Address 3: 0x19d7028
Address 4: 0x19d7030

I thought it would be 10, 15, 20, 25 & 30
#include <iostream>

using namespace std;

int main( int argc, char **argv) {

char ** alpha;
alpha = new char * [5];
cout<<"Address alpha: "<<alpha<<'\n';

cout<<"Size of alpha: "<<sizeof(alpha)<<'\n';
for (int i=0; i<5; i++)
{
*(alpha+i)=new char [5];
cout<<"Address "<<i<<": "<<(alpha+i)<<'\n';

if(i<2)
for(int j=0; j<5; j++)
*(*(alpha+i)+j)='t';
else
for(int j=0; j<5; j++)
*(*(alpha+i)+j)='o';

for(int j=0; j<5; j++)
cout<<"Value "<<i<<": "<<(*(alpha+i)+j)<<'\n';

}

for(int i=0; i<5; i++){
cout<<"Value of i: "<<i<<'\n';
delete[] *(alpha+i);
}
delete[] alpha;
}

A: You are using 64 system In that size of pointers will be 8 bytes. If you take 8 bytes your address locations, You results are in continues locations
19d7018 − 19d7010 = 8
19d7020 − 19d7018 = 8
19d7028 − 19d7020 = 8

And How your said it should be 19d7020,19d7015,19d7010 etc.. ?
if you take like that then pointer size will 5 bytes. I think none of the architecture take 5 bytes for pointers.
19d7015 − 19d7010 = 5


text:
Q: How to handle less size situation in string concatination? I'm working on C and want to implements a string concatenation function.
I implemented following function:
void mystr_concat(char* dest, char* src)
{
        char* temp = dest;
        while(*temp)
        {
                temp++;
        }

        while(*src)
        {
                *temp++ = *src;
                src++;
        }
        *temp = '\0';
        return;
}

The output of above program is that it append "src"  string to "dest" string.
If user passed a "dest" string which is small in the length such that it can't append "src" string anymore.
e.g. user have this strings and invoked function
char dest[6] = "abcnd";
char src[100] = "zdfhjksdfskdfsdfsdfj";
mystr_concat(dest, src)

In this case
How to check the above raise condition and required solution to resolve this issue?

A: C does not perform any bounds checks on array references. If you need this done, you will need to either pass into the function the maximum size of the destination array and then verify that the source will fit (or decide to truncate it if required), or, introduce an additional data structure to track the length of strings in the way that typical Pascal implementation prefix each string with its maximum length.
Neither solution is automatic and to support this functionality in a safe way requires the use of a language like Java or C# to prevent the use of unsafe constructs.

A: Notice that strings, when passed as parameters of functions, are decayed to char pointers. And there is no portable way in C to know at runtime the size of a memory zone given by its pointer. So your mystr_concat cannot know the size of dest (unless you give that size somehow, e.g. by passing that size as an additional function paramter e.g. declaring
 void mystr_concat(char* dest, size_t destsize, char* src)

Then you might call it with e.g.
 char destbuf[36];
 strncpy (destbuf, sizeof(destbuf) /*i.e. 36*/, "start");
 mystr_concat(destbuf, sizeof(destbuf), "some-more");

Notice that the standard snprintf(3) function has a similar convention.
Another possible way is to decide that your function returns a heap allocated string and that it is the responsibility of its caller to free that string. Then you could code
char *my_string_catenation (const char* s1, const char* s2)
{
   if (!s1||!s2) return NULL;
   size_t s1len = strlen(s1);
   size_t s2len = strlen(s2);
   char* res = malloc(s1len+s2len+1);
   if (!res)
    { perror("my_string_catenation malloc"); exit(EXIT_FAILURE); };
   memcpy (res, s1, s1len);
   memcpy (res+s1len, s2, s2len);
   res[s1len+s2len] = (char)0;
   return res;
}

You then might code things like
 char buf[32];
 snprintf(buf, sizeof(buf), "+%d", i);
 char* catstr = my_string_catenation((i>30)?"foo":"boo", buf);
 do_something_with(catstr);
 free(catstr), catstr = NULL;

The above example is a bit stupid, since one could just use snprintf without my_string_catenation but I can't think of a short better example.
It is common in C libraries to have conventions about who is responsible to free some heap-allocated data. You should document such conventions (at least in comments in the header files declaring them).
Perhaps you might be interested in using Boehm's conservative garbage collector; you'll then use GC_MALLOC  instead of malloc etc... and you won't bother about free ...


text:
Q: Maximum of a convolution I have a function $f:{\mathbb R}\rightarrow {\mathbb R}_+$ which has a unique maximum at $x=0$. $f$ can be symmetric or asymmetric. I am interested on the mollified-f function
$$\tilde{f}(x)=\int_{-\epsilon}^{\epsilon}\varphi(y)f(x-y)dy,\,\,\, \epsilon>0$$
I wonder if there are general results on the Mollifier $\varphi$, such that $\tilde{f}$ also has a unique maximum (not necessarily at $0$).


text:
Q: How to open Safari directly from Widget in SwiftUI? I have a link written in SwiftUI inside Widget View like this:
            Link("Visit Apple",
                  destination: URL(string: "https://www.apple.com")!)
                .font(.caption)
                .foregroundColor(.red)

But now, I need to open this in Safari. Is it possible without opening the host app?

A: No, WidgetKit widgets always open their app. There's no way around it. The best you can do is have your widget open your app (passing the web url) and then your app opens the passes URL in Safari automatically.


text:
Q: How to decode HTML entities I have string variable with HTML entities:
var str = 'Some text & text';
I want to convert (decode) it to original characters:
Some text & text.
JavaScript doesn't have built-in function to achieve wanted result. I can't use jQuery or DOM objects because I need it to work in Google Apps Script.
How can I do that in simple way?

A: You can use built-in Xml Services (reference):
var str = 'Some text & text';
var decode = XmlService.parse('<d>' + str + '</d>');
var strDecoded = decode.getRootElement().getText();

or you can use built-in E4X XML class.
var str = 'Some text & text';
var decode = new XML('<d>' + str + '</d>');
var strDecoded = decode.toString();


text:
Q: How to configure chrome to NOT use windows certificate store By default it appears firefox does not trust the windows certificate store (which is good).
Is it possible to configure chrome to not trust the windows certificate store?
I can't use Firefox because there are some plugins I use that are only available in Chrome. There are some CA certificates on my work computer that I don't trust and I want to know about any SSL MITM attempt. I doubt this would happen, it's more likely the private key for the CA cert might be leaked.
I found this link on managing certificates
https://certsimple.com/blog/control-the-ssl-cas-your-browser-trusts
https://www.chromium.org/Home/chromium-security/root-ca-policy
Google can manually revoke certificates for chrome, however is it possible for users to do the same?


text:
Q: ConcurrentModificationException in MapActivity this is my first question here, so if anything's wrong, do tell.
Now, I have a public class MainMap extends MapActivity which uses a MyLocationListener for the user's location and a HelloItemizedOverlay.
I'm getting certain POI's from an XML-file which I want to add markers (pretty basic Overlays).
User presses a button, AsyncTask starts:
private class GetPOITask extends AsyncTask<String, Void, Void> {

 protected Void doInBackground(String... params) {
    clearMapOverlay();
    if(!isBusyAddingOverlays)
    {
       connect(params[0]);
    }
    return null;
 }

 protected void onPreExecute() {
  clearMapOverlay();
 }
}

Clearing out the MapOverlay (this.mv is a MapView):
public void clearMapOverlay()
 {
  this.mv.getOverlays().remove(placesItemizedOverlay);
  this.mv.postInvalidate();
  this.mv.getOverlays().add(myLoc);
 }

This is the method that my connect-method calls when I have enough information to add a marker:
private void addOverlayToList(int id, GeoPoint point, String title, String description)
{
 //Log.e("Debug", "Adding overlay");
 placesItemizedOverlay.addOverlay(new POIOverlay(id, point, title, description));
 this.mv.getOverlays().add(placesItemizedOverlay);
}

That should be all the relevant code.
The problem is that when I add the POI's and zoom the map (or move it), I get a ConcurrentModificationException.
I've searched through this site, reading similar threads (this one for example) but I can't really find what I'm doing wrong.
Knowing myself, it's probably something obvious.
Thanks in advance,
iarwain

A: This could come from the fact that addOverlayToList() is called from connect() which is called in a different Thread (doInBackground()). Only the thread wich initiated the UI can touch its views.
Move the add overlay calls into onPostExecute() (which you should override) of GetPOITask.


text:
Q: PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\Anaconda3\\pkgs\\vs2015_runtime-14.0.25123-0.tmp Conda newbie here! How can I solve this problem?
C:\Users\mona>conda create --name universe-starter-agent python=3.5
Fetching package metadata .........
Solving package specifications: ..........

Package plan for installation in environment C:\Users\mona\.conda\envs\universe-starter-agent:

The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    pip-9.0.1                  |           py35_1         1.7 MB

The following NEW packages will be INSTALLED:

    pip:            9.0.1-py35_1
    python:         3.5.2-0       (copy)
    setuptools:     27.2.0-py35_1 (copy)
    vs2015_runtime: 14.0.25123-0  (copy)
    wheel:          0.29.0-py35_0 (copy)

Proceed ([y]/n)? y

Fetching packages ...
pip-9.0.1-py35 100% |###############################| Time: 0:00:00   2.94 MB/s
Extracting packages ...
WARNING conda.lock:touch(53): Failed to create lock, do not run conda in parallel processes [errno 13]
An unexpected error has occurred.
Please consider posting the following information to the
conda GitHub issue tracker at:

    https://github.com/conda/conda/issues

Current conda install:

               platform : win-64
          conda version : 4.2.9
       conda is private : False
      conda-env version : 4.2.9
    conda-build version : 2.0.2
         python version : 3.5.2.final.0
       requests version : 2.11.1
       root environment : C:\Program Files\Anaconda3  (read only)
    default environment : C:\Program Files\Anaconda3
       envs directories : C:\Users\mona\.conda\envs
                          C:\Program Files\Anaconda3\envs
          package cache : C:\Users\mona\.conda\envs\.pkgs
                          C:\Program Files\Anaconda3\pkgs
           channel URLs : https://repo.continuum.io/pkgs/free/win-64/
                          https://repo.continuum.io/pkgs/free/noarch/
                          https://repo.continuum.io/pkgs/pro/win-64/
                          https://repo.continuum.io/pkgs/pro/noarch/
                          https://repo.continuum.io/pkgs/msys2/win-64/
                          https://repo.continuum.io/pkgs/msys2/noarch/
            config file : None
           offline mode : False

`$ C:\Program Files\Anaconda3\Scripts\conda-script.py create --name universe-starter-agent python=3.5`

    Traceback (most recent call last):
      File "C:\Program Files\Anaconda3\lib\site-packages\conda\exceptions.py", line 473, in conda_exception_handler
        return_value = func(*args, **kwargs)
      File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main.py", line 144, in _main
        exit_code = args.func(args, p)
      File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main_create.py", line 68, in execute
        install(args, parser, 'create')
      File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\install.py", line 405, in install
        execute_actions(actions, index, verbose=not context.quiet)
      File "C:\Program Files\Anaconda3\lib\site-packages\conda\plan.py", line 643, in execute_actions
        inst.execute_instructions(plan, index, verbose)
      File "C:\Program Files\Anaconda3\lib\site-packages\conda\instructions.py", line 134, in execute_instructions
        cmd(state, arg)
      File "C:\Program Files\Anaconda3\lib\site-packages\conda\instructions.py", line 58, in EXTRACT_CMD
        extract(arg)
      File "C:\Program Files\Anaconda3\lib\site-packages\conda\install.py", line 801, in extract
        t.extractall(path=temp_path)
      File "C:\Program Files\Anaconda3\lib\tarfile.py", line 1996, in extractall
        numeric_owner=numeric_owner)
      File "C:\Program Files\Anaconda3\lib\tarfile.py", line 2038, in extract
        numeric_owner=numeric_owner)
      File "C:\Program Files\Anaconda3\lib\tarfile.py", line 2100, in _extract_member
        os.makedirs(upperdirs)
      File "C:\Program Files\Anaconda3\lib\os.py", line 231, in makedirs
        makedirs(head, mode, exist_ok)
      File "C:\Program Files\Anaconda3\lib\os.py", line 241, in makedirs
        mkdir(name, mode)

I am getting this error

PermissionError: [WinError 5] Access is denied: 'C:\Program
  Files\Anaconda3\pkgs\vs2015_runtime-14.0.25123-0.tmp'

A: I solved it by running the Command Prompt as an administrator. Search for cmd executable, right click on it and select Run as Administrator. You will need an admin user to do this of course.
Hope this helps.

A: METHOD 1:
Try opening your terminal as admin.
METHOD 2:
If METHOD 1 doesn't work, add "--user" at then end of install command.
For example: pip install --ignore-installed --upgrade tensorflow --user
METHOD 3:
If this doesn't work either, the PATH variable might not be set. In that case, path should be printed as warning. Add these path by following steps:
3.1. Right click on my computer->properties
3.2. Advanced system settings
3.3. Under Advanced tab, select environment variables.
3.4. Click new, name the variable name as 'PATH' and value as the directory given in warning.
Hope this help :)

A: Best step is to login as administrator

*

*Install spacy from the scratch from command shell as
conda install -c conda-forge spacy

*Then download 'english' in spacy as
python -m spacy download en

A: I was using commandline in Pycharm I solved it by running Pycharm as Administrator. then running commands in Pycharm command line solved my problem.


text:
Q: String.split() and replaceAll from Java to VB.net I have several lines of code in Java that i need to convert VB.net:
1) s.replaceAll("f\\((.*)\\).*", "$1").trim()
2) s.split("\\,")
3) s.split("\\s+")
4) s.replaceAll("[Tt]hreshold\\s*=(.*)", "$1").trim()

I used Java to VB.net converter and here is the result:
1) s = s.ReplaceAll("f\((.*)\).*", "$1").Trim()
2) s.Split("\,", True)
3) s.Split("\s+", True)
4) s.ReplaceAll("[Tt]hreshold\s*=(.*)", "$1").Trim()

The problem i have is that this code does not work. Lines 2 and 3 have an error "Argument matching parameter 'separator' narrows from 'String' to '1 - Dimensional array of Char'". Lines 1 and 4 say that 'ReplaceAll' is not a member of 'String'.
I am a bit puzzled, how could I do make it work the exact same way as Java code? Help is very much appreciated.

A: In Java, unlike .NET, methods on String allow regular expressions.  In .NET, the Regular Expressions library (located in System.Text.RegularExpressions) would be used instead.  The converter is failing to identify this difference.
In both Java and .NET, strings are immutable, that is, the Java code does not change the value of s, and the lines by itself are no-ops.  You would need to capture the result of each call, for instance as a variable, for later use.
In the first line:
s.replaceAll("f\\((.*)\\).*", "$1").trim()

This can be expressed using the Regex library as
Regex.Replace(s, "f\((.*)\).*", "$1").Trim()

Now take the second line:
s.split("\\,")

This expression simply splits a comma-delimited string into an array.  (The comma does not need to be escaped; this expression is the same as s.split(",")).  The equivalent VB code does not require regular expressions and is simply:
s.split(","c)

(or, assigned to a variable, dim Sa as String() = s.Split(","c).)

The third line:
s.split("\\s+")

This pattern uses a regular expression to use a string delimited on whitespace (any number of characters).  The Regex.Split method returns the same result:
Regex.Split(s, "\s+")

Finally, take:
s.replaceAll("[Tt]hreshold\\s*=(.*)", "$1").trim()

This construct is functionally identical to the first, albeit with a different pattern.  It can be expressed in VB as:
Regex.Replace(s, "[Tt]hreshold\\s*=(.*)", "$1").Trim()


text:
Q: DATA_ALIGN Pragma - Tiva What is the purpose of a pragma Data_Align in TI emb. compiler.
The datasheet explanation:
http://www.ti.com/lit/ug/spnu151j/spnu151j.pdf
"The DATA_ALIGN pragma aligns the symbol in C, or the next symbol declared in C++, to an alignment
boundary. The alignment boundary is the maximum of the symbol's default alignment value or the value of
the constant in bytes. The constant must be a power of 2. The maximum alignment is 32768.
The DATA_ALIGN pragma cannot be used to reduce an object's natural alignment."
Can someone re-explain it in a different method? I really don't understand the purpose of this pre-compile directive.

A: DATA_ALIGN will cause the symbol to be located at an address that satisfies the specified alignment requirement.  For example:
The following code will locate mybyte at an even address.
#pragma DATA_ALIGN(mybyte, 2)
char mybyte;

The following code will locate mybuffer at an address that is evenly divisible by 1024.
#pragma DATA_ALIGN(mybuffer, 1024)
char mybuffer[256];

Most symbols don't require any special alignment beyond the data type's default alignment so you won't need to use DATA_ALIGN often.  But occasionally you'll want a symbol to be located on a special address boundary and that's when DATA_ALIGN is useful.  For example, sometimes buffers used with a DMA controller should be aligned on a special boundary.


text:
Q: Eliminar Archivo o Caperta en C# Estoy tratando de eliminar archivo o una capeta completa a traves de C#, pero me sale la siguiente excepción.

Acceso denegado a la ruta de acceso '03.png'.

Mi código es el siguiente:
String tempFolder = @"C:\AdjuntosChat\";
if (Directory.Exists(tempFolder))
{
    File.Delete(tempFolder);
    Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(tempFolder, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
    foreach (var item in Directory.GetFiles(tempFolder, "*.*"))
    {
        File.Delete(item);
    }
}

A: Intenta añadir esta línea justo antes de eliminar el archivo:
File.SetAttributes(item, FileAttributes.Normal);

De manera que, según tu código, quede así:
foreach (var item in Directory.GetFiles(tempFolder, "*.*"))
{
    File.SetAttributes(item, FileAttributes.Normal);
    File.Delete(item);
}

A: Principalmente se debe a dos posibles causas:
1) Falta de permisos suficientes para eliminar el archivo
Solución:
Dar permisos sobre el(los) archivo(s) para el usuario que ejecuta tu aplicación, normalmente el permiso de escritura te permite borrar, sin embargo si usas los permisos extendidos de Windows existe un permiso Eliminar.
Definir, ver, cambiar o quitar permisos de archivos y carpetas
Un camino fácil (no el mas recomendado) es otorgar permisos de Control Total sobre toda la carpeta vía código sería algo así:
DirectorySecurity sec = Directory.GetAccessControl(path);
// Using this instead of the "Everyone" string means we work on non-English systems.
SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
Directory.SetAccessControl(path, sec);

fuente: https://stackoverflow.com/questions/5298905/add-everyone-privilege-to-folder-using-c-net
2) El archivo se encuentra en uso por otro proceso:
Solución:
Asegúrate que no sea tu mismo programa quien tiene "agarrado" el archivo en alguna otra rutina: usando variables por método, no globales, ni por procedimientos, cerrar streams de acceso a archivos, etc.
En caso de no ser así puedes ver que proceso tiene "agarrado" el archivo con Process Explorer de Sysinternals, siguiendo los pasos de esta página:
Como borrar, mover o renombrar archivos bloqueados por Windows
Si bien Process Explorer te permite liberar el archivo, te recomiendo enfocarte en encontrar el por qué se encuentra bloqueado para que el bloqueo no se repita ya liberada tu aplicación. El antivirus puede ser una causa.


text:
Q: How can a strong water current be cold This is a layman question.
If heat is the motion of atoms, how can a fast moving water current be cold?

A: The  motion of molecules that is responsible for heat content in water is random motion; that is  there are molecules moving in all directions. The directed motion that you are considering ( all molecules moving in the same direction)  from the flowing water does possess kinetic energy, but it is not heat energy.
However, if the water flow  encountered some obstacle that impeded the flow and randomized the motion of the molecules, some heating would occur. In that case some of the kinetic energy of the flow would be converted to heat energy ( internal energy) of the water.
It may be worth noting though that the average magnitude of the random velocities of the individual water molecules is quite high (probably on the order of 500-600 m/sec for room temp water ) compared to the likely velocity of any "fast moving water current", so the heat energy or internal energy would be large compared to the kinetic energy of the water current as well. Thus, not much heating would be expected from  converting the flow to randomized motion.

A: Its too slow. Thermal motion of molecules is about km per second.

A: The speeds of a water current aren't high enough to make any real difference in kinetic energy.
The reason for water currents are that different water temperatures have different densities and so a temperature difference drives the motion of the water. So major water currents often flow between regions of different temperatures. Eg the Alaskan current brings cold water down the Californian coast.
Small water currents, like a hose pipe, feel cold compared to standing water on your skin for the same reason an air flow does. You skin warms up the stationary water immediately in contact with it - then as the water approaches the temperature of your skin the flow of heat reduces and so there is less cooling effect and you don't feel cold. With flowing water you are constantly warming a new bit of cold water and this constant heat flow from your skin makes you feel cold


text:
Q: How can I avoid / combat / eliminate boarding parties? UPDATE 3/5/19: Apparently my troubles were common enough that a recent patch provided some much needed clarity and relief (somewhat) from boarding parties.

I am new to Genesis Alpha One but I've already completed a few "longer" games (10+ crew, preparing for Genesis, never completed). Unfortunately, every run ends the same way, with a boarding party of either Framen or Mechanics ruining everything.
Apologies if I'm missing something simple here, the game is also pretty new so I am having trouble finding even basic info about mid-to-end-game mechanics.
Questions:

*

*Can you avoid being boarded?

*When boarded, is there a way to "end" the encounter?

*Is there a way to more efficiently track/fight a boarding party (as a captain) than just running around? I don't see any way to detect intruders via map or modules.

*

*E.g. hearing the computer say "Lifeform detected" every 5 seconds doesn't  help, it just gives me anxiety, and "Corridor Damaged" doesn't narrow it down when I have 75+ corridors.

Context:
Just to be clear, I'm talking about the actual boarding parties, not when a few enemies appear via the Tractor Beam process.
Enemies just start appearing on my ship after a jump, and I've fought my way through 100+ a few times, jumping away from the system where I encountered them while I'm fighting. After a long time (15/20 minutes?) they seem to trickle out and stop boarding me, but the crew loss and ship damage are usually massive. I often lose all my crew, or just keep cloning and making turrets until I am out of resources (and then give up). If I survive long enough for the enemies to stop appearing all together, they inevitably come back after a few jumps.
Am I missing necessary modules? Using the wrong strategy? Or do I just need to not be so bad at this game?

A: You can track enemy ship locations using the map on the bridge's terminal. I've found that if you keep at least one map square away from the enemy vessels, they don't seem to board. Jusy be careful since their ships also move on the map, so getting within a square or two of an enemy ship risks letting them jump onto your square quickly and easily. It's a good idea to check the map regularly if you are in unsafe territory since an enemy ship that was not in your scanner range when you jumped your ship into a square can suddenly appear while you are gathering resources or otherwise occupied. You will be able to see roughly what regions have enemy ships once you unlock more of the map. The ememy ship icon remains in the last square it was on before your ship moves out of scanner range, so you can still keep a rough idea of where enemy ships are likely to be even when you move to a different part of the map. I'm not totally sure, but it also seems like any extended period in which you are idle in the game increases the chance of a random enemy attack.  On several occasions, I've left the game for some reason without pausing it only to return and find my ship was boarded and destroyed, even if there wasn't an enemy in range when I stepped away.
I'm not sure if it actually helps, but the only times I've survived an attack so far (at about 24-25 crew members into the game) was when I alternated hunting down pirates throughout my ship with returning to the bridge to jump away from the attacking pirate ship. It appeared like the pirates could not teleport new atracker to my ship once i moved the ship put of range.  The pirate ship will chase yours, but it seems to move less frequently than yours can, so you can easily escape even without the hyperdrive module. In terms of preventing the attack, use your map to avoid nearby enemy ships. In terms of ending the attack, set up ship defenses, try jumping away a few squares during the attack, fight, and hope you get lucky!  You can visually see attacker locations on your ship by switching to building mode. They show up as red dots just like your own crewmembers show up as geeen dots.
Unfortunately, pirates seem to be able to appear anywhere on your ship during an attack, so you really do have to manually search the whole ship. This also limits the utility of energy fields and turrets unless you place them all over your ship (which I'd recommend!).
Later in the game, you can find ship modules that help with attacks, like the quarantine module. These can be built around your ship and actively damage enemies who have boarded during an attack or stowed away during resource gathering. I wish there was a way to board and attack enemy ships though since there are regions on the map thay are virtually inaccessible  because of one or more enemy ships that hang out in that region....would love to blow them out of the sky at some point, so I can explore and harvest more difficult regions in relative peace!


text:
Q: Displaying Specific Events in Specific Month? I am using CalenderView to Display the Date and Below CalenderView I have Used ListView to Display the date(day) with Events.I am able to parse all the Events with Day but what i want is that Display Specific Day and Events under Specific Month.How can this be achieved?
CalenderFragment
public class CalenderFragment extends Fragment {
    CalendarView calendar;
    String Navigation_URL = "http://192.168.100.5:84/api/academics/getEvents";
    String access_token;
    ListView listView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.calender, container, false);
        getActivity().setTitle("");
        setHasOptionsMenu(true);

        calendar = (CalendarView) view.findViewById(R.id.calendar);
        calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {

            @Override
            public void onSelectedDayChange(CalendarView view,
                                            int year, int month, int dayOfMonth) {
                Toast.makeText(getContext(),
                        dayOfMonth + "/" + month + "/" + year, Toast.LENGTH_LONG).show();
            }
        });

        listView = (ListView) view.findViewById(R.id.calenderlist);
        SessionManagement session = new SessionManagement(getContext());
        session.checkLogin();
        access_token = session.getAccesstToken();

        makeJsonObjectRequest();

        return view;
    }

    private void makeJsonObjectRequest() {

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        String URL = Navigation_URL;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            ArrayList<CalenderPojoStudent> student_list_calender = new ArrayList<>();

                            JSONArray jArray = new JSONArray(response);
                            for (int i = 0; i < jArray.length(); i++) {
                                JSONObject jsonObject = jArray.getJSONObject(i);
                                String StartAt =  jsonObject.getString("StartAt").substring(6,10);
                                String Title =  jsonObject.getString("Title");
                                student_list_calender.add(new CalenderPojoStudent(StartAt, Title));
                            }
                            CalenderAdapter calenderAdapter = new CalenderAdapter(getActivity(), student_list_calender);
                            listView.setAdapter(calenderAdapter);

                        } catch (JSONException e) {
                            Toast.makeText(getContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), error.toString(), Toast.LENGTH_LONG).show();
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "Bearer " + access_token);
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                return headers;
            }
/*
            @Override
            protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();

                map.put("id", master_id);
                map.put("accessID", accessID);
                map.put("currentUser", master_id);
                return map;

            } */
        };

        requestQueue.add(stringRequest);

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.dashboard, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_settings:
                // do s.th.
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}

CalenderAdapter
public class CalenderAdapter extends BaseAdapter {

    Context mContext;

    ArrayList<CalenderPojoStudent> student_class_calender = null;
    String TAG = "HomeTab_adapter";

    public CalenderAdapter(Context mContext, ArrayList<CalenderPojoStudent> student_class_calender) {

        this.mContext = mContext;
        this.student_class_calender = student_class_calender;
    }

    @Override
    public int getCount() {
        //   System.out.println(student_class_calender.size());
        return student_class_calender.size();

    }

    @Override
    public Object getItem(int position) {
        return student_class_calender.get(position);
        // return arg0;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int postion, View convertView, ViewGroup parent) {
        // final ClassScheduleStudentAdapter.Holder viewHolder;
        final Holder viewHolder;

        if (convertView == null) {
            // inflate the layout
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            convertView = inflater.inflate(R.layout.calender_student_listitems, parent, false);

            // well set up the ViewHolder
            //  viewHolder = new ClassScheduleStudentAdapter.Holder();
            viewHolder = new Holder();
            viewHolder.student_calender_date = (TextView) convertView.findViewById(R.id.student_calender_date);
            viewHolder.student_calender_events = (TextView) convertView.findViewById(R.id.student_calender_events);

            convertView.setTag(viewHolder);

        } else {
            // we've just avoided calling findViewById() on resource everytime
            // just use the viewHolder
            //  viewHolder = (ClassScheduleStudentAdapter.Holder) convertView.getTag();
            viewHolder = (CalenderAdapter.Holder) convertView.getTag();
        }
        // Log.d(TAG, "@@ postion:" + postion + " getTeacherName" + student_class_schedule.get(postion).getTeacherName());
        viewHolder.student_calender_date.setText(student_class_calender.get(postion).getDate());
        viewHolder.student_calender_events.setText(student_class_calender.get(postion).getEvents());

        // convertView.setTag(viewHolder);
        return convertView;
    }

    class Holder {

        TextView student_calender_date;
        TextView student_calender_events;

    }

}

CalenderPojoStudent
public class CalenderPojoStudent {
    String Date;
    String Events;

    public CalenderPojoStudent(String date, String events) {
        Date = date;
        Events = events;
    }

    public String getDate() {
        return Date;
    }

    public String getEvents() {
        return Events;
    }

    public void setEvents(String events) {
        Events = events;
    }

    public void setDate(String date) {
        Date = date;

    }
}

calender_student_listitems
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="center_horizontal"
    android:background="#DAE2E6"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/student_calender_date"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:background="#fff"
        android:gravity="center_horizontal"
        android:paddingTop="7dp"
        android:text="04"
        android:textColor="#008b8b"
        android:textSize="20dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/student_calender_events"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="8dp"
        android:text="Sports Day"
        android:textSize="17dp"
        android:textStyle="bold" />

</LinearLayout>

calender
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#2E353D"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_gravity="center_horizontal"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="30dp"
                android:layout_height="match_parent"
                android:padding="3dp"
                android:src="@mipmap/calander" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="8dp"
                android:text="Calendar"
                android:textColor="#fff"
                android:textSize="17dp"
                android:textStyle="bold" />

        </LinearLayout>
    </LinearLayout>

    <CalendarView
        android:id="@+id/calendar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <ListView
        android:id="@+id/calenderlist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

JSON
[
  {
    "EventID": 2,
    "Title": "Event1",
    "Description": "gdfg",
    "StartAt": "2017-03-01T00:00:00",
    "EndAt": "2017-03-02T05:45:00",
    "IsFullDay": true,
    "IsHoliday": false
  },
  {
    "EventID": 4,
    "Title": "f",
    "Description": "sdf",
    "StartAt": "2017-03-02T09:52:00",
    "EndAt": "2017-03-02T10:52:00",
    "IsFullDay": false,
    "IsHoliday": false
  },
  {
    "EventID": 3,
    "Title": "Event3",
    "Description": "dsf",
    "StartAt": "2017-03-03T00:00:00",
    "EndAt": "2017-03-04T05:45:00",
    "IsFullDay": true,
    "IsHoliday": true
  },
  {
    "EventID": 10,
    "Title": "xcgz",
    "Description": "zxcv",
    "StartAt": "2017-04-02T00:00:00",
    "EndAt": "2017-04-03T00:00:00",
    "IsFullDay": true,
    "IsHoliday": false
  },
  {
    "EventID": 9,
    "Title": "xzcvzx",
    "Description": "vxzvc",
    "StartAt": "2017-04-04T00:00:00",
    "EndAt": "2017-04-05T00:00:00",
    "IsFullDay": true,
    "IsHoliday": false
  },
  {
    "EventID": 14,
    "Title": "afagag",
    "Description": "",
    "StartAt": "2017-04-04T00:00:00",
    "EndAt": "2017-04-05T00:00:00",
    "IsFullDay": true,
    "IsHoliday": true
  }
]

How do display the events of specific month on the listView on the basais of Calender Month?

A: You can use this library it has som e for showing events in calendar.DOts will be shown under the dates. MaterialCalendarView
Search for decorator you can use wth dates in that library.
materialCalendarView.setDateTextAppearance()
materialCalendarView.addDecorator(new OpenSansDecorator(getActivity()));
      materialCalendarView.setHeaderTextAppearance(R.style.TextAppearance_ProfileCalenderHeader);

This can be used to show dots in calendar and u can implement a logic to show recylerview based on date click in calendar.
Refer this for events decoration in the lib  :


text:
Q: Route::delete in Laravel is not catching Request $request with this url
http://localhost:8888/api/v1/apartments/delete , I'm trying to delete a determinate apartment without passing the id through the URL. I'm sending data with POSTMAN but I can't catch it with Request or Input classes.
Routes.php
Route::delete('/api/v1/apartments/delete', 'ApartmentApiController@destroy');

ApartmentApiController
public function destroy(Request $request)
{
  dd($request->all());
}

In methods like UPDATE Request is working but not here in DELETE. Why is this? I'm a little bit curious and I have not found it.
It's a good practice to delete passing the item id in the URL like this? Should I do like this?
http://localhost:8888/api/v1/apartments/delete/13

A: Since you are passing the id in the route:
Route::delete('apartments/delete/{id}', 'ApartmentApiController@destroy');

You need to inject that in your method along with the Request object.
public function destroy($id, Request $request)
{
  dd($id);
}

A: Just ran into this same problem. I found that I had to change the header from Accept: application/json to content-type: application/json...


text:
Q: self-admiration or self-appreciation If X believes that whatever abilities he has he gained all on his own. X merely ignores the factor that many of the abilities are by birth too and you have your abilities given to you by God. X thinks all his abilities are by his own efforts. X is unmindful of the fact that Almighty power may ever take any of his abilities back anytime. Which word is best here:
self-admiration
self-appreciation


text:
Q: Is missing cockpit-docker no longer in the 20.04 repository? I installed Ubuntu server 20.04 into a vm, to see how if I want upgrade my 18.04. I use cockpit for ease of use on my 18.04. Anyways the cockpit-docker deb is missing from the repository. Why is this? Was this an over site or is their some other reason for it not being part of 20.04?

A: Though they do not build cockpit-docker for Ubuntu 20.04 or later anymore, you can still install older versions according to this.
I downloaded cockpit-docker_215-1~ubuntu19.10.1_all.deb and installed manually.
It seems to be working now.

A: If you really want to make a difference; I forked the thing and pulled it apart as a plugin.
You can find it on Github

A: cockpit-docker is replaced by cockpit-podman
If sudo apt install cockpit-podman fails then [ Upvote the Official Bug ]
Workaround:
wget https://launchpad.net/ubuntu/+source/cockpit/215-1~ubuntu19.10.1/+build/18889196/+files/cockpit-docker_215-1~ubuntu19.10.1_all.deb
sudo gdebi cockpit-docker_215-1\~ubuntu19.10.1_all.deb
rm cockpit-docker_215-1\~ubuntu19.10.1_all.deb

Working for me:


text:
Q: Adding other Android widgets into your app I'm working on a program for android very similar to a car/media dock program but not quite. It will have shortcuts to launch apps, but I also want to add widgets to it.  I don't want this app to be a widget that the user can add to their homescreen.  I want the user to choose a widget they have installed and have that widget built into my dock program that fully functions....and that's where I hit a road bump that I can't figure out how to accomplish.
I tried looking through the launcher2 code but that's way more complex then what I need and I can't find any documentation for this function anywhere.
Thanks in advance for your help.

A: Have you seen this AppWidgetHost tutorial?


text:
Q: Building a Grid out of FlowBox GTK What I'm aiming to do is build a 3x2 grid from within Python Gtk using the FlowBox widget.
The screenshot shows I'm doing the 3x2 perfectly. The problem is that I wanted the buttons to look like smaller squares and not fill up the whole screen. I realize I might have to do this with the grid layout, but I'm just hoping that this wouldve been accomplishable using FlowBox for simplicity. Any ideas?

from gi.repository import Gtk

class MyWindow(Gtk.Window):
    def __init__(self):
        super().__init__(title="Hello World")

        self.box1 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.add(self.box1)
        self.set_default_size(800, 500);

        self.btnTL= Gtk.Button(label="back")
        self.heading= Gtk.Label(label="Home")
        self.btnTR= Gtk.Button(label="home")
        self.boxT = Gtk.Box()
        self.boxT.pack_start(self.btnTL, False, False, 0)
        self.boxT.pack_start(self.heading,True, True, 0)
        self.boxT.pack_start(self.btnTR, False, False, 0)
        self.box1.add(self.boxT)

        self.cFlow = Gtk.FlowBox()
        self.cFlow.set_valign(Gtk.Align.FILL)
        self.cFlow.set_max_children_per_line(3)
        self.cFlow.set_hadjustment(Gtk.Adjustment(100, 100, 10, 100, 100, 100))
        self.buttonAdd(self.cFlow)
        self.buttonAdd(self.cFlow)
        self.buttonAdd(self.cFlow)
        self.buttonAdd(self.cFlow)
        self.buttonAdd(self.cFlow)
        self.buttonAdd(self.cFlow)
        self.box1.pack_start(self.cFlow,True,True,0)

        self.button1 = Gtk.Button(label="test")
        self.button1.connect("clicked", self.on_button1_clicked)
        #self.box1.pack_start(self.button1, True, True, 0)

        self.btnBL = Gtk.Button(label="L")
        self.bread = Gtk.Label(label="")
        self.btnBR = Gtk.Button(label="R")
        self.boxB = Gtk.Box()
        self.boxB.pack_start(self.btnBL, False, False, 0)
        self.boxB.pack_start(self.bread, True, True, 0)
        self.boxB.pack_start(self.btnBR, False, False, 0)
        self.box1.add(self.boxB)

UPDATE:
I made some tweaks but now I get this issue where my window height expands from what I originally set it and I tried everything to eliminate the Xtra space. the window also expands when I add like an 8 character (or more) label to the button.
    def buttonAdd(self,widget):

    self.button2 = Gtk.Button("tffkjdsljdsflkds\nt")
    #self.button2.set_halign(Gtk.Align.CENTER)
    #self.button2.set_valign(Gtk.Align.CENTER)
    #self.button2.set_vexpand(True)
    #self.button2.set_hexpand(True)

    #self.button2.set_property("height-request",100)
    #self.button2.set_property("width-request",150)
    self.button2.connect("clicked",self.clickedTest)
    widget.add(self.button2)

A: My answer will be in C++, but I think it will be easily translatable to Python.
First of all, the same problem would arise when using Gtk.Grid instead of Gtk.FowBox. The way containers work in Gtk is that you add widgets to your layout and you then specify their sizes using expanding flags and margins. In the following example, I resized the first test button in the Gtk.FlowBox. Look at the MakeButtonsSmaller() method, this is where it happens:
#include <iostream>
#include <gtkmm.h>

// Some contants, just for better readability
constexpr bool EXPAND     = true;
constexpr bool NO_EXPAND  = false;
constexpr bool FILL       = true;
constexpr bool NO_FILL    = false;
constexpr bool NO_PADDING = 0;

class MainWindow : public Gtk::ApplicationWindow
{

public:

    MainWindow();

private:

    void MakeButtonsSmaller();

    Gtk::Box m_box1;

    // Header widgets:
    Gtk::Box m_boxT;
    Gtk::Button m_btnTL{"back"};
    Gtk::Button m_heading{"Home"};
    Gtk::Button m_btnTR{"home"};

    // Main space widgets:
    Gtk::FlowBox m_cFlow;
    Gtk::Button m_button1{"test"};
    Gtk::Button m_button2{"test"};
    Gtk::Button m_button3{"test"};
    Gtk::Button m_button4{"test"};
    Gtk::Button m_button5{"test"};
    Gtk::Button m_button6{"test"};

    // Footer widgets:
    Gtk::Box m_boxB;
    Gtk::Button m_btnBL{"L"};
    Gtk::Button m_bread{""};
    Gtk::Button m_btnBR{"R"};

};

void MainWindow::MakeButtonsSmaller()
{
    m_button1.set_halign(Gtk::Align::ALIGN_CENTER);
    m_button1.set_vexpand(true);
    m_button1.set_margin_bottom(170);
    m_button1.set_margin_top(170);
}

MainWindow::MainWindow()
: m_box1{Gtk::Orientation::ORIENTATION_VERTICAL}
{
    MakeButtonsSmaller();

    set_title("Hello World");
    set_default_size(800, 500);

    add(m_box1);

    // Header:
    m_boxT.pack_start(m_btnTL,   NO_EXPAND, NO_FILL, NO_PADDING);
    m_boxT.pack_start(m_heading, EXPAND,    FILL,    NO_PADDING);
    m_boxT.pack_start(m_btnTR,   NO_EXPAND, NO_FILL, NO_PADDING);
    m_box1.add(m_boxT);

    // Main space:
    m_cFlow.set_valign(Gtk::Align::ALIGN_FILL);
    m_cFlow.set_max_children_per_line(3);
    m_cFlow.set_hadjustment(Gtk::Adjustment::create(100, 100, 10, 100, 100, 100));

    m_cFlow.add(m_button1);
    m_cFlow.add(m_button2);
    m_cFlow.add(m_button3);
    m_cFlow.add(m_button4);
    m_cFlow.add(m_button5);
    m_cFlow.add(m_button6);
    m_box1.pack_start(m_cFlow, EXPAND, FILL, NO_PADDING);

    // Footer:
    m_boxB.pack_start(m_btnBL, NO_EXPAND, NO_FILL, NO_PADDING);
    m_boxB.pack_start(m_bread, EXPAND,    FILL,    NO_PADDING);
    m_boxB.pack_start(m_btnBR, NO_EXPAND, NO_FILL, NO_PADDING);
    m_box1.add(m_boxB);
}

int main(int argc, char *argv[])
{
    std::cout << "Gtkmm version : " << gtk_get_major_version() << "."
                                    << gtk_get_minor_version() << "."
                                    << gtk_get_micro_version() << std::endl;

    auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");

    MainWindow window;
    window.show_all();

    return app->run(window);
}

Which yields:

I leave it to you to tweak the other buttons, but the basic idea is there.


text:
Q: Call js function when button is pressed I want to call a js function when a button is pressed. After reading this and this, I did something like this in the jsFiddle. However, when I press the button, nothing happens! What am I missing?
js code:
jQuery(document).ready(function() {
    $('#ref1').keypress(function() {
        alert('Handler for .keypress() called.');
    });
});

A: You can't have keypress event on  element, use click
Demo

jQuery(document).ready(function() {
  $('#ref1').click(function() {
    alert('Handler for .click() called.');
  });
});

Refresh page (helpful in case of mistake)


text:
Q: Mediawiki: How to prevent images in wikitext from beeing rendered in html? To offer a mobile version of an existing mediawiki installation I was looking for a practicable way to remove all images from output. The most preferred solution would be one where the generated html would no longer contain the image-tags.
As I was not able to figure out a clean solution I moved the images to a different server and disabled $wgForeignFileRepos and $wgAllowExternalImages in this version.
Unfortunately - while the images are not shown - there appears a placeholder box containing the image's name and a (now not functioning) link to it.
Do you know about a way to get rid of the images without using css/js or a way to bring my approach to completion?

A: You could use this javascript mobile browswer detection and then on detection it runs the following javascript code.
var imagesremove = document.getElementsByTag('img')
imagesremove.parentNode.removeChild(imagesremove);

A: There are probably better solutions, but you can override the ImageBeforeProduceHTML hook to make images generate empty output:
$wgHooks['ImageBeforeProduceHTML'][] = function( &$skin, &$title, &$file, &$frameParams, &$handlerParams, &$time, &$res ) {
    $res = '';
    return false;
}

...or something more fancy, such as returning a link to the image instead of an actual <img> tag.
Depending on your wiki's caching settings, you might have to purge the page cache afterwards, e.g. by setting $wgCacheEpoch.


text:
Q: How to check if mobile data is actually active or wifi is actually connected to any hot spot? I am trying to check if there is an internet connectivity or if the device is actually connected to wifi.
Note: I am not trying to see if there is internet connectivity or if just the wifi is connected. I want to check if the device is actually receiving and sending the packets.
This code snippet actually checks if there is a mobile data connectivity or if the wifi is enabled but it doesn't say if the connection is actually established.
public boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            Toast.makeText(context, "No Network", Toast.LENGTH_LONG).show();
            return false;
        } else
            return true;

OR
    boolean isConnected = ni != null && ni.isConnectedOrConnecting();

    if(isConnected){

        return true;

    }
    else{
        Toast.makeText(context, "No Network", Toast.LENGTH_LONG).show();
        return false;
    }
}

or
public boolean haveNetworkConnection(Context context) {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }

All the above code snippets only checks if the wifi or data is enabled. It doesn't show if the connection is established. It will always return true if the wifi or data is enabled.
Again, my goal is to check is to check if the connection is established.
Any help will be really helpful.. Thank's in advance..:)
This question has been answered. Thanks again.

A: Thanks for the comments and answer guys but I think this solution is working for me. This is actually trying to connect to internet and checking the status. Not sure if this is the right way to do it.
public Boolean isOnline() {
        try {
            Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
            int returnVal = p1.waitFor();
            boolean reachable = (returnVal==0);
            if(reachable){
                System.out.println("Internet access");
                return reachable;
            }
            else{
                System.out.println("No Internet access");
            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return false;
    }

Hope this helps other viewers.

A: You have to ping a server on the internet(ie. google) to see if you're actually connected.


text:
Q: QML Rectangle customisation If I have two Rectangles side-by-side, and I want to position an object (text or numbers) at specific points within each rectangle, can I use the pixels taken from the size as a positioner?
In this example the Rectangles are width:100 height:100,
What I would like to do is place my first object at width: 2 and height: 2, and another object at width: 23, height: 23
My Question Is
Can I use the pixel size of a Rectangle to position children of it?

A: If I understand your question fully, you want to set one or more items(text/numbers ect) at certain points within a rectangle?
Personally I am unsure if this is possible?!, see the link for all members of QML Item/Rectangle;
Item QML Type
Without knowing your use-case, if I wanted to add multiple items within a rectangle, I would use either a Grid,Row or Column for adding multiple objects to a rectangle, I have linked below for each of them. Please remember these are just positioners (as with eyllanesc comments) if there is specific place you want them too be, use a Repeater with a model (also linked) and for what use? Let me know if that's the case and I might be able to help a little more!

*

*QML Grid

*QML Row

*QML Column

*QML Repeater
Thanks!


text:
Q: multiple event targets on same parent element not working I have been dealing with this problem for quite some time. It's been a great way to learn Javascript, but I'm just done and need help before I end up in prison for something. I need the inline formset's delete checkbox checked before removing the parent element (form). I am using Django's inline formsets and am currently refusing to use jquery to handle this because I want to learn good ol' vanilla Javascript. The onclick will do one or the other. Won't do both in the same click of the button. I have tried all things to handle bubbling and capturing to the best of my ability. Okay I'll be quiet now.
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" type="text/css" href="{% static 'css/availability_update_new.css' %}">
</head>
<body>
<form id="all-add-form" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <legend class="bottom mb-4">Profiles Info</legend>
    {{ sun_bool.sunday|as_crispy_field }}
    {{ sunday_formset.management_form }}
    {% for sun_form in sunday_formset %}
        {% for hidden in sun_form.hidden_fields %}
            {{ hidden }}
        {% endfor %}
        <div class="sun_time_slot_form">
            {{ sun_form }}
            <button class="delete-sun-form" type="button" id="delete-sun-btn" onclick="one();"> Delete This Sunday
                Timeslot
            </button>
        </div>
    {% endfor %}

    <button id="add-sun-form" type="button" class="button">Add Other Sunday Times</button>

    <input type="submit" name="submit" value="Submit" class="btn btn-primary"/>
</form>

<script type="text/javascript" src="{% static 'js/add_timeslot.js' %}"></script>

</body>
</html>
{% endblock content %}

const sunForm = document.getElementsByClassName('sun_time_slot_form');
const mainForm = document.querySelector('#all-add-form');
const addSunBtn = document.querySelector("#add-sun-form");
const submitFormBtn = document.querySelector('[type="submit"]');
const totalForms = document.querySelector("#id_id_sunday_formset-TOTAL_FORMS");

let formCount = sunForm.length - 1;

addSunBtn.addEventListener('click', function (e) {
    e.preventDefault();

    const newSunForm = sunForm[0].cloneNode(true);
    const formRegex = RegExp(`id_sunday_formset-(\\d){1}-`, 'g');

    formCount++;

    newSunForm.innerHTML = newSunForm.innerHTML.replace(formRegex,
    `id_sunday_formset-${formCount}-`);
    mainForm.insertBefore(newSunForm, submitFormBtn);
    totalForms.setAttribute('value', `${formCount + 1}`);
});

function updateSunForm() {
    let count = 0;
    for (let sun_form of sunForm) {
        const sunFormRegex = RegExp(`id_sunday_formset-(\\d){1}-`, 'g');
        sun_form.innerHTML = sun_form.innerHTML.replace(sunFormRegex,
            `id_sunday_formset-${count++}-`)
    }
}

mainForm.addEventListener('click', (ee) => {
    if (ee.target.classList.contains('delete-sun-form')) {
        ee.preventDefault();
        ee.target.value;
        ee.target.parentElement.querySelector('input[id$="-DELETE"]' +
            '[type="checkbox"]').checked = true;
        ee.target.value;
        ee.target.parentElement.remove();
        formCount--;
        updateSunForm();
        totalForms.setAttribute('value', `${formCount + 1}`);
    }
});