text:
Q: How to display a specific content from a post in a Bootstrap 4 Modal, Wordpress I have searched for this answer, I tried a lot of things but it is still not working...
Here below I'll give you the code. Please, I will be so grateful to the person that will help me. Thank You.

I will try to explain to you what I did. Basically, I linked the Post ID to the modal window to display the specific post content on a specific modal window. Seems like it might work, but nope. I realized that the modal id link does not change while the Link it is changing... I don't what to do...
Here Below I Will Give you a screenshot.
Sorry If I made a mistake explaining you all this..:)
PHP Code:

<?php the_excerpt(); ?>

                            *** <a class="btn btn-primary" id="clickme" data-toggle="modal" data-id="<?php the_ID(); ?>" href="#myModal-<?php the_ID(); ?>">читать полностью>>
                                 ***

<?php the_title(); ?>

                        <?php
                    }

                    wp_reset_postdata(); // сброс

                 ?>

                <button id="opinion-btn" class="main-button opinion-btn btn btn-primary" type="button" data-toggle="collapse" data-target="#collapsed-opinion-leave" aria-expanded="false" aria-controls="collapsed-opinion-leave">Добавить отзыв</button>

Оставьте свой отзыв

                    <?php

                        echo do_shortcode('[contact-form-7 id="144" title="Контактная форма (ОТЗЫВЫ)"]');

                     ?>

        *** <div class="modal fade" id="myModal-<?php the_ID(); ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> ***

<?php the_title(); ?>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  ×
                </button>

                <?php the_content(); ?>

JS code:
    $(document).ready(function(){
        $("#clickme").on
          ("click", function(){
            $("#myModal-" + $(this).attr('data-id')).modal();

          });
      });

Picture:
enter image description here


text:
Q: node.js correct extending of json objects I'm currently using node-ews in a project to access an Exchange Web Server via node.js. Now i ran into a weird problem. To run for example a "CreateItem" request, which can be an E-Mail or Appointment for example, I'm giving the function the arguments as a json similar to this
var args = {
    "attributes" : {
        "SendMeetingInvitations" : "SendToAllAndSaveCopy"
    },
    "SavedItemFolderId": {
        "DistinguishedFolderId": {
            "attributes": {
                "Id": "calendar"
            }
        }
    },
    "Items" : {
        "CalendarItem" : {
            "Subject" : "",
            "Body" : {
                "attributes" : {
                },
                "$value" : ""
            },
            "ReminderIsSet" : "true",
            "ReminderMinutesBeforeStart" : "30",
            "Start" : "",
            "End" : "",
            "IsAllDayEvent" : "false",
            "LegacyFreeBusyStatus" : "Busy",
            "Location" : ""
        }
    }
};

As the REST-API I'm writing will receive Attributes like Subject, Start, End etc. I initially stripped out those out of the JSON and would define them later like
args.Items.CalendarItem.Subject = req.body.Subject;

Oddly this will make the internal validation of node-ews fail and tell me that CalendarItem has an invalid Child Subject. If i leave Subject als an empty string in the initial args and later change it set it to req.body.Subject it works just fine.
My question is this: Is the Object somewhat different if I later add attributes and if yes is there a way to do it right? Because I don't think its the best way to have a bunch of empty Attributes in my Object if they aren't used and define standard values for all of them even if api won't require them to be sent.
Would great if someone knew the answer. Hope i could clarify what the problem is

A: Ok,
so the problem seems to be this. Internally the JSON "object" seems to have an order based on the order the variable is defined. in JavaScript this is no problem. But when the xml is parsed, the tag that was defined last will also be at the end of the xml so if you had
   <someTag>
     <variable2 />
     <variable3 />
   </someTag>

and you add variable1 to your json by someTag.variable1 = x in the end the xml will look like this after beeing parsed by node-ews
   <someTag>
     <variable2 />
     <variable3 />
     <variable1 >x</variable1>
   </someTag>

Now unfortunately the exchange web server seems to be picky about the order of the xml tags. so when you build your json be sure to use the direct order. Changing content of the json later will not affect the order.

redpajama_set_name: RedPajamaStackExchange


text:
Q: looking for a function I am new to SQL and I am trying to create a query that will give me the same result as LEFT OUTER JOIN but between two data bases. For example, in DB1 there are 100 records with the value X in specific column and in DB2 there 80 records. I want a query that will give the 20 missing records.
Thanks.

A: If you mean "between two tables":
select Table1.*
from Table1
left join Table2
on Table1.id = Table2.id
where Table2.id is null

This gives everything in Table2 that does not match
For more visual info on joins, go here
For basic info on SQL, try here

A: DB1 (table_users)
+----+-----------+--------------+
| id | username  |    lastname  |
+----+-----------+--------------+
| 1  | xxxxxx    | mmmmmmm      |
+----+-----------+--------------+
| 2  | bbbbbb    | wwwwwww      |
+----+-----------+--------------+

DB2 (table_users)
+----+-----------+--------------+
| id | username  |    lastname  |
+----+-----------+--------------+
| 1  | xxxxxx    | mmmmmmm      |
+----+-----------+--------------+
| 2  | bbbbbb    |  wwwwwwww    |
+----+-----------+--------------+
| 3  | ccccc     | ppppppppppp  |
+----+-----------+--------------+

SELECT  *
FROM    DB2.table_users
WHERE   phone_number NOT IN (SELECT * FROM DB2.table_users);

I think it servers the same purpose, except that your dealing with tables from different databases.


text:
Q: TextView onClickListener does not recognize the click Basically, I have a layout with an EditTex with multiline input type and a clickable TextView. The problem comes when I click the TextView It seems that setOnClcickListener isn't working properly.
The debugger of the code shows that the listener doesn't recognize the click.
Activity layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">

    <EditText
        android:id="@+id/reviewText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:gravity="start"
        android:inputType="textPassword"
        android:textAlignment="textStart"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.069" />

    <TextView
        android:id="@+id/submitReviewTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:clickable="true"
        android:focusable="true"
        android:text="Enviar Crítica"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.974"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/reviewText"
        app:layout_constraintVertical_bias="0.575" />

</android.support.constraint.ConstraintLayout>

And the Activity code:
package com.example.myapplication

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private var reviewConditionsOk = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        submitReviewTextView.setOnClickListener {
            checkMandatoryReviewConditions()
            if (!reviewText.text.isEmpty() && !reviewConditionsOk) {
                Log.d("Test", "Button Clicked")
                Toast.makeText(applicationContext,
                    "La crítica no a de estar vacía y tiene que tener un mínimo de 5 líneas.",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        finish()
    }

    private fun checkMandatoryReviewConditions() {
        reviewText.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                reviewConditionsOk = reviewText.text.toString().trim().length < 5
            }
        }
    }
}

A: I tested the code along with the code myself and found no problem with the click listener. The event is triggered correctly. You need to modify the following condition so that it shows the Toast that you want to get.
if (!reviewText.text.isEmpty() && !reviewConditionsOk) // Fix this


text:
Q: What are the ways to connect Azure Cloud Services(Worker Roles in specific) to an on-premise database(SQL Server)? Can you also provide some kind of comparison? I am looking to transfer lots of data.
Some ways that I can come up with:-
1) WCF service covering the on-premise DB and the cloud service connects to this using service bus
2) a point to site VNET connection b/w DB and VM on which the cloud service resides
3) On-prem DB ---(Hybrid Connection/BizService)---> AzureWebApp ----(Storage Queues)---> Azure Cloud Service   (as BizService Hybrid Connection is not available for cloud services).

A: You can do this with the Azure App Service, MSDN will help you:
web-sites-hybrid-connection-connect-on-premises-sql-server
app-service-changes-existing-services


text:
Q: Does the path graph have least algebraic connectivity among simple, undirected, connected graphs? Let $G = (V, E)$ be a simple, undirected, unweighted graph on $n$ nodes (all uses of the word "graph" in this question refer only to graphs with these properties). Define its Laplacian as
\begin{equation}
L(G) = D(G) - A(G),
\end{equation}
where $D(G)$ and $A(G)$ are, respectively, the degree and adjacency matrices associated with $G$.
The second-smallest eigenvalue of $L(G)$, often denoted $\lambda_2(L(G))$ or simply $\lambda_2$ when $G$ is understood, was termed its algebraic connectivity by Fiedler in seminal work $[1]$ which showed that a graph $G$  is connected if and only if $\lambda_2 > 0$.
For any fixed $n \in \mathbb{N}$, there are a finite number of graphs on $n$ nodes (without worrying about exactly how many distinct possible graphs there are, this number is clearly bounded above by $2^n$), and there are likewise a finite number of connected graphs on $n$ nodes. My question is the following.

Which simple, undirected, unweighted, connected graph on $n$ nodes minimizes the algebraic connectivity among all such graphs on $n$ nodes?

My suspicion is that the answer to this question is the path graph, thought I haven't been able to confirm this. It is known (e.g., from $[1]$) that the path graph on $n$ nodes has algebraic connectivity $\lambda_2 = 2\left(1 - \cos\frac{\pi}{n}\right)$, and I've done quite a few numerical experiments in generating graphs and trying to find one with a smaller value of $\lambda_2$, though I have not yet found such a graph for any value of $n$.
I've looked in Godsil and Royle, and while there was obviously plenty on connectivity of graphs, I couldn't seem to find the answer to this question. I've also done some Googling with search terms like "least connected graph" and "minimum algebraic connectivity of graphs," but that didn't turn anything up either.
[1] M. Fiedler, "Algebraic Connectivity of Graphs," Czechoslovak Mathematical Journal, 1973, vol. 23, no. 2, pp. 298-305.

A: The fact that the path graph $P_n$ minimizes algebraic connectivity among all connected graphs with $n$ vertices follows from proposition 4.3 in Fiedler's paper.
This proposition states (among other things) that the algebraic connectivity of a graph $G$ is at least $2 e(G) (1-\cos(\pi/n))$, where $e(G)$ is the edge-connectivity of $G$, i.e. the minimum number of edges that must be removed to disconnect the graph.
This fact is also stated more explicitly (with a reference to Fiedler) as Proposition 1.12 in Belhaiza et al's Variable Neighborhood Search for Extremal Graphs. XI. Bounds on Algebraic Connectivity.


text:
Q: "Clang: error: no input files" in OS X Following this solution, I use #include "...frontend/tokens.mll" in my lexer.mll, then I use cpp -P frontend/lexer.mll -o frontend/gen/lexer.mll to generate the complete mll file. This solution worked before under Ubuntu.
Now, I try to do this in Mac OS 10.11.1, it gives an error clang: error: no input files.
gcc -v returns
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.3.0 (clang-703.0.29)
Target: x86_64-apple-darwin15.0.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

I don't see where I use XCode, or PCH file. Does anyone know how I should configure the environment to make cpp work?
Edit 1:
cpp --version returns
Apple LLVM version 7.3.0 (clang-703.0.29)
Target: x86_64-apple-darwin15.0.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

And an example from the comment:

A: So if I understand correctly what you are trying to do, you want to run the c preprocessor on a file to produce text output which will be stored in another file. I don't know why but, here is a command that will accomplish that :
clang -x c frontend/lexer.mll -E -P -o frontend/gen/lexer.mll

This invokes clang; sets the language to C (-x c); gives your file; asks for preprocessing only, no compile or link (-E); no line info in the output (-P), stores it in frontend/gen/lexer.mll
Xcode is an IDE that runs clang. If you are working in ocaml it may not be helpful to use Xcode since it wouldn't know what to do with ocaml files.

A: It could be a bug from clang, as this one works for me:
$ cpp -P xxx yyy
$ cat yyy
from zzz

and
$ clang --version
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin14.5.0
Thread model: posix

A: 1 - open XCode
2 - Create a new XCode project
3 - choose tab of OSX
4 - choose Application
5 - choose Command Line tool
6 - in next window you have to enter product name etc
7 - and choose c++ as a language

A: 'cpp -P xxx -o yyy' you need it to be -> 'echo "blahblahblah.cpp" > xxx'


text:
Q: Optimizar consulta SQL usando Eloquent de Laravel Espero que estén todos bien, tengo la siguiente consulta en mi sistema.
public function visits()
{

    foreach ($this->countrys as $country)
    {
        $query = Visit::where('country',$country)->count();
        $visits[$country]=$query;

    }

    return $visits;
}

La consulta va iterando el siguiente array
public $countrys = array('AF','AX','AL','DZ','AS','AD','AO','AI','AQ','AG','AR','AM','AW','AU','AT','AZ','BS','BH','BD','BB','BY','BE','BZ','BJ','BM','BT','BO','BQ','BA','BW','BV','BR','IO','VG','BN','BG','BF','BI','KH','CM','CA','CV','KY','CF','TD','CL','CN','CX','CC','CO','KM','CK','CR','HR','CU','CW','CY','CZ','CD','DK','DJ','DM','DO','TL','EC','EG','SV','GQ','ER','EE','ET','FK','FO','FJ','FI','FR','GF','PF','TF','GA','GM','GE','DE','GH','GI','GR','GL','GD','GP','GU','GT','GG','GN','GW','GY','HT','HM','HN','HK','HU','IS','IN','ID','IR','IQ','IE','IM','IL','IT','CI','JM','JP','JE','JO','KZ','KE','KI','XK','KW','KG','LA','LV','LB','LS','LR','LY','LI','LT','LU','MO','MK','MG','MW','MY','MV','ML','MT','MH','MQ','MR','MU','YT','MX','FM','MD','MC','MN','ME','MS','MA','MZ','MM','NA','NR','NP','NL','AN','NC','NZ','NI','NE','NG','NU','NF','KP','MP','NO','OM','PK','PW','PS','PA','PG','PY','PE','PH','PN','PL','PT','PR','QA','CG','RE','RO','RU','RW','BL','SH','KN','LC','MF','PM','VC','WS','SM','ST','SA','SN','RS','CS','SC','SL','SG','SX','SK','SI','SB','SO','ZA','GS','KR','SS','ES','LK','SD','SR','SJ','SZ','SE','CH','SY','TW','TJ','TZ','TH','TG','TK','TO','TT','TN','TR','TM','TC','TV','VI','UG','UA','AE','GB','US','UM','UY','UZ','VU','VA','VE','VN','WF','EH','YE','ZM','ZW');

y el resultado es este mas o menos este, claro mas resumido
array["AF"=>32,"AX"=>21];//Asi sucesivamente hasta obtener todos lo resultados de array

Pero existe un problema de rendimiento y es que son como 251 consultas a la base de datos y cada vez que entro en el dashboard de mi aplicación.
Existe alguna manera de hacer un count de cada uno de los parámetro del array a la base de datos en una única consulta?
las columnas de la tabla son las siguientes:
 id, ip, country, created_at y updated_at
Gracias disculpen la ignorancia.

A: Después de investigar un rato conseguí la siguiente solución por si a alguien le puede servir.
public function visits()
{

    $visits = Visit::select('country')
                    ->selectRaw('count(*) as totalCountry')
                    ->groupBy('country')
                    ->get();

    return $visits;

}


text:
Q: Displaying dynamic table in Data Driven Pages environment? I am creating a map series that has many polygons per sheet. There is annotation for the polygons however some polygons are very small with no annotation for them (annotation would completely hide a polygon). Thus, I have an attribute table where labels are stored for those specific polygons.
How can I have that table displayed on the map, with only the attribute values per sheet, rather than all 2000+ values?
I am looking for a simple, dynamic solution.

A: This is possible using the Graphic Table Element in the Production Mapping extension. If you don't have the extension (our company didn't either but managed to arrange on), a free trial is available here:
There is more info at this ESRI help article:here
I also found this ESRI forum post particularly useful:here

A: I do not think this is possible with the standard 10.0 out of the box.  However, with enhancements to arcpy at 10.1, you can dynamically create a table using arcpy scripting.
Take a look at the Esri 2012 Conference Proceedings and the talk titled "Python Map Automation—Beyond the Basics of arcpy.mapping".
On page 6 of the PDF, they show some sample code for how to clone graphic lines to generate a table-like graphic, and then insert text for various attribute components into the "cells".
Also, in the "arcpy.mapping / Map Automation" gallery you will find a number of samples, some of which include examples of how to create "dynamic" or "graphic" tables.

A: Add a legend that consists only of that shapefile, symbolize it by the desired attribute field and set the legend to only display feature in that extent.

A: According to me you can access the attribute table for this.
Select the data you were talking about and head to the top left in the attribute table window. click on Add table to layout. It won't update every time you make a change but it should display the data you need.

A: If anyone is looking for a solution to requirements like yours, then writing pseudo-dynamic tables on layouts for map automation using ArcPy is covered in one of my eLearning courses titled Challenging times with Python and ArcPy for ArcGIS Pro.
That course is for ArcGIS Pro but the learnings from it could be back-applied to ArcMap.  The lack of arcpy.da cursors might make it noticeably slower if using ArcGIS Desktop 10.0.  The key technique is generating "table-like feature classes" that can be placed in a separate map/data frame on the layout used by cursoring through an index feature class.
Disclosure: I am the author and presenter of the course suggested above.


text:
Q: Express 4 : I have a variable set up in app.js and I need to send it to my routes Here's what I have added to my app.js page. (using express generator)
app.js
var express = require('express');
var socket_io = require( "socket.io" );

var app = express();

// Socket.io
var io = socket_io();
app.io = io;

Now if I were to do the following:
io.on('connection', function (socket) {
   console.log("connection made!");
});

This works nicely! But I'm wondering, how do I send socket_io to my route? For example I have a route called 'playground' and I would like to use socket_io specifically inside that route. I don't know how to do so! Any help would be great and I hope I was descriptive enough!

A: There are many ways to do this.
You can pass io as a function argument to your route module:
app.js
var express = require('express');
var socket_io = require( "socket.io" );

var app = express();

// Socket.io
var io = socket_io();

var route = require('./route')(io);

route.js
module.exports = function(io) {
    io.on('connection', function (socket) {
       console.log("connection made!");
    });
};

Or you can export an init method:
route.js
module.exports.init = function(io) {
    io.on('connection', function (socket) {
       console.log("connection made!");
    });
};

Or you can define a constructor for your route:
app.js
var express = require('express');
var socket_io = require( "socket.io" );

var app = express();

// Socket.io
var io = socket_io();

var Route = require('./route');

var r = new Route(io);
r.doSomething();

route.js
var Route = function(io) {
    this.io = io;
    io.on('connection', function (socket) {
       console.log("connection made!");
    });
};

Route.prototype.doSomething = function() {
    console.log('hi');
};

// route.js
module.exports = Route;


text:
Q: Does the stable category of a nice exact category embed in (the underlying category of) a derivator? In Derivators, Pointed Derivators, and Stable Derivators, Moritz Groth gives as an example of a non-invertible morphism with trivial cone an inclusion $f:X\to I$. Here $X$ is an object of injective dimension $1$ in an exact category $\mathcal{E}$ with enough injectives, $I$ is an injective, and the stable category $\underline{\mathcal{E}}$ has a "suspended structure" given in the same way as the triangulation of the stable category of a Frobenius category but without the invertibility of suspension.
This is fine as far as it goes, but it's not obvious to me that this is an example of a cone in a pointed derivator, what he's just defined, and Groth doesn't give any indication of how to see it as such.
Question: how can I realize this example as a cone in a derivator?
Having looked around, I don't see any evidence that $\underline{\mathcal{E}}$ is known to be the underlying category of a derivator, even with extra assumptions a la a paper of Stovicek to make $\mathcal{E}$ more like a Grothendieck category. Is it, in fact, such an underlying category, given some extra assumptions? Or can we, perhaps, give it an exact embedding in a homotopy category, and extend to a derivator in that way?

A: This is not exactly answering your question but: a Frobenius category $\mathcal{E}$ (with suitable assumptions) can be given the structure of a model category whose homotopy category is the stable category $\underline{\mathcal{E}}$. See James Gillespie's http://arxiv.org/abs/1009.3574.
Now take the derivator associated with this model category structure (again, I am not so sure about the required assumptions). Its underlying category will be the stable category $\underline{\mathcal{E}}$.


text:
Q: How does a roller coaster car stay on the track on a curve Say a roller coaster car is going up a ramp to a drop. At some point it needs to traverse a curve to get to the drop. In general, since the car is constrained to the rail, how is it able to move around on curves without breaking the car? Does there exist some kind of free motion for the wheels to move a little bit? Otherwise it seems like the car would bend.

A: The Google search "roller coaster wheels" brings up this picture (from wikipedia page):

As you can see, the "wheels" are really an assembly of three different pairs of wheels: the ones from above, supporting the normal weight; a pair below, that stops the car flying off the track in negative g curves; and ones on the side that, in conjunction with a similar pair on the other side of the tracks, holds the car on the rails laterally. Clearly, the rails are circular in cross section with all the supports on the inside in order to accommodate these wheels.
Note also the giant swivel bolt in the center, near the top. This is where the entire assembly can swivel so the wheels can deal with curvature of the rails. I suspect that there is a further degree of freedom (not shown) just as there is on train cars, where the entire assembly (wheels from both sides joined together) can swivel about a common vertical axis - and another one to swivel about a central horizontal axis (see how the two sets of wheels in the picture below are at very different angles - you need lots of degrees of freedom to achieve that). You can't see the pivots, but you can see the motion, in this picture from
http://www.ultimaterollercoaster.com/coasters/reviews/typhoon/typhoon8.shtml

A further cartoon to explain how the first axle allows the car to accommodate convex or concave tracks:

As you can see, the wheels accommodate the curvature - and because they grip the rail on three sides (four, if you look at sets of wheels on both sides of the track) they can hold the car in place on any curve regardless of the direction of the required force.

A: Is there anything wrong with this image (not even considering the suspension on the wheels)?


text:
Q: Объясните, как работает этот код (Python)? class GameState(Enum):
   QUIT = -1
   TITLE = 0
   NEWGAME = 1

def main():
   pygame.init()

   screen = pygame.display.set_mode((screen_w, screen_h))
   game_state = GameState.TITLE

   while True:
      if game_state == GameState.TITLE:
          game_state = title_screen(screen)

      if game_state == GameState.NEWGAME:
          game_state = play_level(screen)

      if game_state == GameState.QUIT:
          pygame.quit()
          return

Меня интересует данная строка из функции main():
if game_state == GameState.TITLE:
        game_state = title_screen(screen)

Проверяется условие, а потом выполняется присвоение переменной game_state функции title_screen(). Но дело в том, что переменная game_state больше нигде в коде не вызывается, только в цикле while и эта строчка
game_state = title_screen(screen)

срабатывает в коде так, как будто после проверки условия происходит не присвоение, а непосредственно вызов функции title_screen(), как будто если бы было просто
if game_state == GameState.TITLE:
        title_screen(screen)

Объясните, как это работает, почему вместо вызова функции используется присвоение переменной?
Вот полный код, если что: https://disk.yandex.ru/d/LFmmqnkNMIawgg


text:
Q: Is it possible to ensure a file is closed without assigning it to a variable? I am reading some data from a .txt file in Python using the following:
fileData = open("file.txt", "rb").read()

I know that you should always close opened files, and I assume in this case the file remains open. Is there a way to close the file without assigning it to a variable?
I'd like to avoid:
openedFile = open("file.txt", "rb")
fileData = openedFile.read()
openedFile.close()

And also:
with open("file.txt", "rb") as openedFile:
    fileData = openedFile.read()

It might not be possible, in which case okay, but just making sure.

A: No, it's not possible. The with statement version is the idiomatic way to write it.
Though I would shorten openedFile to file or even f. Rule of thumb: The smaller the scope of a variable the shorter its name can be. Save the long names for long-lived identifiers.
with open("file.txt", "rb") as file:
    data = file.read()


text:
Q: Multi-level Pie Chart in R I'd like to make a very simple multi-level pie chart like the one you see below:

As you can see I already know about sunburstR but (since I am looking for a  simpler solution) that's not exactly how it should be. Additionally I'd prefer if I could easily export it as vector graphics.
The second solution, using ggplot2 to do a plot in polar coordinates also appears quite complicated for such a simple plot.
I'd be happy if you could help me! Thanks in advance!
SP

A: In ggplot2 this is should do the trick:
    library("ggplot2")
    df <- data.frame(a = c(4, 3, 3, 8, 1, 1, 10),
                     b = c("x", "x", "x", "y", "y", "y", "z"),
                     c = c("x1", "x2", "x3", "y1", "y2", "y3", "z1"))

    ggplot(df, aes(x = b, y = a, fill = c))+
      geom_bar(stat = "identity")+
      coord_polar(theta="y")

I hope this helps.
Cheers


text:
Q: How to add two columns together and order by id in scala? My df is like id col1 col2 and I want to sum col1 and col2 together to make cols. Then display id cols order by id. I know how to do sum like df.select($"col1" + $"col2").orderBy(desc("id")) but df.select($"col1" + $"col2") will remove id so I cannot do orderBy id. Any idea?

A: df.withColumn("cols", $"col1" + $"col2").orderBy(desc("id")).select($"id",
$"cols")

withColumn returns a new dataframe with the column : "cols" in it. Then perform an orderBy on column "id" and select columns "id" and "cols". Alternatively,you may also just drop columns after orderBy function drop(columnNames*) function
scala> val df = Seq((2, 10, 20), (1, 5, 30), (3, 25, 15)).toDS.select($"_1" as "id", $"_2" as "col1", $"_2" as "col2")
df: org.apache.spark.sql.DataFrame = [id: int, col1: int ... 1 more field]

scala> df.show
+---+----+----+
| id|col1|col2|
+---+----+----+
|  2|  10|  10|
|  1|   5|   5|
|  3|  25|  25|
+---+----+----+

scala> df.withColumn("cols", $"col1" + $"col2").orderBy(desc("id")).select($"id", $"cols").show
+---+----+
| id|cols|
+---+----+
|  3|  50|
|  2|  20|
|  1|  10|
+---+----+

scala> df.withColumn("cols", $"col1" + $"col2").orderBy(desc("id")).drop("col1", "col2").show
+---+----+
| id|cols|
+---+----+
|  3|  50|
|  2|  20|
|  1|  10|
+---+----+

scala> df.withColumn("cols", $"col1" + $"col2").orderBy(desc("id")).show
+---+----+----+----+
| id|col1|col2|cols|
+---+----+----+----+
|  3|  25|  25|  50|
|  2|  10|  10|  20|
|  1|   5|   5|  10|
+---+----+----+----+

A: Something like below.
val df = Seq(("Edward",1, 1, 1000,"me1@example.com"),
      ("Michal",3,2,15000,"me1@example.com"),
      ("Steve",7,3,25000,"you@example.com"),
      ("Jordan",2,4,40000, "me1@example.com")).
      toDF("Name", "ID1", "ID2","Salary","MailId")

    df.show()

+------+---+---+------+---------------+
|  Name|ID1|ID2|Salary|         MailId|
+------+---+---+------+---------------+
|Edward|  1|  1|  1000|me1@example.com|
|Michal|  3|  2| 15000|me1@example.com|
| Steve|  7|  3| 25000|you@example.com|
|Jordan|  2|  4| 40000|me1@example.com|
+------+---+---+------+---------------+

    val df1 = df.select($"Salary",($"ID"+$"ID2").as("ID")).orderBy(desc("Salary"))

df1.show()

+------+---+
|Salary| ID|
+------+---+
| 40000|  6|
| 25000| 10|
| 15000|  5|
|  1000|  2|
+------+---+


text:
Q: TypeError: Assignment to constant variable. React.js Hook Im coding a navigation bar, button should change false to true  and true to false for display a navigation menu, but when i click on it throws TypeError: Assignment to constant variable.
NavBar.js:
import React, { useState } from "react";
import "./navbar.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBars } from "@fortawesome/free-solid-svg-icons";

const NavBar = (props) => {
  const [toggle, setToggle] = useState(false);
  return (

      Iván Méndez
      Acerca de mí
      Proyectos
      Habilidades
      Contactacme
      <button
        onClick={() => setToggle((toggle = !toggle))}
        className="navbar__toggler"
      >
        <FontAwesomeIcon icon={faBars} />
      </button>

  );
};

export default NavBar;

Chrome throws this:
  13 | Habilidades
  14 | Contactacme
  15 | <button
> 16 |   onClick={() => setToggle(toggle = !toggle)}
     | ^  17 |   className="navbar__toggler"
  18 | >
  19 |   <FontAwesomeIcon icon={faBars} />

Ive Been reading react docs again and again but im misunderstanding somethings

A: The error is self descriptive I guess. You need to use the setter instead of assigning a value directly to your state object.
Avoid this:
toggle = !toggle

Replace your onClick to not to re-assign:
onClick={() => setToggle(!toggle)}

A: You can do it like this:
<button
  onClick={() => setToggle(prevToggle => !prevToggle)}
  className="navbar__toggler"
>
  <FontAwesomeIcon icon={faBars} />
</button>


text:
Q: Problem with NumberForm when exporting I have a two-part question regarding NumberForm

First question

In my attempt at answering this i stumbled upon a strange behavior by NumberForm when the final result is exported.
Lets say I have a simple Table output as shown below which uses the command NumberForm
t1 = Table[{i, NumberForm[Range[i], {2, 2}]}, {i, 1, 2}]

Now if I export this it works fine
   Export["try.dat", t1];
   FilePrint["try.dat"]
  (* 1  {1.00} *)
  (* 2  {1.00, 2.00}*)

But if i slightly tweak the Table like this
 t2 = Table[{i, NumberForm[Range[i + #], {2, 2}] & /@ Range[2]}, {i, 1, 2}]

Now on export NumberForm remains unevaluated
  Export["try.dat", t2];
  FilePrint["try.dat"]

(* 1    {NumberForm[{1, 2}, {2, 2}], NumberForm[{1, 2, 3}, {2, 2}]} *)
(* 2    {NumberForm[{1, 2, 3}, {2, 2}], NumberForm[{1, 2, 3, 4}, {2, 2}]} *)

So why is this happening?

Second question

Also while searching I found this where the OP asked and answered his own question regarding NumberForm but when I run his/her solution it's not giving the expected answer in my machine (Windows 8 with mma 9). Below is the code which the OP gave.
time = Table[i, {i, 0, 0.4, 0.01}];
time2 = Table[NumberForm[i, 6], {i, 0, 0.4, 0.01}];
op = Table[time[[i]]^2 + time[[i]], {i, 1, Length@time}];
Export["data.dat", Transpose@{time2, op}, "Table"];
FilePrint["data.dat"];

Can someone confirm what they get on running the above piece matches with whats given in that thread. I'm getting some numbers which are not formatted.

A: I confirm the issue in Version 9.0.1.0 (Windows 8 64-bit). A workaround is wrapping NumberForm with OutputForm:
t2b = Table[{i, OutputForm[NumberForm[Range[i + #], {2, 2}]] & /@ Range[2]}, {i, 1, 2}]
Export["tryb.dat", t2b];
FilePrint["tryb.dat" ]

A: You have an extra pair of list brackets in t2 which you can remove like so:-
t2 = Table[{i, Apply[Sequence,
    NumberForm[Range[i + #], {2, 2}] & /@ Range[2]]}, {i, 1, 2}]

Then it works like t1.
Export["try.dat", t2];
FilePrint["try.dat"]

(* 1    {1.00, 2.00}    {1.00, 2.00, 3.00} *)
(* 2    {1.00, 2.00, 3.00}  {1.00, 2.00, 3.00, 4.00} *)


text:
Q: Return individual cell values from a wildcard search against a range into individual cells using Excel so I've been trying to work out this problem in Excel (Office 2016, Mac El Capitan, latest updates installed) but have failed so far.
In essence, I would like to search a range of cells (in this case A2:A9) for a partial keyword (A2). Hence all cells that match this criterium should then appear in the result range (E2:E9). I already struggle with this, as I'm only able to return a single result (e.g. one row entry in E2). I have attempted this with INDEX and MATCH but have failed so far.
After this, I would then look-up the corresponding quantity in range B2:B9 using vlookup, this works for now.
The final, desired outcome is attached as an image.
Thanks a lot for your help.

A:
Apply the formula below to E2 and copy down as far as needed.
=IFERROR(INDEX(A:A,AGGREGATE(15,6,ROW(A:A)/ISNUMBER(SEARCH($C$2,A:A)),ROW(A1))),"no more entries")

in F2 use the following formula and copy down as required as well
=SUMIF(A:A,E2,B:B)

A few caveats.

*

*Since the first formula is performing array like calculations inside the aggregate function, full column references should be avoided.  Change A:A to $A$2:$A$9or whatever your range is.

*Column A is assumed to be full of unique names

*The search is not case sensitive.  If you need it to be change SEARCH to FIND

*If you do not want to see "no more entries" change it to ""

A: In Cell E2 enter the following formula
=IFERROR(INDEX($A$2:$A$9,SMALL(IF(ISNUMBER(SEARCH($C$2,$A$2:$A$9)),ROW($A$2:$A$9)-1),ROW(1:1))),"")

This is an array formula so commit it by pressing Ctrl+Shift+Enter. Drag/Copy down as required.
Then to get corresponding quantity enter following formula in Cell F2
=INDEX($B$2:$B$9,MATCH(E2,$A$2:$A$9,0))

Drag/Copy down as required. See image for reference.

Note: SEARCH function is case-insensitive. If you are looking for a case sensitive match, use FIND function.


text:
Q: Can AutoCAD connect to PostGIS (specifically for Ordnance Survey Mastermap)? As per title.
Can up to date (2019) AutoCAD versions be practically/safely connected to a PostGIS database.
And more specifically does this work well/practically/safely for accessing Ordnance Survey Mastermap data? What are the limitiations?


text:
Q: Load divi slider slides randomly with some some slides weighted to display more frequently I'm using the below script to load a fullwidth Divi slider randomly - so the same slide doesn't always load first. Now I wonder if anyone can suggest an edit.
I would like to prevent some slides from loading first, and/or to just weight some slides so they display more frequently than others. Any ideas?
Thanks!
'''
<script type="text/javascript">
jQuery(document).ready(function(){
  var item = document.querySelector('.et_pb_slider .et_pb_slides');
  if(item!=null){
    for (var i = item.children.length; i >= 0; i--) {
      item.appendChild(item.children[Math.random() * i | 0]);
    }
  }
});
</script>

'''


text:
Q: Docker build from Dockerfile with more memory How to docker build from Dockerfile with more memory?
This is a different question from this Allow more memory when docker build a Dockerfile
When installing the software natively, there is enough memory to successfully build and install the marian tool
But when building the Docker image using the Dockerfile
https://github.com/marian-nmt/marian/blob/master/scripts/docker/Dockerfile.cpu , it fails with multiple memory exhausted errors
virtual memory exhausted: Cannot allocate memory

[out]:
Step : RUN cmake $MARIANPATH && make -j
 ---> Running in 4867d166d17a
-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CUDA_TOOLKIT_ROOT_DIR not found or specified
-- Cannot find CUDA libraries. Compiling without them.
-- Could NOT find CUDA (missing:  CUDA_TOOLKIT_ROOT_DIR CUDA_NVCC_EXECUTABLE CUDA_INCLUDE_DIRS CUDA_CUDART_LIBRARY)
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE
-- Boost version: 1.58.0
-- Found the following Boost libraries:
--   system
--   filesystem
--   program_options
--   timer
--   iostreams
--   python
--   thread
--   chrono
--   regex
--   date_time
--   atomic
-- Found Python
-- Found PythonLibs: /usr/lib/x86_64-linux-gnu/libpython2.7.so (found suitable version "2.7.12", minimum required is "2.7")
-- Found ZLIB: /usr/lib/x86_64-linux-gnu/libz.so (found version "1.2.8")
-- Found Git: /usr/bin/git (found version "2.7.4")
-- Git version: 5abc774
-- Found SparseHash: /usr/include
-- Configuring done
-- Generating done
-- Build files have been written to: /marian/build
Scanning dependencies of target fast_align
Scanning dependencies of target extract_lex
Scanning dependencies of target libcnpy
Scanning dependencies of target atools
Scanning dependencies of target libyaml-cpp-amun
[  2%] Building CXX object src/amun/3rd_party/extract_lex/CMakeFiles/extract_lex.dir/exception.cpp.o
[  2%] Building CXX object src/amun/3rd_party/extract_lex/CMakeFiles/extract_lex.dir/utils.cpp.o
[  3%] Building CXX object src/amun/3rd_party/fast_align/CMakeFiles/fast_align.dir/src/ttables.cc.o
[  6%] Building CXX object src/amun/3rd_party/fast_align/CMakeFiles/fast_align.dir/src/fast_align.cc.o
[  7%] Building CXX object src/amun/3rd_party/extract_lex/CMakeFiles/extract_lex.dir/extract-lex-main.cpp.o
[ 10%] Building CXX object src/amun/3rd_party/CMakeFiles/libcnpy.dir/cnpy/cnpy.cpp.o
[ 10%] Building CXX object src/amun/3rd_party/fast_align/CMakeFiles/atools.dir/src/atools.cc.o
[ 10%] Building CXX object src/amun/3rd_party/fast_align/CMakeFiles/atools.dir/src/alignment_io.cc.o
[ 11%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/regex_yaml.cpp.o
[ 12%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/scanner.cpp.o
[ 14%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/convert.cpp.o
[ 15%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/stream.cpp.o
[ 16%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/memory.cpp.o
[ 17%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/node.cpp.o
[ 19%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/directives.cpp.o
[ 20%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/null.cpp.o
[ 21%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/emitfromevents.cpp.o
[ 23%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/singledocparser.cpp.o
[ 24%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/emitterstate.cpp.o
[ 25%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/scantag.cpp.o
[ 26%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/simplekey.cpp.o
[ 28%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/binary.cpp.o
[ 29%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/parser.cpp.o
[ 30%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/nodeevents.cpp.o
[ 32%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/emit.cpp.o
[ 33%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/exp.cpp.o
[ 35%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/nodebuilder.cpp.o
[ 38%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/scanscalar.cpp.o
[ 39%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/emitter.cpp.o
[ 41%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/tag.cpp.o
[ 42%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/scantoken.cpp.o
[ 43%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/ostream_wrapper.cpp.o
Scanning dependencies of target libcommon
[ 37%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/node_data.cpp.o
[ 44%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/contrib/graphbuilder.cpp.o
[ 46%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/emitterutils.cpp.o
[ 34%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/contrib/graphbuilderadapter.cpp.o
[ 47%] Building CXX object src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/parse.cpp.o
[ 48%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/scorer.cpp.o
[ 50%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/git_version.cpp.o
[ 51%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/base_matrix.cpp.o
[ 52%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/sentence.cpp.o
[ 53%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/config.cpp.o
[ 55%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/utils.cpp.o
[ 56%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/vocab.cpp.o
[ 65%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/filter.cpp.o
[ 66%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/god.cpp.o
[ 67%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/exception.cpp.o
[ 69%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/search.cpp.o
[ 69%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/hypothesis.cpp.o
[ 70%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/translation_task.cpp.o
[ 70%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/printer.cpp.o
[ 70%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/sentences.cpp.o
[ 70%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/history.cpp.o
[ 70%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/logging.cpp.o
[ 70%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/processor/bpe.cpp.o
[ 71%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/output_collector.cpp.o
[ 73%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/types.cpp.o
[ 74%] Building CXX object src/amun/CMakeFiles/libcommon.dir/common/loader.cpp.o
virtual memory exhausted: Cannot allocate memory
virtual memory exhausted: Cannot allocate memory
virtual memory exhausted: Cannot allocate memory

And eventually it leads to:
src/amun/CMakeFiles/libcommon.dir/build.make:254: recipe for target 'src/amun/CMakeFiles/libcommon.dir/common/loader.cpp.o' failed
virtual memory exhausted: Cannot allocate memory
make[2]: *** [src/amun/CMakeFiles/cpumode.dir/cpu/decoder/encoder_decoder.cpp.o] Error 1
src/amun/CMakeFiles/cpumode.dir/build.make:110: recipe for target 'src/amun/CMakeFiles/cpumode.dir/cpu/decoder/encoder_decoder.cpp.o' failed
[ 79%] Built target libcnpy
virtual memory exhausted: Cannot allocate memory
src/amun/CMakeFiles/libcommon.dir/build.make:326: recipe for target 'src/amun/CMakeFiles/libcommon.dir/common/printer.cpp.o' failed
make[2]: *** [src/amun/CMakeFiles/libcommon.dir/common/printer.cpp.o] Error 1
CMakeFiles/Makefile2:340: recipe for target 'src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/all' failed
make[1]: *** [src/amun/3rd_party/yaml-cpp/CMakeFiles/libyaml-cpp-amun.dir/all] Error 2
CMakeFiles/Makefile2:182: recipe for target 'src/amun/CMakeFiles/libcommon.dir/all' failed
make[1]: *** [src/amun/CMakeFiles/libcommon.dir/all] Error 2
make[1]: *** [src/amun/CMakeFiles/cpumode.dir/all] Error 2
CMakeFiles/Makefile2:110: recipe for target 'src/amun/CMakeFiles/cpumode.dir/all' failed
make: *** [all] Error 2

Looking at the docker build --help, there are options to control memory usage:
$ docker build --help

Usage:  docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

Options:
      --build-arg list             Set build-time variables (default [])
      --cache-from stringSlice     Images to consider as cache sources
      --cgroup-parent string       Optional parent cgroup for the container
      --compress                   Compress the build context using gzip
      --cpu-period int             Limit the CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int              Limit the CPU CFS (Completely Fair Scheduler) quota
  -c, --cpu-shares int             CPU shares (relative weight)
      --cpuset-cpus string         CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string         MEMs in which to allow execution (0-3, 0,1)
      --disable-content-trust      Skip image verification (default true)
  -f, --file string                Name of the Dockerfile (Default is 'PATH/Dockerfile')
      --force-rm                   Always remove intermediate containers
      --help                       Print usage
      --isolation string           Container isolation technology
      --label list                 Set metadata for an image (default [])
  -m, --memory string              Memory limit
      --memory-swap string         Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --network string             Set the networking mode for the RUN instructions during build (default "default")
      --no-cache                   Do not use cache when building the image
      --pull                       Always attempt to pull a newer version of the image
  -q, --quiet                      Suppress the build output and print image ID on success
      --rm                         Remove intermediate containers after a successful build (default true)
      --security-opt stringSlice   Security options
      --shm-size string            Size of /dev/shm, default value is 64MB
  -t, --tag list                   Name and optionally a tag in the 'name:tag' format (default [])
      --ulimit ulimit              Ulimit options (default [])

But I couldn't figure out the correct syntax of where exactly to put the -m option -_-|||
It isn't before the Dockerfile:
# Before Docker file.
$ docker build -m 4g Dockerfile.cpu -t ibot-cpu .

"docker build" requires exactly 1 argument(s).
See 'docker build --help'.

Usage:  docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

It isn't after Dockerfile before -t
# Before -t
$ docker build Dockerfile.cpu -m 4g -t ibot-cpu .

"docker build" requires exactly 1 argument(s).
See 'docker build --help'.

Usage:  docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

It isn't after -t before the local path
# Before local path
$ docker build Dockerfile.cpu -t ibot-cpu -m 4g .

"docker build" requires exactly 1 argument(s).
See 'docker build --help'.

Usage:  docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

It isn't after the local path at the end too...
# At the end...
$ docker build Dockerfile.cpu -t ibot-cpu . -m 4g

"docker build" requires exactly 1 argument(s).
See 'docker build --help'.

Usage:  docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

How to docker build from Dockerfile with more memory?
My docker version:
docker version
Client:
 Version:      17.03.1-ce
 API version:  1.27
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Tue Mar 28 00:40:02 2017
 OS/Arch:      darwin/amd64

Server:
 Version:      17.04.0-ce
 API version:  1.28 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   4845c56
 Built:        Wed Apr  5 18:45:47 2017
 OS/Arch:      linux/amd64
 Experimental: false

A: It is not something about order. The Dockerfile must be specified with -f
docker build -f Dockerfile.cpu -t ibot-cpu -m 4g .

However, take into account that by default docker does not limit the container memory. It can take the whole free memory.
As I can see that you are on OSX, which runs docker over a Linux VM. Configure the max memory clicking the whale icon in the task bar. It's 2GB by default.
For further information please see my other answer:
How to assign more memory to docker container


text:
Q: How to add database in RESTful web application? I am a newbie in asp.net and trying to learn things. So I created a project with code from a tutorial online(https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio) with the the following classes.
Controllers:
namespace WebApiSample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TodoController : ControllerBase
    {
        private readonly ToDoContext _context;

        public TodoController(ToDoContext context)
        {
            _context = context;

            if (_context.TodoItems.Count() == 0)
            {
                // Create a new TodoItem if collection is empty,
                // which means you can't delete all TodoItems.
                _context.TodoItems.Add(new ToDoItem { Name = "Item1" });
                _context.SaveChanges();
            }
        }

        // GET: api/Todo
        [HttpGet]
        public async Task<ActionResult<IEnumerable<ToDoItem>>> GetTodoItems()
        {
            return await _context.TodoItems.ToListAsync();
        }

        // GET: api/Todo/5
        [HttpGet("{id}")]
        public async Task<ActionResult<ToDoItem>> GetTodoItem(long id)
        {
            var todoItem = await _context.TodoItems.FindAsync(id);

            if (todoItem == null)
            {
                return NotFound();
            }

            return todoItem;
        }

        // POST: api/Todo
        [HttpPost]
        public async Task<ActionResult<ToDoItem>> PostTodoItem(ToDoItem todoItem)
        {
            _context.TodoItems.Add(todoItem);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem);
        }

        // PUT: api/Todo/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutTodoItem(long id, ToDoItem todoItem)
        {
            if (id != todoItem.Id)
            {
                return BadRequest();
            }

            _context.Entry(todoItem).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return NoContent();
        }

        // DELETE: api/Todo/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<ToDoItem>> DeleteTodoItem(long id)
        {
            var todoItem = await _context.TodoItems.FindAsync(id);
            if (todoItem == null)
            {
                return NotFound();
            }

            _context.TodoItems.Remove(todoItem);
            await _context.SaveChangesAsync();

            return todoItem;
        }
    }
}

Models:
namespace WebApiSample.Models
{
    public class ToDoItem
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }
}

namespace WebApiSample.Models
{
    public class ToDoContext : DbContext
    {
        public ToDoContext(DbContextOptions<ToDoContext> options)
    : base(options)
        {
        }

        public DbSet<ToDoItem> TodoItems { get; set; }
    }
}

Startup.cs:
namespace WebApiSample
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ToDoContext>(opt => opt.UseInMemoryDatabase("ToDoList"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

Program.cs
namespace WebApiSample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

You can see that it doesn't use any database. How can I add a database in this project so that whenever I run it I can get the list of items already added before ?
Any ideas?

A: Generally, Entity Framework will be the best solution for this. Below is a link for the supported databases using entity framework Entity Framework Databases Supported. However, if you want to connect to other databases then you will need to make your own CRUD operations (Create, Retrieve, Update, Delete). Here is an example of CRUD using MongoDB.


text:
Q: How do you implement a custom ConnectionHandler for aspnetcore? I have looked through samples in the github repo, but when i develop my process, i get "Connection ID required" when accessing the route that is mapped to a custom ConnectionHandler. My log message is never printed, nor do i land in the implementation with the debugger.
Startup:
        builder.Services.AddConnections();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapConnectionHandler<CustomDelegationHandler>("/proxy/{id}");
        });

Implementation:
public class CustomDelegationHandler : ConnectionHandler
{
    private readonly ILogger<CustomDelegationHandler> _logger;

    public CustomDelegationHandler(ILogger<CustomDelegationHandler> logger)
    {
        _logger = logger;
    }

    public override async Task OnConnectedAsync(ConnectionContext connection)
    {
        _logger.LogWarning("Connection incoming");

        while (true)
        {
            var result = await connection.Transport.Input.ReadAsync();
            var buffer = result.Buffer;
            try
            {
                if (!buffer.IsEmpty)
                {
                    var stream = new MemoryStream();
                    var data = buffer.ToArray();
                    await stream.WriteAsync(data, 0, data.Length);
                    stream.Position = 0;
                }
                else if (result.IsCompleted)
                {
                    break;
                }
            }
            finally
            {
                connection.Transport.Input.AdvanceTo(buffer.End);
            }
        }
    }
}

A: You need add the connection like below and it will map the custom ConnectionHandler:
public async Task<IActionResult> Index()
{
    var url = "https://localhost:yourPortNumber/proxy/1";
    var connection = new HttpConnection(new Uri(url));
    await connection.StartAsync();

    var bytes = Encoding.UTF8.GetBytes("aaaa");
    async Task SendMessage()
    {
        await connection.Transport.Output.WriteAsync(bytes);
    }
    // Send the receive concurrently so that back pressure is released
    // for server -> client sends
    await SendMessage();
    return View();
}


text:
Q: getting my calculator to work Ok, so I have this code here and what I am trying to do is read in a character for supersize and if the value is "y" then multiply the price times 1.5 to show fifty percent increase. I'm not really sure where my error is here....
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org     /TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

 <form>

      Enter Product Code
      <input type="text" name="code" id="code" />

      Quantity Buying
      <input type="text" name="numbuy" id="numbuy" />

      Supersize?
      <input type="text" name="ssize" id="ssize" />

      The Price
      <input type="text" name="price" id="price" />

      Bill
      <input type="text" name="bill" id="bill" />

      Tax
      <input type="text" name="tax" id="tax" />

      Total Bill
      <input type="text" name="total" id="total" />

      <input type="button" name="forsum" id="forsum" value="Add" onclick="computebill(this.form)"/>

</form>

A: On a stylistic point, rather than:
                if(ssize=="y"){

                        form.price.value=prices[i];

                        thebill+=(prices[i]*1.5)*thequantity;
                        form.bill.value=thebill.toFixed(2);

                        thetax+=(prices[i]*1.5)*thequantity*taxes[i];
                        form.tax.value=thetax.toFixed(2);

                        thetotal=thebill+thetax;
                        form.total.value=thetotal.toFixed(2);
                }
                else{

                        form.price.value=prices[i];

                        thebill+=(prices[i])*thequantity;
                        form.bill.value=thebill.toFixed(2);

                        thetax+=(prices[i])*thequantity*taxes[i];
                        form.tax.value=thetax.toFixed(2);

                        thetotal=thebill+thetax;
                        form.total.value=thetotal.toFixed(2);
                }

do this:
                var theprice = prices[i];
                if(ssize=="y"){
                        theprice *= 1.5;
                }

                form.price.value=theprice;

                thebill+=theprice*thequantity;
                form.bill.value=thebill.toFixed(2);

                thetax+=theprice*thequantity*taxes[i];
                form.tax.value=thetax.toFixed(2);

                thetotal=thebill+thetax;
                form.total.value=thetotal.toFixed(2);

There are two reasons to suggest this. First, your code says what it means -- namely, in one exceptional case, add 50% to the price, but do everything else the same. Second, it's much easier to add a logging or output statement here to debug what's really wrong with your environment.
Cheers.


text:
Q: How to collect every observable emittion into one object in rxJava2/rxKotlin2? Observable emits trade objects.
How to make operation on each emission into one result object?
Trade(tradeType: String, profit: BigDecimal)
Result(totalProfit: BigDecimal)
Example:
trades
.scan(result: Result, currentTrade: Trade){
  result.totalProfit += currentTrade.profit
}
.subscribe(
 printLn(it.totalProfit)
)

A: Do you have something like this in mind? Please provide a full example next time.
import io.reactivex.rxjava3.core.Flowable
import org.junit.jupiter.api.Test
import java.math.BigDecimal

    class SoScan {
        private val seed : Result = Result(BigDecimal(0.0))

        internal data class Result(val total : BigDecimal)

        internal data class Trade(val profit : Double)

        @Test
        fun scan() {
            Flowable.just(Trade(1.0), Trade(1.0))
                    .scan(seed) { prev, curr ->
                        Result(prev.total.plus(BigDecimal(curr.profit)))
                    }.test()
                    .assertValues(seed, Result(BigDecimal(1.0)), Result(BigDecimal(2.0)))
        }
    }


text:
Q: How to pre warm / pre cache a Trusted Web Activity I'm currently using the TwaLauncher class to launch a Trusted Web Activity from my app using code like the following:
        val launcher = TwaLauncher(context)
        launcher.launch(Uri.parse(URL))

This launches a TWA from within a broader native app.
However the performance is a little slow, i'm seeing a lot of information about pre warming / pre caching with Chrome Custom Tabs (which TWA is based on) but no documentation or information on how too achieve this with TwaLauncher.

A: It is not currently possible to split connecting to the service and launching the Trusted Web Activity when using the TwaLauncher.
One alternative would be to create your own version of the TwaLauncher and modify it so that those 2 steps are split.


text:
Q: Regex detect empty line as end I want to extract a sequence out of some text.
The sequence begins with Diagnostic-Code:, the middle part can be any characters even over multiple lines and the end is marked by an empty line (after which the text continues, but this isn't part of the desired sequence).
This does work for the beginning and middle part, but the ending is found too late:
(?s)Diagnostic-Code: (.+)\n\n

The string looks something like this:
...
Status: 5.0.0
Diagnostic-Code: X-Postfix; test.com
*this*
*should*
*be included too*

--EA7634814EFB9.1516804532/mail.example.com
Content-Description: Undelivered Message
...

--------- edit ---------
Thank you for the anwer @Gurman!
But java.util.regex does somehow behave differently than regex101.com
Action: failed
Status: 5.1.1
Remote-MTA: dns; gmail-smtp-in.l.google.com
Diagnostic-Code: smtp; 550-5.1.1 The email account that you tried to reach does
    not exist. Please try 550-5.1.1 double-checking the recipient's email
    address for typos or 550-5.1.1 unnecessary spaces. Learn more at 550 5.1.1
    https://support.google.com/mail/?p=NoSuchUser u11si15276978wru.314 - gsmtp

--E8A363093CEC.1520529178/proxy03.hostname.net
Content-Description: Undelivered Message
Content-Type: message/rfc822

Return-Path: <no-reply@hostname.net>

The pattern matches the whole multiline diagnostic-code on regex101, but java only matches the first line as group 1:
smtp; 550-5.1.1 The email account that you tried to reach does

The java-code:
diagnosticCodePatter = Pattern.compile("(?i)diagnostic[-| ]Code: ([\\s\\S]*?[\\r\\n]{2})");
matcher = diagnosticCodePatter.matcher(message);
    if (matcher.find()) {
        diagnosticCode = matcher.group(0);

A: Try this regex:
Diagnostic-Code[\s\S]*?[\r\n]{2}

Click for Demo
Don't forget to escape \ with another \ in front of it, in Java.
Explanation

*

*Diagnostic-Code - matches the text Diagnostic-Code

*[\s\S]*? - matches 0+ occurrences of anycharacter(including newlines), as few as possible

*[\r\n]{2} - matches 2 occurrences of either a newline character or a carriage-return.


text:
Q: Gauge transformation for Bloch waves? I have seen in many places saying a gauge transformation transform the Bloch wave function as $\psi_{nk}\to e^{-i\phi_n(k)}\psi_{nk}$. However I don't quite understand how it is related to the "gauge transformation".
When we study the gauge transformation in quantum mechanics, the wave function change by a phase factor which is a function of coordinates, but here it is a function of $k$.
Additional concern:

*

*does $\phi_n(k)$ depend only on $k$ or also on $r$?

*are $\phi_n(k)$ same or different for different $n$?

A: very good question let's see what is gauge transformation
for example if i have some state $|a>$ and I also relabel it as $|b>$ such that $|a>=|b>$.
so they are absolutely same physical states but we just have two different labels for them as $a$ and $b$.
now if you think a hamiltonian for example if we have a system with a hamiltonian, $$H=\frac{p^2}{2m}+
V\cos(2\pi x /\ell)$$ with open boundary conditions where $\ell$ is some parameter
than $|x>$ and $|x+\ell>$ are wo distinc states.
however, if we have a periodic boundary condition then such that system lives in a circle with length $\ell$
$$|x>=|x+\ell>$$ they would be the exactly same physical state. We can define a translation operator $T_\ell$ such that $T_\ell|x>=|x+\ell>$.
now in a first case $T_\ell$ is a symmetry operation it changes $|x>$ to $|x+\ell>$  with same physical properties.
in the second case, $T_\ell$ is a gauge transformation it changes $|x>$ to $|x+\ell>$  and $|x>=|x+\ell>$ so in the second case, it is just relabeling of the exactly same state.  that's the spirit behind gauge transformation.
there can be many different kinds of gauge transformations in physics and all of this actually really hidden in the meaning of term gauge it is defined as according to oxford dictionary
gauge: noun  an instrument that measures and gives a visual display of the amount, level, or contents of something.
so it is just a label and you are transforming the label.
for example $\vec{\nabla}\times\vec{A}=\vec{B}$ where $A$ is electromagnetic potential $A$ is not something physical yet $B$ is I can gauge transform  $A$ as $A\rightarrow A+\nabla f$ and it would give  exactly same $B$ so the same physical  state $B$ can be described by infinite number of different $A$ we can use infinite number of different labels for same $B$. so that's also a gauge structure.
Now finally to your question also wave function is not physical but the square of its magnitude has a physical meaning. $|\psi|^2$ is something physical yet $\psi$ is not and thus you can do a gauge transformation you use a different label that gives the exactly same physical state as $\psi e^{i\phi}$ this will also give exactly same state. in your case also it absolutely does not matter whether it depends on  $k$ because it will give the same square magnitude and same energy.
thus as a takeaway message gauge transformation are the transformation that transforms your state to the same physical state.
on the other hand, symmetries transform your state to a different state with the same physical properties.
gauge transformations do not change any observable and leaves the inner product of untransformed and transformed state unchanged.
symmetry also may not change observable, however, the inner product between initial and transformed state will be zero.
more intuitively, gauge transformation is changing the name of your girlfriend it won't change any physical thing about her you only gauge transformed her.
symmetry is, starting to date with an identical twin of your girlfriend, they have the same physical properties but they are different people you now made an exchange transformation to your girlfriend.


text:
Q: How to play 32-bit Steam games on macOS 12.6 (Monterey)? Apparently since macOS Catalina 10.15 Mac disabled support for 32-bit apps?
How can Steam games like Portal 2 be played on MacBooks that have been keeping up with macOS updates?
In my case I'd like to do this on Intel MacBooks from 2015.

A: I rolled my 2018 Mac Mini back to Mojave.
In hindsight, I wouldn't have done that (I lost a few factory-loaded apps).  I would have gotten a very fast USB thumb drive and put a Mojave OS (and the games) on that.  That particular drive is what I used for my gaming until I got a slightly faster USB-C drive.  Apple explains how to get previous versions of macOS, here.
MacWorld has a procedure on that.  You might need to use a partition on a second thumb drive to install the previous version OS X installer and then reboot to that thumb drive for the installation proper in case the 10.14 installer doesn't want to run under Monterey.


text:
Q: How to store state in rxjs observables in an Angular app? I want to store user status in an Angular service. So I'got a code like this:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class UserService {
  private userName = new BehaviorSubject<string>('undefined');
  private userLoggedIn = new BehaviorSubject<boolean>(false);

  public UserName = this.userName.asObservable();
  public UserLoggedIn = this.userLoggedIn.asObservable();

  constructor() { }

  signOut() {
    this.userLoggedIn.next(false);
    this.userName.next('undefined');
  }

  signIn(name) {
    this.userLoggedIn.next(true);
    this.userName.next(name);
  }
}

It works fine, but seems to reset userName and userLoggedIn values each time a page refreshes. So it doest't store anything like, f.e. Redux does.
I think, I've made a mistake somewhere, but can't get what I'm doing wrong - it's my first Angular app((

A: Just to expand on @HT89s answer, you could store the status in the browser so that it is preserved between page refreshes.
constructor() {

   // store in the browser each time a value is emitted to userLoggedIn
   this.userLoggedIn
      .do((loggedIn) => {
         localStorage.setItem('userLoggedIn', loggedIn);
      });

   this.userName
      .do((userName) => {
         localStorage.setItem('userName', userName);
      });
}

But you would also probably want to extend this kind of solution so that there is some sort of check for expiry of the login.

A: You use BehaviorSubject which is similar to the Observer pattern and therefore often used to facilitate communication between separate components. It cannot keep data after refreshing the page unless you store your user status in local storage as follows:
Store user status in local storage:
localStorage.setItem('userStatus', JSON.stringify(userStatus));

Get user status from local storage:
let userStatus = JSON.parse(localStorage.getItem('userStatus'));


text:
Q: A movie where two teenagers save humanity from harvesting by aliens A B-movie from early 2000s, probably. It might have been based on a comic.
A teenage boy (young adult, maybe) somehow discovers an alien ship that belonged to some kind of space rangers. On the ship, the guy learns that humanity was seeded to Earth by some carnivore arachnids millions of years ago, only to be harvested for food.
Then, with a girl, who becomes the second pilot, they save humanity.

A: Pretty sure this is Laserhawk (1997).

Teenagers in a mid-west town discover that they are destined to fight off an alien invasion as the crew of a spacecraft of unknown origin. They are aided by a mysterious patient in a psychiatric hospital and a frenetic comic book artist.

The film opens with the following voiceover (and the caption, "250 million years ago..."), which matches the basic premise that you described. And the climax of the film does involve a young man and woman piloting a spacecraft of some sort.

An alien lifeform known as Arachtoids has germinated Earth to serve as a future resource for food. Opposed to such harvesting practices, a benevolent lifeform has vowed to protect Earth and other planets from these creatures. Travelling in a ship called Laserhawk, these peacekeepers travel through time to the year 1984, where they inhabit the bodies of three humans who will one day save our planet from their return, and the human species from certain destruction.


text:
Q: Could not read script '..\node_modules\@react-native-community\cli-platform-android\native_modules.gradle' as it does not exist I am trying to buld my react-native app but gradle is not working as well. Could you help me?
My gradle version is 7.5.1


text:
Q: Creating app in Android studio but keep getting an error Required Boolean found int So I'm creating an app that validates a users input but when I did it for the password all it says is Required boolean found int
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user);

   submit = (Button)findViewById(R.id.submit);
   name = (EditText)findViewById(R.id.name);
   pass = (EditText)findViewById(R.id.pass);
   number = (EditText)findViewById(R.id.number);
   email = (EditText)findViewById(R.id.email);

    submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

            final String Name = name.getText().toString();
            final String Pass = pass.getText().toString();

            if(name.length()==0)
            {
                name.requestFocus();
                name.setError("Field cannot be empty");
            }

            else if(!Name.matches("[a-zA-Z]+"))
            {
                name.requestFocus();
                name.setError("ENTER ONLY ALPHABETICAL CHARACTERS");
            }

            else if (pass.length())
            {
                pass.requestFocus();
                pass.setError("FIELD CANNOT BE EMPTY");
            }

            else {
                Context context = getApplicationContext();
                CharSequence text = "Thank you, your request is being processed!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
        }
    });
 }

The error is happening on the line where it says pass.length. Could anyone please help in what the problem is

A: While using conditional statements you have to use boolean variable to check the condition is valid or not.
else if (pass.length())

Here pass.length() returns the length of the variable, which is an integer. You should not use the integer to check the condition.

A: In contrast with e.g. C/C++ language, Java does not allow numeric values to be used instead of boolean values (0/1 != false/true).

A: Use
else if (pass.length()>0)

instead so that you get a boolean value to use inside the if condition


text:
Q: Can't catch exception thrown from Phobos in GDC I wrote a small D program. When compiled with DMD, it works fine, but neither GDC nor LDC2 can catch exceptions thrown from Phobos (proven by GDB). How do I fix this?
Example code:
import std.process;
void main(){
  try
  {
    spawnProcess(["/dev/null"]);
  }
  catch (Throwable p)
  {
    return;
  }
}

which dies with SIGABRT when compiled and executed, even though the catch block should catch the ProcessException.
Compiler: ldc2 based on LLVM 3.3 and DMD 2.063.2 (invoked via ldmd2 -O -inline -release), but also happens with gdc 4.8.2 (invoked via gdmd -O -inline -release). The execption is caught when I use dmd -O -inline -release to compile, even when I only catch ProcessException and not Throwable.

A: It's probably a library mismatch as Adam D. Ruppe noted. Make sure that you're using the correct library via a custom dmd.conf. Don't forget to add a -L switch to your correct libphobos.
The binary download is here.


text:
Q: Silverlight window boundaries say your silverlight area on a webpage is 200px by 200px.
you open a child window, is there a way to make it moveable outside the 200x200 silverlight area?
or say you drop down a combo box, let the drop down go out side of the 200x200 aea?
Thank you

A: Sorry there isn't any practical way to do this.
(There are is a fairly ridiculous/heroic option suggested in the  duplicate thread mentioned in the comment above...)


text:
Q: how to connect a kubernetes pod to the outside world without a forwarding rule (google container engine) I'm using Google's Container Engine service, and got a pod running a server listening on port 3000. I set up the service to connect port 80 to that pod's port 3000. I am able to curl the service using its local and public ip from within the node, but not from outside. I set up a firewall rule to allow port 80 and send it to the node, but I keep getting 'connection refused' from outside the network. I'm trying to do this without a forwarding rule, since there's only one pod and it looked like forwarding rules cost money and do load balancing. I think the firewall rule works, because when I add the createExternalLoadBalancer: true to the service's spec, the external IP created by the forwarding rule works as expected. Do I need to do something else? Set up a route or something?
controller.yaml
kind: ReplicationController
apiVersion: v1beta3
metadata:
    name: app-frontend
    labels:
        name: app-frontend
        app: app
        role: frontend
spec:
    replicas: 1
    selector:
        name: app-frontend
    template:
        metadata:
            labels:
                name: app-frontend
                app: app
                role: frontend
        spec:
            containers:
                - name: node-frontend
                  image: gcr.io/project_id/app-frontend
                  ports:
                    - name: app-frontend-port
                      containerPort: 3000
                      targetPort: 3000
                      protocol: TCP

service.yaml
kind: Service
apiVersion: v1beta3
metadata:
  name: app-frontend-service
  labels:
    name: app-frontend-service
    app: app
    role: frontend
spec:
  ports:
    - port: 80
      targetPort: app-frontend-port
      protocol: TCP
  publicIPs:
   - 123.45.67.89
  selector:
    name: app-frontend

Edit (additional details):
Creating this service adds these additional rules, found when I run iptables -L -t nat
Chain KUBE-PORTALS-CONTAINER (1 references)
target     prot opt source               destination
REDIRECT   tcp  --  anywhere             10.247.247.206       /* default/app-frontend-service: */ tcp dpt:http redir ports 56859
REDIRECT   tcp  --  anywhere             89.67.45.123.bc.googleusercontent.com  /* default/app-frontend-service: */ tcp dpt:http redir ports 56859
Chain KUBE-PORTALS-HOST (1 references)
target     prot opt source               destination
DNAT       tcp  --  anywhere             10.247.247.206       /* default/app-frontend-service: */ tcp dpt:http to:10.241.69.28:56859
DNAT       tcp  --  anywhere             89.67.45.123.bc.googleusercontent.com  /* default/app-frontend-service: */ tcp dpt:http to:10.241.69.28:56859

I don't fully understand iptables, so I'm not sure how the destination port matches my service. I found that the DNS for 89.67.45.123.bc.googleusercontent.com resolves to 123.45.67.89.
kubectl get services shows the IP address and port I specified:
NAME                             IP(S)               PORT(S)
app-frontend-service             10.247.243.151      80/TCP
                                 123.45.67.89

Nothing recent from external IPs is showing up in  /var/log/kube-proxy.log

A: TL;DR: Use the Internal IP of your node as the public IP in your service definition.

If you enable verbose logging on the kube-proxy you will see that it appears to be creating the appropriate IP tables rule:
I0602 04:07:32.046823   24360 roundrobin.go:98] LoadBalancerRR service "default/app-frontend-service:" did not exist, created
I0602 04:07:32.047153   24360 iptables.go:186] running iptables -A [KUBE-PORTALS-HOST -t nat -m comment --comment default/app-frontend-service: -p tcp -m tcp -d 10.119.244.130/32 --dport 80 -j DNAT --to-destination 10.240.121.42:36970]
I0602 04:07:32.048446   24360 proxier.go:606] Opened iptables from-host portal for service "default/app-frontend-service:" on TCP 10.119.244.130:80
I0602 04:07:32.049525   24360 iptables.go:186] running iptables -C [KUBE-PORTALS-CONTAINER -t nat -m comment --comment default/app-frontend-service: -p tcp -m tcp -d 23.251.156.36/32 --dport 80 -j REDIRECT --to-ports 36970]
I0602 04:07:32.050872   24360 iptables.go:186] running iptables -A [KUBE-PORTALS-CONTAINER -t nat -m comment --comment default/app-frontend-service: -p tcp -m tcp -d 23.251.156.36/32 --dport 80 -j REDIRECT --to-ports 36970]
I0602 04:07:32.052247   24360 proxier.go:595] Opened iptables from-containers portal for service "default/app-frontend-service:" on TCP 23.251.156.36:80
I0602 04:07:32.053222   24360 iptables.go:186] running iptables -C [KUBE-PORTALS-HOST -t nat -m comment --comment default/app-frontend-service: -p tcp -m tcp -d 23.251.156.36/32 --dport 80 -j DNAT --to-destination 10.240.121.42:36970]
I0602 04:07:32.054491   24360 iptables.go:186] running iptables -A [KUBE-PORTALS-HOST -t nat -m comment --comment default/app-frontend-service: -p tcp -m tcp -d 23.251.156.36/32 --dport 80 -j DNAT --to-destination 10.240.121.42:36970]
I0602 04:07:32.055848   24360 proxier.go:606] Opened iptables from-host portal for service "default/app-frontend-service:" on TCP 23.251.156.36:80

Listing the iptables entries using -L -t shows the public IP turned into the reverse DNS name like you saw:
Chain KUBE-PORTALS-CONTAINER (1 references)
target     prot opt source               destination
REDIRECT   tcp  --  anywhere             10.119.240.2         /* default/kubernetes: */ tcp dpt:https redir ports 50353
REDIRECT   tcp  --  anywhere             10.119.240.1         /* default/kubernetes-ro: */ tcp dpt:http redir ports 54605
REDIRECT   udp  --  anywhere             10.119.240.10        /* default/kube-dns:dns */ udp dpt:domain redir ports 37723
REDIRECT   tcp  --  anywhere             10.119.240.10        /* default/kube-dns:dns-tcp */ tcp dpt:domain redir ports 50126
REDIRECT   tcp  --  anywhere             10.119.244.130       /* default/app-frontend-service: */ tcp dpt:http redir ports 36970
REDIRECT   tcp  --  anywhere             36.156.251.23.bc.googleusercontent.com  /* default/app-frontend-service: */ tcp dpt:http redir ports 36970

But adding the -n option shows the IP address (by default, -L does a reverse lookup on the ip address, which is why you see the DNS name):
Chain KUBE-PORTALS-CONTAINER (1 references)
target     prot opt source               destination
REDIRECT   tcp  --  0.0.0.0/0            10.119.240.2         /* default/kubernetes: */ tcp dpt:443 redir ports 50353
REDIRECT   tcp  --  0.0.0.0/0            10.119.240.1         /* default/kubernetes-ro: */ tcp dpt:80 redir ports 54605
REDIRECT   udp  --  0.0.0.0/0            10.119.240.10        /* default/kube-dns:dns */ udp dpt:53 redir ports 37723
REDIRECT   tcp  --  0.0.0.0/0            10.119.240.10        /* default/kube-dns:dns-tcp */ tcp dpt:53 redir ports 50126
REDIRECT   tcp  --  0.0.0.0/0            10.119.244.130       /* default/app-frontend-service: */ tcp dpt:80 redir ports 36970
REDIRECT   tcp  --  0.0.0.0/0            23.251.156.36        /* default/app-frontend-service: */ tcp dpt:80 redir ports 36970

At this point, you can access the service from within the cluster using both the internal and external IPs:
$ curl 10.119.244.130:80
app-frontend-5pl5s
$ curl 23.251.156.36:80
app-frontend-5pl5s

Without adding a firewall rule, attempting to connect to the public ip remotely times out. If you add a firewall rule then you will reliably get connection refused:
$ curl 23.251.156.36
curl: (7) Failed to connect to 23.251.156.36 port 80: Connection refused

If you enable some iptables logging:
sudo iptables -t nat -I KUBE-PORTALS-CONTAINER -m tcp -p tcp --dport
80 -j LOG --log-prefix "WTF: "

And then grep the output of dmesg for WTF it's clear that the packets are arriving on the 10. IP address of the VM rather than the ephemeral external IP address that had been set as the public IP on the service.
It turns out that the problem is that GCE has two types of external IPs: ForwardingRules (which forward with the DSTIP intact) and 1-to-1 NAT (which actually rewrites the DSTIP to the internal IP). The external IP of the VM is the later type so when the node receives the packets the IP tables rule doesn't match.
The fix is actually pretty simple (but non-intuitive): Use the Internal IP of your node as the public IP in your service definition. After updating your service.yaml file to set publicIPs to the Internal IP  (e.g. 10.240.121.42) you will be able to hit your application from outside of the GCE network.

A: If you add the node's external IP address to the service's publicIPs field, you should then be able to access it at the node's IP address. If your cluster has multiple nodes, you can put more than one of their IP addresses into the field  if you'd like to enable accessing the pod on any of them.
In an upcoming release there will be a simpler built-in option for setting up an external service without a load balancer. If you're curious or reading this sometime in the future, check out the updated "External Services" section of this doc to see how you'll be able to use use NodePort to accomplish the same thing much more easily.

A: Answer by @Robert Bailey is absolutely correct. publicIPs has been deprecated in kubernetes 1.5.1, you can use externalIPs instead.

*

*get the internal ip of the node, kubectl describe node | grep Address
Addresses:     10.119.244.130,101.192.150.200,gke-...

*or you can run the ifconfig eth0 inside the node terminal to get the internal ip

*set the ip in service.yaml

spec:
  type: NodePort
  externalIPs:
    - 10.119.244.130

*can curl with resolve to test
curl --resolve 'example.com:443:23.251.156.36' https://example.com -k


text:
Q: Real-valued functions whose level sets are hyperplanes? Does the class of functions $f:\mathbb{R}^n\to\mathbb{R}$ such that all of their level sets $\{x\in\mathbb{R}^n: f(x)=c\}$ are hyperplanes have a special name?
In either case, could someone direct me to a characterization result?
Many thanks!

A: I don't know that they have a special name, but they are all composites of some linear function $\Bbb R^n\to \Bbb R$ with some injective function $\Bbb R\to \Bbb R$.
Proof: Take a function $f:\Bbb R^n\to \Bbb R$ with hyperplanes as level sets. These planes must all be parallel as they are not intersecting, so they all have some normal vector $v$ in common. Define the linear function $f_0:\Bbb R^n\to \Bbb R$ by scalar product with $v$.
Define $f_1:\Bbb R\to \Bbb R$ by
$$
f_1(x) = f(f_0^{-1}(x))
$$
This is well-defined as each level set of $f_0$ is also a level set of $f$, and therefore $f$ only takes one value on all of $f_0^{-1}(x)$.
This gives $f = f_1\circ f_0$.


text:
Q: Is it possible to use input variables in keybindings in VS Codium? In Visual Studio Codium I want to define a command that has a variable parameter.
I want the IDE to open specific file, which name is written in another file. Assume I have the following project structure:
/home/user/myproject/
/home/user/myproject/dir1/
/home/user/myproject/dir1/problem1.py
/home/user/myproject/dir1/problem2.py
/home/user/myproject/dir2/problem1.py
...
/home/user/myproject/pointer.txt

The pointer.txt contains path to the file I want to work on. For example, it contains:
dir1/problem1.
I have read the documentation here. Now I created the following construction:
keybindings.json:
    {
        "key": "numpad3",
        "command": "htmlRelatedLinks.openFile",
        "args": {
            "file": "${workspaceFolder}/${input:mycatinput}.py",
            "method": "vscode.open",
            "viewColumn": 2,
        }
    },

tasks.json:
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "mycat",
            "type": "shell",
            "command": "cat /home/user/myproject/pointer.txt"
        },
    ],
    "inputs": [
        {
          "id": "mycatinput",
          "type": "command",
          "command": "workbench.action.tasks.runTask",
          "args": "mycat"
        }
    ]
}

But when I press numpad3, I get an error notification with text: Unable to open '${input:mycatinput}.py': File not found.
Am I missing something? How do I specify a variable in keybindings.json command, which itself is a result of another command (a shell command, not a vscode command).

A: In HTML Related Links v0.17.0 is it possible to use a ${command} variable.
Together with the extension Command Variable you can read the file content and use it.
  {
    "key": "numpad3",
    "command": "htmlRelatedLinks.openFile",
    "args": {
      "file": "${workspaceFolder}/${command:mypointer}.py",
      "method": "vscode.open",
      "viewColumn": "2",
      "command": {
        "mypointer": {
          "command": "extension.commandvariable.file.content",
          "args": {
            "fileName": "${workspaceFolder}/pointer.txt"
          }
        }
      }
    }
  }

Command Variable can also read Key-Value files, JSON files, and you can construct a pick list or prompt string, and you can transform the content if needed.


text:
Q: Documentation for nuget API does anyone knows a good documentation for nuget service endpoints?
I'm looking for it for both nuget v2 and v3 (v2 in priority as V3 is still in contruction).

A: Updating several years later: There is now official documentation for the NuGet server API over at microsoft.com.

A: There is no official documentation of NuGet API, but since NuGet is open source, you can take a look here: https://github.com/NuGet/NuGetGallery
The API requests handling code is located in this file:
https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery/Controllers/ApiController.cs


text:
Q: Popup program execution - python I need a simple popup that indicates the execution of the program and disappears when finished. It should only serve to indicate to the user that the script is running. I have PySimpleGUI.

A: This code will popup a window.
import PySimpleGUI as sg

sg.popup('This is my popup message')

Do you want it to "block", waiting for the user to click OK?
You can also have it autoclose after a while.
Or, you can make it not-block and your program will immediately continue executing.
It's all described in the PySimpleGUI documentation under the Popup section.
Here's is code that will show the Popup window.  Your program will NOT block on it and will thus continue running immediately
import PySimpleGUI as sg

sg.popup_non_blocking('This is my popup message')
print('My program continued')

When the program is done running, the window will disappear.
The plain popup function also has a parameter to indicate if you want it to be a non-blocking call that you can use instead of the popup_non_blocking function.  The popup_non_blocking function calls popup with this parameter set for you.


text:
Q: What privileges are required to create a user in Oracle with a non DBA user? What should be the privileges existing on an Oracle User to create a user?
I'm trying to execute the following command from a Java program and hit the following exception multiple times:
Oralce 12.1 Command:
CREATE USER USERTABLE IDENTIFIED BY USERPASSWORD
DEFAULT TABLESPACE MYTABLESPACE
QUOTA UNLIMITED ON MYTABLESPACE

Stacktrace:

Error :java.sql.SQLSyntaxErrorException: ORA-01031: insufficient privileges
Error occurred while processing the request. Error from database server or driver.java.sql.SQLSyntaxErrorException: ORA-01031: insufficient privileges

The following privileges are assigned to the user:
GRANT ALTER ANY INDEX TO dummyuser;
GRANT CREATE ANY TABLE TO dummyuser;
GRANT CREATE SESSION TO dummyuser;
GRANT CREATE TABLE TO dummyuser;
GRANT DROP ANY TABLE TO dummyuser;
GRANT GLOBAL QUERY REWRITE TO dummyuser;
GRANT SELECT ANY TABLE TO dummyuser;
GRANT UNDER ANY TABLE TO dummyuser;
GRANT UNLIMITED TABLESPACE TO dummyuser WITH ADMIN OPTION;

Can someone please let me know if there are any other privileges that needs to be assigned to this user?

A: Chect the CREATE USER priviledge.
But you typically do not create database users using your JDBC client. This is more a static task done by the DBAs.

A: For all the forthcoming issues that I had got, after @Marmite Bomber's answer - I had applied the following change to the user for my JUnits!
GRANT CONNECT, RESOURCE, DBA TO cordysdemo;
commit;

Hope this helps someone!


text:
Q: Удаление элемента Здравствуйте. Подскажите код, как сделать, чтобы удалялся элемент с классом tur.
Все перекопал, не нашел в Интернете.
A: Как один из вариантов.

.tur {
 border: 1px solid #6495ed;
 margin: 5px;
 padding: 5px;
}

Элемент 0

Элемент 1

Элемент 2

<input type="button" value="Удалить Элемент 1" onclick="document.getElementsByClassName('tur')[1].outerHTML = '';">


text:
Q: ¿Como escribir en archivos de sistema? Quiero poder escribir en un archivo que es de sistema y que la única forma de lograrlo es con permisos root (Los tengo pero no funciona incluso).
Mi código
Process proc = Runtime.getRuntime().exec(command);
Toast.makeText(this, "Si", Toast.LENGTH_LONG).show();
OutputStream os = proc.getOutputStream();
byte[] chunk = new byte[CHUNK_SIZE];
int bytesLeidos = 0;

while ( (bytesLeidos = is.read(chunk)) > 0) {

    os.write(chunk, 0, bytesLeidos);
}
os.close();

Les explico mi código: lo único que hace es solicitar permisos root y abre el contenido del fichero y luego trato de escribir en él mediante los métodos convencionales de java.
Mi comando
El comando que uso es su -c cat ruta de archivo


text:
Q: How to use prefix table names with jpa I'm using java play to make a web application and I'm having some trouble persisting data using ebeans and jpa annotations.
I've searched a lot, and I'm a little confused, I think that this is something that should be common, I want to have tables named like this:

*

*company 1_users

*company 2_users

*company N_users
but I want to have only one entity named user, can be possible to have this schema ?
I've searched about using one entity with multiple tables, about using table name prefixes and about using dynamic table name but I got nothing helpful.
Some ideas ??

A: As @GlennLane said in comment,  creating separate tables isn't good idea, instead use some field as a company id/discriminator. You will save tons of nerves, and you won't need to update your code each time when new company joins the branch.
If you really want separate tables create separate model for each company, at least you won't mishmash that in code.


text:
Q: Symfony2 Embedded Form Collection Not Validating I have an entity Company and Address that have their own types CompanyType and AddressType. The AddressType is embedded in CompanyType. I did everything exactly the same as in Embedded Forms cookbook entry. The form is embedded correctly and is showing exactly as it should but validation is not working. I use separate .yml files for validation like this...
        $yamlMappingFiles = $container->getParameter('validator.mapping.loader.yaml_files_loader.mapping_files');
    $yamlMappingFiles[] = __DIR__.'/../Resources/config/validation/address_validation.yml';
    $yamlMappingFiles[] = __DIR__.'/../Resources/config/validation/company_validation.yml';
    $container->setParameter('validator.mapping.loader.yaml_files_loader.mapping_files', $yamlMappingFiles);

... and it is not validating in any of the entities. I tried corrupting the yml files and the parser throws an error which means that it loads the files. I also tried viewing var_dump($form->getErrors()); but it returns an empty array. At the same time, if i leave all blank fields in forms, the form isn't validated. Code is not entering here...
if( $form->isValid() ) {
    ... does not enter here if all input elements are empty ...
}

If I'm not mistaken, if no validation is used on a form, the form is always valid, so this must mean that validation .yml files are processed.
I didn't post any code beacuse my form is exactly the same as in the cookbook example. Just imagine that Task is Company and Tag is Addres.
Any ideas?