Q:

Where should the CSS transition property go?

When creating a CSS Transition for an element, should the transition property be applied to the element's existing class (or id or selector) or to the new class that causes the transition? It works either way I believe, but is one way better than the other and why?
JSFiddle

.box {
    height: 100px;
    width: 100px;
    background: blue;
}

/* background-change class to be added to the element with the box class */
.background-change {
    background: red;
    /* Should this be under .background-change or .box? */
    transition: background 2s;
}

A:

You can use both of these variants, they're both OK. But you should understand the difference between them.
If you set transition property to new/separate class, your transition will be applied only when you set this class:
JSFiddle

$('.box').hover(function() {
    $(this).toggleClass('background-change');
});
.box {
    height: 200px;
    width: 200px;
    background: green;
}

.background-change {
    background: red;
    transition: background 2s;
}

Hover it to change background

But if you set transition property to main/existing class, your transition will be applied also when you remove class:
JSFiddle

$('.box').hover(function() {
    $(this).toggleClass('background-change');
});
.box {
    height: 200px;
    width: 200px;
    background: green;
    transition: background 2s;
}

.background-change {
    background: red;
}

Hover it to change background

I prefer to use the last variant because it looks better and consistently.


Q:

Android - Draw border around ImageView

I have defined an imageView and it I want to do two actions: Round its edges and draw a colored border around the bitmap. First I get it well, but the second one does not.
This is what I have done with canvas:
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm, 150, 150, false);

    int min = Math.min(resizedBitmap.getWidth(), resizedBitmap.getHeight());

     Bitmap bitmapRounded = Bitmap.createBitmap(min, min, resizedBitmap.getConfig());

                Canvas canvas = new Canvas(bitmapRounded);
                Paint paint = new Paint();
                paint.setAntiAlias(true);
                paint.setShader(new BitmapShader(resizedBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
                canvas.drawRoundRect((new RectF(0.0f, 0.0f, min, min)), min / 2, min / 2, paint);

    avatar.setImageBitmap(bitmapRounded);

    //I tried this, but don't work.
    avatar.setPadding(1, 1, 1, 1);
    avatar.setBackgroundColor(getResources().getColor(R.color.negro));

Thanks you!

A:

you can get rounded corner bitmap wirh border like below
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int color, int cornerDips, int borderDips, Context context) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int borderSizePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) borderDips,
                context.getResources().getDisplayMetrics());
        final int cornerSizePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) cornerDips,
                context.getResources().getDisplayMetrics());
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        // prepare canvas for transfer
        paint.setAntiAlias(true);
        paint.setColor(0xFFFFFFFF);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(rectF, cornerSizePx, cornerSizePx, paint);

        // draw bitmap
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        // draw border
        paint.setColor(color);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth((float) borderSizePx);
        canvas.drawRoundRect(rectF, cornerSizePx, cornerSizePx, paint);

        return output;
    }


Q:

Docker Private Registry Image Upload

I'm trying to upload images to my private docker registry using the HTTP API, unfortunately without success.
Apparently I haven't understood the upload process yet and would like to ask if anyone can explain this in detail or push me in the right direction.
So far I have tried the following with curl. To experiment I only use the empty alpine image.
For that i download it to my workstation with docker pull alpine and then I create tar archive with docker save -o alpine.tar alpine
I then unpack this archive into an alpine directory. This is what the content looks like:
ls -R alpine
alpine:
    39cb81dcd06e3d4e2b813f56b72da567696fa9a59b652bd477615b31af969239
    e7d92cdc71feacf90708cb59182d0df1b911f8ae022d29e8e95d75ca6a99776a.json
    manifest.json

alpine/39cb81dcd06e3d4e2b813f56b72da567696fa9a59b652bd477615b31af969239:
    json
    layer.tar
    VERSION

According to the documentation I should first initiate the upload by sending a POST to the /v2//blobs/uploads/ URL, for this I execute the following command:
curl -X POST -L -D headers $DOCKER_HOST/v2/alpine/blobs/uploads
The answer is the following:
cat headers
HTTP/1.1 301 Moved Permanently
Docker distribution api version: registry/2.0
location: /v2/alpine/blobs/uploads/
Date: Tu, 21 Jan 2020 12:42:55 GMT
content length: 0

HTTP/1.1 202 Accepted
content length: 0
Docker distribution api version: registry/2.0
Docker upload guide: ed595b3c-1236-46c8-a759-14187fc60e7d
Location: http://<IPADDRESS>/v2/alpine/blobs/uploads/ed595b3c-1236-46c8-a759-14187fc60e7d?_state=GjzU_y-YDQherf4xXO57KyEonSSSwNEM8FiF8rmNfuN7Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiZWQ1OTViM2MtMTIzNi00NmM4LWE3NTktMTQxODdmYzYwZTdkIiwiT2Zmc2V0IjowLCJTdGFydGVkQXQiOiIyMDIwLTAxLTIxVDEyOjQyOjU1LjMxNDYzNTg0NVoifQ%3D%3D
Range: 0-0
X Content Type Options: nosniff
Date: Tu, 21 Jan 2020 12:42:55 GMT

now i would like to do a monolithic upload, as described in the docker-registry documentation.
For this I make the following curl request:
url=http://<IPADDRESS>/v2/alpine/blobs/uploads/ed595b3c-1236-46c8-a759-14187fc60e7d?_state=GjzU_y-YDQherf4xXO57KyEonSSSwNEM8FiF8rmNfuN7Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiZWQ1OTViM2MtMTIzNi00NmM4LWE3NTktMTQxODdmYzYwZTdkIiwiT2Zmc2V0IjowLCJTdGFydGVkQXQiOiIyMDIwLTAxLTIxVDEyOjQyOjU1LjMxNDYzNTg0NVoifQ%3D%3D?digest=sha256:39cb81dcd06e3d4e2b813f56b72da567696fa9a59b652bd477615b31af969239

layerpath=/home/user/alpine/39cb81dcd06e3d4e2b813f56b72da567696fa9a59b652bd477615b31af969239/layer.tar

curl -X PUT -H "Content-Type=application/octet-stream" --data-binary @"$layerpath"  $url

For this I receive an answer that means nothing to me:
 {"errors":[{"code": "BLOB_UPLOAD_INVALID", "message": "blob upload invalid", "detail":212}]}

I don't know what I'm doing wrong. For any help I am very grateful.

A:

Okay, I figured it out.
For all the others who are also dealing with this question here is a little script which should clarify the handling of the HTTP-Api:
#!/bin/bash

# Global Variables

MANIFEST="./Manifest.json"

DOCKER_HOST=$1
REPOSITORY=$2
LAYERPATH=$3
CONFIGPATH=$4

SIZE=
DIGEST=

LOCATION=

CONFIGSIZE=
CONFIGDIGEST=
LAYERSIZE=
LAYERDIGEST=

# Functions

function initiateUpload(){
   LOCATION=$(curl -X POST -siL -v  -H "Connection: close" $DOCKER_HOST/v2/$REPOSITORY/blobs/uploads | grep Location | sed '2q;d' | cut -d: -f2- | tr -d ' ' | tr -d '\r')
}

function patchLayer(){
    layersize=$(stat -c%s "$1")
    LOCATION=$(curl -X PATCH -v -H "Content-Type: application/octet-stream" \
        -H "Content-Length: $layersize" -H "Connection: close" --data-binary @"$1" \
        $LOCATION 2>&1 | grep 'Location' | cut -d: -f2- | tr -d ' ' | tr -d '\r')
    SIZE=$layersize
}

function putLayer(){
    DIGEST=sha256:$(sha256sum $1 | cut -d ' ' -f1)
    url="$LOCATION&digest=$DIGEST"
    curl -X PUT -v -H "Content-Length: 0" -H "Connection: close" $url

}

function uploadManifest(){
    ((size=$(stat -c%s "$MANIFEST")-1))
    curl -X PUT -vvv -H "Content-Type:   application/vnd.docker.distribution.manifest.v2+json"\
    -H "Content-Length: $size" -H "Connection: close" \
    -d "$(cat "$MANIFEST")" $DOCKER_HOST/v2/$REPOSITORY/manifests/latest
}

# Check Parameters

if [ $# -lt 4 ]
    then
        echo "Error: No arguments supplied."
        echo "Usage: upload.sh <DOCKER_HOST> <REPOSITORY> <LAYER> <CONFIG>"
       exit 1
fi

#upload Layer
initiateUpload
patchLayer $LAYERPATH
LAYERSIZE=$SIZE
putLayer $LAYERPATH
LAYERDIGEST=$DIGEST

#upload Config

initiateUpload
patchLayer $CONFIGPATH
CONFIGSIZE=$SIZE
putLayer $CONFIGPATH
CONFIGDIGEST=$DIGEST

cat > $MANIFEST << EOF
{
   "schemaVersion": 2,
   "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
   "config": {
       "mediaType": "application/vnd.docker.container.image.v1+json",
       "size": $CONFIGSIZE,
       "digest": "$CONFIGDIGEST"
   },
   "layers": [
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size":$LAYERSIZE,
            "digest": "$LAYERDIGEST"
        }
    ]
 }
 EOF

 uploadManifest

It's not pretty, but it works for that.
If you need more information, I will gladly extend this answer


Q:

Set a variable and print it, without any threads, but it prints the old value?

I have a simple piece of Java code:
class A {
    static {
        int x=3;
        int y;
        int yy=1234;
        int yyy;y=1;int zy=x;
        System.out.println("x: "+x);
    }
}

I'd expect it to print "x: 1234".
javac A.java && java A
x: 3
Exception in thread "main" java.lang.NoSuchMethodError: main

But instead it prints "x: 3". Why? Is this another type of optimization I don't know about like volatile? I thought volatile only matters if you have multiple threads? I tried setting all variables to volatile, and even putting locks around them, but no luck. Someone told me I should set strictfp on the class, but no luck there either.

A:

You have characters that make displaying weird.
Actual code:
  1 class A {
  2     static {
  3         int x=3;
  4         int y<202d>;
  5         int yy=1234;
  6         int yyy<202e>;y<202d>=1;int z<202e>y=x;
  7         System.out.println("x: "+x);
  8     }
  9 }

<202e> is called "right-to-left override"
<202d> is "left-to-right override"


Q:

privilege dropping possible in Javascript?

I wonder if it would be possible to drop privileges in Javascript?

function takeAwaySetTimeout()
{
  var oldSetTimeout = window.setTimeout;
  window.setTimeout = function()
  {
    console.log("not working anymore!");
  };
}

setTimeout("console.log('this works');",0);  // "this works!"
takeAwaySetTimeout();
setTimeout("console.log('this works');",0);  // "not working anymore!"

unfortunatelly it seesm to me complicated as a simple delete window.setTimeout will bring back the priviledge! So for me this seems indicative to the fact that unfortunatelly Javascript would not provide for taken away privileges.
I am aware that the term privilege is somewhat borrowed.
It is the background to the question that I would conceive any possiblity to workingly remove a [Native Code] function (= that the method .toSource() indicates its an function provided by the javascript engine) from being accessible in some part as a way to secure the code subjected to this limitation (the privileges are dropped) from being less of a safety concern.
clarification
I welcome your request for more clarity, and hope your will respond to it responsibly and de-hold "free" the question!
Please also consider that having received indeed already two helpful answers shows that, there are people who were able to understand the question. Yet sure, if possible (something simply need background....) I also strive for broadening the understanding.
"It's a bit unclear how restricting access to native functions would give more security. Is
this server-side or client-side JavaScript?"
1) it does not very much matter if client or server-side. Maybe a tiny little bit more important seems of course server-side. Because there is likely likely more functionality (i.e. writing to files, access files.....), more then maybe the more limited Javascript inside of Browser would be able to do (but consider new API's power ...and risks!)
2) maybe the choice for window.setTimeout() [Native function] is not perfect (for clarity), as maybe no direct security relationship is obvious. It has been used because it is well known and it is placeholder. see (3)
3) my reasoning is that each functionality that is provided to Javascript code is ambivalent. On the pro side, it enriches "what it can do?" positively and well-meaning code will use it responsible. Yet on the con side a functionality can mean access to things which when abused can cause security related stuff. An example would be that an external Javacript would do a XHR and post information to the server, potentially data that has private data (i.e. customers health state). If then for example it was possible to take away the XHR object better window.XMLHttpRequest the chances for such an abuse would be limited. Plainly "you cannot shoot somebody, not having a gun!". XHR for instance (maybe more clearly than setTimeout) is such a gun. If the "untrusted code" is not really needing XHR, then it is just good sense to take the risk away, by dropping this privilege/functionality.
4) I think (also in the context of the replies) this question has evolved. I think it is clear, yet please post comment if not so. While initially Juhana said:

It's a bit unclear[...]

I understand that it was not totally unclear, and hence now it might have reached enough clarity (please consider the helpful answers) to allow for "deholding"/"freeing the Question". Also if you found the question interesting enough to hold it, then now would be the time to find it interesting enough to upvote it ;)

A:

There are so many ways to get the original function and blacklisting can't work because you'll miss something e.g.
Window.prototype.setTimeout.call(window,'alert(1)');

One solution to this problem is to create a whitelisted sandbox. I've created such a sandbox called MentalJS. This sandbox rewrites all your code with a suffix of $ for example alert(1) becomes alert$(1) this allows you to choose which functions/objects are allowed within the sandbox.
The code is available here:
http://code.google.com/p/mentaljs/
and a demo:
http://businessinfo.co.uk/labs/MentalJS/MentalJS.html


Q:

Count occurences of a substring in a string

im struggling to figure out where the error in my code is;
here is my test:
@Test
public void testCountOccurences()
{
    assertEquals(1, sc1.countOccurences("ence"));
    assertEquals(2, sc1.countOccurences("en"));
    assertEquals(1, sc2.countOccurences("that"));
    assertEquals(0, sc2.countOccurences("This"));
}

here is my method:
public int countOccurences(String t)
{
    int j = 0;
    int i;
    for(i = 0; i < sentence.length(); i++)
    {
         String subString = sentence.substring(i, i + t.length());
         if(subString.equals(t))
            {
                j++;
            }
    }
    return j;
}

A:

I am going to assume that you're doing this as an exercise.
It seems that you are going off the end of the original string.
Try changing for(i = 0; i < sentence.length(); i++) to for(i = 0; i < sentence.length() - t.length(); i++).


Q:

How to define API keys in restFul meteor?

I am new to rest api in meteorjs. I am trying to run the example explained in The meteor chef  but getting this error:
ReferenceError: APIKeys is not defined
    at Object.API.authentication (api/config/api.js:4:19)
    at Object.API.connection (api/config/api.js:16:34)
    at Object.API.handleRequest (api/config/api.js:28:26)
    at [object Object].Router.route.where (api/pizza.js:9:9)
    at boundNext (packages/iron_middleware-stack/lib/middleware_stack.js:251:1)
    at runWithEnvironment (packages/meteor/dynamics_nodejs.js:110:1)
    at packages/meteor/dynamics_nodejs.js:123:1
    at [object Object].urlencodedParser (/Users/mac/.meteor/packages/iron_router/.1.0.12.13720an++os+web.browser+web.cordova/npm/node_modules/body-parser/lib/types/urlencoded.js:84:40)
    at packages/iron_router/lib/router.js:277:1
    at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1)

The code is same as explained in the example

A:

It is because you didn't created APIKeys mongo collection as shown here: https://github.com/themeteorchef/writing-an-api/blob/master/code/collections/api-keys.js
Add this file to your project and then it'll work.
Here is explanation from post you linked:

Next, we try to insert a new key for our user into the APIKeys collection. Wait a minute! Where did this come from?! This collection was setup beforehand, but let’s talk about why we have a separate collection to begin with. The reason we want to separate our API key storage from the more predictable location of our user’s profile (the writable portion of a user’s record in the Meteor.users() collection) is that by default, the profile object is writable.

So you just missed this part of tutorial where they created APIKeys collection.


Q:

angular-material css leaks to other div

I want to use Angular Material's md-autocomplete in my angular application. I already have a modified css which my application is using. But adding the angular material css screws up my entire page.
I tried scoping the css to only that div. But still it somehow overrides the parent css also.
This is how I used the css in my page :

I thought the above would scope the css only to that div. But it somehow leaks to the other divs as well.
Also I tried to remove parts of the original css so that I leave only the styles that the md-autocomplete uses. But this is really tiring and also the results are not great as well.
Please help me how to use the md-autocomplete in my original html file.

A:

what you are trying to do is not possible in css see below code

  some text

  another text

earlier it was possible in css with

however you could use CSS preprocessor like less or sass
.your-class {
    @include 'style.css';
}

for more details you can refer Link external CSS file only for specific Div
hope i answered your question


Q:

Preguntas sin investigación y con respuesta aceptada ¿Deben permanecer abiertas o cerradas?

El día de hoy intente mejorar una pregunta del sitio principal, la cual también le asigne mi voto de cierre por demasiado amplia(no lo recuerdo muy bien), pregunta en cuestión es la siguiente: Ejecutar función si se vacía un textarea, la cual le puse como comentario al OP lo siguiente:

Hola no eres un usuario nuevo, lo cual ya sabes como se pregunta por
  aquí te invito a mirar nuevamente Cómo preguntar y también procura
  agregar un Ejemplo mínimo, completo y verificable.

El me respondió el comentario diciendo algo así (el comentario fue eliminado):

¿como puedo poner un ejemplo cuando ni siquiera tengo idea de como hacerlo?

proseguí invitándolo a realizar una búsqueda en Google.

como puedo poner ejemplos: ¿Qué investigación has hecho?, en Google
  puedes encontrar información básica, como dice en Cómo preguntar
  "Busca e investiga", tus búsquedas se pueden volver un ejemplo aunque
  no funcione

Después vuelvo a entrar y veo que mi voto ha sido retirado, veo el timeline y aparece que fue cerrada por un moderador y reabierta.
Platicando por el chat con el moderador me comenta:

la cerré porque lo que le pusiste tiene bastante sentido sin embargo
  la reabrí porque vi que tenía respuestas y una de ellas ya estaba
  aceptada.

No estoy del todo de acuerdo con lo que me responde, debido a que he visto preguntas muy similares y terminan cerradas aunque tengan respuesta aceptada. un ejemplo puede ser esta: Validar campos vacios C#, entre otras que no encuentro.

A:

El estado de una pregunta debe ser independiente de si se solucionó el tema o no. Si es demasiado amplia, lo seguirá siendo a pesar de que tenga respuestas.
Creo que es importante ser consistentes en nuestra gestión de cerrado de preguntas. Si tenemos unas líneas maestras, sigámoslas. De esta forma se evitará caerá en agravios comparativos (¿Por qué me cierran esta si aquella otra no se cerró? y demás).
Probablemente lo más pertinente aquí sería:

Cerrarla como demasiado amplia, porque lo es.
Dejarla visible (no borrarla1, vaya) porque el contenido parece ser útil.

Así trasladamos a los futuros usuarios la idea de que ese tipo de preguntas necesitan mejor enfoque.
Pero esperemos a ver qué comenta el moderador, pues lo mismo pasé algo por alto :)

1: La pregunta no será borrada de forma automática pues la respuesta ha sido aceptada y cuenta con varios votos positivos.


Q:

Which tags for questions on texts?

Right now we have the following tags that are related to buddhist texts.

pali-canon x  13
sutras x 9
texts x 8
scripture x 2
canon x 2
buddhist-text x 1

Most seem rather redundant to me, but which tags should we mark as synonym?
Personally I'm in favor of keeping pali-canon  for questions about the pali canon in general and sutras for questions about specific buddhist texts. We can mark texts, scripture and buddhist-text as synonym of sutras. The one tag I'm not sure what to do with is canon

A:

Great suggestion! I would make canon a synonym of pali-canon (is there any other canon in Buddhism?)
Not all texts belong to either pali-canon or sutras though, even in Theravada e.g. Milinda-panha, Visuddhimagga. Plus, there are Mahayana & Vajrayana texts that are not sutras.
One approach is to standardize on texts as the most encompassing tag, to be accompanied by another tag specifying a school e.g.

early-buddhism texts
theravada texts
mahayana texts
tibetan-buddhism texts


Q:

How do I 'zoom' a graph so all the nodes are in the browser window?

The graph loads in my browser but I have to scroll all around to see the nodes. How do I zoom in and out?

A:

It is explained in https://neo4j.com/developer/kb/how-do-i-zoom-in-out-within-the-graph-visualization-of-the-browser/
So :

Make browser window become full screen
Use magnifying glass icon

Hope this helps.
Regards,
Tom


Q:

Average sequence rows MATLAB one column at a time

I have an array of data that is in variable m1 that is a 288 X 13 array.  I need to average 24 rows in sequence 12 times for each column.  I have tried many times to use this index we by calculating an average but I'm getting incorrect answers.  My desired outcome (meanf1) is a 12 X 13 array showing the averages in 12 rows for each column of data.  Thanks!
we = 1    25    49    73    97   121   145   169   193   217   241   265

    for ii = 1:13;
        for jj = 1:12;
            meanf1(jj,ii) = mean(m1(we(jj):we(jj)+23,ii));
        end;
    end`

A:

Given the regular spaced intervals created by we, you can reshape and then use mean, like so -
meanf1 = reshape(mean(reshape(m1(1:288,1:13),24,[]),1),12,13);


Q:

Ruby - Passing instance variables to a class from another

I have 3 classes: Invoice, Address and Customer (but for this problem, only the Invoice and Address class are relevant)
This is my Invoice class:
class Invoice
  attr_reader :billing_address, :shipping_address, :order

  def initialize(attributes = {})
    @billing_address = attributes.values_at(:billing_address)
    @shipping_address = attributes.values_at(:shipping_address)
    @order = attributes.values_at(:order)
  end
end

and this is my Address class:
class Address
  attr_reader :zipcode, :full_address

  def initialize(zipcode:)
    @zipcode = zipcode

    url = 'https://viacep.com.br/ws/' + zipcode.to_s + '/json/'
    uri = URI(url)
    status = Net::HTTP.get_response(uri)
    if (status.code == "200")
      response = Net::HTTP.get(uri)
      full_address = JSON.parse(response)
      @full_address = full_address
    else
      p "Houve um erro. API indisponível. Favor tentar novamente mais tarde."
      @full_adress = nil
    end
  end
end

And this is my Customer class (not much relevant, but i'm showing for better explanation of the problem)
class Customer
  attr_reader :name, :age, :email, :gender

  def initialize(attributes = {})
    @name = attributes.values_at(:name)
    @age = attributes.values_at(:age)
    @email = attributes.values_at(:email)
    @gender = attributes.values_at(:gender)
  end

end

As you can see, my Invoice class has 3 instance variables and my Address class has 2 instance variables.
So, if i test something like that:
cliente = Customer.new(name: "Lucas", age: 28, email: "abc@gmail.com", gender: "masculino")
endereco = Address.new(zipcode: 41701035)
entrega = Invoice.new(billing_address: endereco, shipping_address: endereco)

p endereco.instance_variables

[:@zipcode, :@full_address]

p entrega.shipping_address.instance_variables

[]

My instance variables can be acessed through the variable "endereco", that is an Address object, but can't be acessed through entrega.shipping_address that is also an Address object.
To be more precise, if a try this:
p entrega.shipping_address

I get this return:
[#<Address:0x00000001323d58 @zipcode=41701035, @full_address={"cep"=>"41701-035", "logradouro"=>"Rua Parati", "complemento"=>"", "bairro"=>"Alphaville I", "localidade"=>"Salvador", "uf"=>"BA", "unidade"=>"", "ibge"=>"2927408", "gia"=>""}>]

My full object are being returned, but i can't access the content of my @full_address instance variable.
If a do this:
p entrega.shipping_address.full_address

I get a NoMethodError:
solucao.rb:8:in `<main>': undefined method `full_address' for #<Array:0x000000012d25e8> (NoMethodError)

I'm trying to understand why i can't access the content inside my object if i have the full object. Maybe i'm trying to access in the wrong way, i don't know.
Can someone help ?

A:

If you take a look at the error, it says
undefined method `full_address' for #<Array:0x000000012d25e8>

You're trying to call full_address on an array. So this means that entrega.shipping_address returns you an array (which it does, of course, take a closer look at the output).
If I were you, I'd look into how shipping_address is implemented. It's a simple attr_reader, so it's backed by an instance variable. Must be you initialize that instance variable to a wrong value (it gets an array instead of an address). Look closely at that initialization code and try to run it in IRB session. You should see the problem.

A:

values_at returns an array of values (see https://apidock.com/ruby/Hash/values_at
for explanation)
Change
@shipping_address = attributes.values_at(:shipping_address)

into
@shipping_address = attributes[:shipping_address]

And that way @shipping_address will contain an Address object, not an array that contains an Address object


Q:

Regarding MAINFRAME bin files , how to read/compare any bin files?

I am planning to create a sample application in .NET WPF which reads MAINFRAME bin files, compare files side by side and extract file content without losing any formatting.
Below questions would really be helpful for me to create an algorithm.

What were general encoding standards of a typical MAINFRAME bin file?
How we read a bin file, do we need to use any tool?
How do we find differences between two MAINFRAME bin files?
Will we be able to identify a MAINFRAME bin file without using any tool – meaning from file itself?
What kind of output files are generated/read by MAINFRAME , meaning is it restricted to generate only “.bin” file or any other extension as well?

Please also provide me any open source editor which does the reading/writing/editing of a MAINFRAME bin file which can be a starter.
Record editor is one of the application which I use for some of my bin files although it seems to be incompatible for some bin files.

A:

There is no such thing as a "MAINFRAME bin file" - mainframe datasets neither have the concept of filetypes nor of file-extensions. After transfering files from the mainframe to some Windows/Unix-machine some people use the .bin-extension to indicate that the content should be treated as binary.
Some things you should know about mainframe-files (I'm mostly talking of fixed-recordlength sequential datasets, the most basic kind of dataset):

There is no common file-format, usually each mainframe-program rolls its own record-descriptions and writes those to a file. To make sense of the file you have to know the record-description.
You can read those files with any tool that is able to process an arbitrary sequence of bytes - but again: to make use of it you must interpret those bytes somehow.
Mainframe-datasets don't have some newline-character(s) to indicate the end of one data-record and the beginning of the next. Most datasets used for transfer have a fixed number of bytes per record, so the reading program has to split the read bytes at appropriate places. (There are also varying-recordlength-files, but I'll skip these for now).
Character-data on mainframes is usually encoded using some EBCDIC-characterset opposed to ASCII as used on PC-platforms. So you'll have to convert those for PC-based processing
Other sections might contain packed-decimal numeric data - each digit occupies a half byte ("nibble") and the last nibble indicates the sign of the number. E.g. -4387 might be stored in 3 bytes as 04 38 7D.
Your files might also contain raw binary or floating-point data - we can't tell, you'll have to ask the creator of the file.

To sum it up:

you can't recognize or process them with some out-of-the-box-tool
you have to know the record-description to do anything useful
you'll have to cope with lots of mainframe-specific stuff

For most usecases, transferring raw binary files from mainframe to PC is not feasible. Better create EBCDIC-text-based files on the mainframe, use your filetransfer-tool to convert them to ASCII while transferring and process the text-data.


Q:

How to use array of another view controller class?

I need to use the order array in another class (AddOrderVievContoller.swift class)
class OrderListViewController: UITableViewController {

    var orders: [Order] = []

error message in AddOrderVievContoller.swift class: use of unresolved indentifier 'orders'

if results != nil {
    orders = results as! [Order]
}

A:

Create a global variable:
public var orders = [String]()
place this in-between the modules your importing (import UIKit) and the class definition:
import UIKit

public var orders = [String]()

class OrderListViewController: UITableViewController {

//viewDidLoad, etc.
}

Then you can access the orders array in different viewControllers as you're currently trying to do.


Q:

Deleting the first list item if it contains a specified number of items

I am practicing the imitation of a bash console, I am practically at the very end, although there is a problem. I need to always delete the first element of the .bash-line class if the total number of elements exceeds the given value.
I have created a function for this, unfortunately - it removes the first element, but does not add the next one. What can I do to change that?

function animateConsole(string) {

  var bash = $('

');

  $("#console-content").append(bash);
    var typed = new Typed(bash.get(0), {
      strings: [string],
      typeSpeed: 10,
      showCursor: false,
  });

}

function deleteFirst() {

  if($('.bash-line').length == 2) {

    $(".bash-line").each(function() {
      $(this).first().remove();
    });

  }

}

$(document).ready(function() {

  setTimeout(function() {animateConsole('//GET CONNECTION SECRET');}, 1000);
  setTimeout(function() {animateConsole('//SENDING REQUEST'); deleteFirst();}, 2000);
  setTimeout(function() {animateConsole('//WAITING FOR RESPONSE');}, 3000);

});

A:

You don't need to foreach on every found elements to remove the first element of a set of jQuery elements, just do:
$("#console-content p.bash-line").first().remove();
You can also check the jquery first method documentation: https://api.jquery.com/first/
Here's the full working example:

function animateConsole(string) {
    var bash = $('

');

    $("#console-content").append(bash);

    deleteFirst();
    var typed = new Typed(bash.get(0), {
        strings: [string],
        typeSpeed: 10,
        showCursor: false,
    });
}

function deleteFirst() {
    if($('.bash-line').length > 2) {
        $("#console-content p.bash-line").first().remove();
    }
}

$(document).ready(function() {
    setTimeout(function() {animateConsole('//GET CONNECTION SECRET');}, 1000);
    setTimeout(function() {animateConsole('//SENDING REQUEST');}, 2000);
    setTimeout(function() {animateConsole('//WAITING FOR RESPONSE');}, 3000);
});


Q:

Adafruit_BBIO.ADC.setup() error on Debian 9.2

While my question is similar to Adafruit_BBIO.ADC.setup() on ubuntu 16.04.1 error, the answer provided in that question does not solve my problem.
I'm running the below Python script on a Beaglebone Black.
import Adafruit_BBIO.ADC as ADC
ADC.setup()

#read returns values 0-1.0
value = ADC.read("P8_8")

My board is set up so that I have a 3.3V output running through a voltage divider, and I'm measuring the voltage at a point in the divider where it should read 1.65V.  However, when I run the above code, I get the following.
Traceback (most recent call last):
  File "/var/lib/cloud9/examples/LED_flash/adc_test.py", line 2, in <module>
    ADC.setup()
RuntimeError: Unable to setup ADC system. Possible causes are:
  - A cape with a conflicting pin mapping is loaded
  - A device tree object is loaded that uses the same name for a fragment: helper

I've updated Adafruit_BBIO to the most recent version (1.1.1) and the error persists.  I've also tried following a suggestion from here, which I got to from this Github listing of the same problem as a bug sometime last year.  When I ran the code there, I got the following result.
sudo sh -c "echo BB-ADC' > /sys/devices/platform/bone_capemgr/slots"
bash: /sys/devices/platform/bone_capemgr/slots: Permission denied

So, I'm kinda perplexed and would love to have an idea of where to go next.  Any help is appreciated.

A:

Credit to Robert Nelson on the Beaglebone Black forums.
The /boot/uEnv.txt file was modified and needed to be changed such that the following lines were present as written below.
enable_uboot_overlays=1
#disable_uboot_overlay_adc=1


Q:

Custom Thread Pool - runnable called without calling start()

I was trying to understand for custom thread pool implementation as explained in https://www.roytuts.com/custom-thread-pool-in-java/. After polling out of task queue as
while ((r = taskQueue.poll()) != null) {
          r.run();
       }

the code is directly calling run method without calling start() first. So, i am bit confused how runnable can be started without creating thread on runnable and then call start method? Can anyone please clear out my confusion where i am lacking the understanding. Thanks
class CustomThreadPool {
    // holds tasks
    private BlockingQueue<Runnable> runnableQueue;
    // holds the pool of worker threads
    //private List<WorkerThread> threads;
    // check if shutdown is initiated
    private AtomicBoolean isThreadPoolShutDownInitiated;
    public CustomThreadPool(final int noOfThreads) {
        this.runnableQueue = new LinkedBlockingQueue<>();
        //this.threads = new ArrayList<>(noOfThreads);
        this.isThreadPoolShutDownInitiated = new AtomicBoolean(false);
        // create worker threads
        for (int i = 1; i <= noOfThreads; i++) {
            WorkerThread thread = new WorkerThread(runnableQueue, this);
            thread.setName("Worker Thread - " + i);
            thread.start();
           // threads.add(thread);
        }
    }
    public void execute(Runnable r) throws InterruptedException {
        if (!isThreadPoolShutDownInitiated.get()) {
            runnableQueue.put(r);
        } else {
            throw new InterruptedException("Thread Pool shutdown is initiated, unable to execute task");
        }
    }
    public void shutdown() {
        isThreadPoolShutDownInitiated = new AtomicBoolean(true);
    }

    private class WorkerThread extends Thread {
        // holds tasks
        private BlockingQueue<Runnable> taskQueue;
        // check if shutdown is initiated
        private CustomThreadPool threadPool;
        public WorkerThread(BlockingQueue<Runnable> taskQueue, CustomThreadPool threadPool) {
            this.taskQueue = taskQueue;
            this.threadPool = threadPool;
        }
        @Override
        public void run() {
            try {
                // continue until all tasks finished processing
                while (!threadPool.isThreadPoolShutDownInitiated.get() || !taskQueue.isEmpty()) {
                    Runnable r;
                    // Poll a runnable from the queue and execute it
                    while ((r = taskQueue.poll()) != null) {
                        r.run();
                    }
                    Thread.sleep(1);
                }
            } catch (RuntimeException | InterruptedException e) {
                throw new CustomThreadPoolException(e);
            }
        }
    }
    private class CustomThreadPoolException extends RuntimeException {
        private static final long serialVersionUID = 1L;
        public CustomThreadPoolException(Throwable t) {
            super(t);
        }
    }
}

public class ThreadPoolTest {
    public static void main(String[] args) throws InterruptedException {
        Runnable r = () -> {
            try {
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + " is executing task.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        CustomThreadPool threadPool = new CustomThreadPool(2);
        threadPool.execute(r);
        threadPool.execute(r);
        threadPool.shutdown();
        // threadPool.execute(r);
    }
}

A:

Your thread pool class calls thread.start() which calls runnable.run() by calling thread.run(). The last method is designed for threads initialized with runnable and can be called directly or via start().
According to Oracle docs: start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
EDIT
Calling runnable.run() method simply synchronously executes runnable on the current thread (in which the method was called). In your case it is separate ones (which are created in CustomThreadPool). You can call run() directly in main(), which will synchronously execute the runnable on the main thread. Generally, the example is not breaking any concepts of using runnables, since it executes them on separate threads.
To make a long story short: asynchronous behavior is achieved by executing runnables on different threads. In scope of a single thread, calling multiple runnables' run() will execute them synchronously one by one.


Q:

What were the needs of the US Navy that resulted in the production of both the Arleigh Burke class and Ticonderoga class in the 1980s?

In the 1980s the United States Navy introduced both the Arleigh Burke class and the Ticonderoga class.

Wikipedia pages on them:
https://en.wikipedia.org/wiki/Arleigh_Burke-class_destroyer#Development
https://en.wikipedia.org/wiki/Ticonderoga-class_cruiser
The length, beam, and tonnage of these vessels is all similar. The Arleigh Burke class is considered a destroyer, whereas the Ticonderoga is considered a cruiser. The top speed of the vessels is also similar. Neither possesses a novel form of propulsion, such as nuclear propulsion.
The armament of the vessels is incredibly similar, notably both carry the Mk 41 vertical launch system. I do notice that Wikipedia lists the "cruiser mark 26" of the Ticonderoga class as having the "Mk 26 missile launcher". This is not part of the Aegis system, which is the modern missile combat system used by the United States Navy.
It seems that these vessels are almost identical in their capabilities and construction.
What were the needs of the United States Navy that resulted in the acquisition of such similar classes of combat vessels? I'm interested mostly in the mindset or "perceived needs" of the Navy. Why would the Navy introduce and continue to construct such similar classes of vessels? Do they differ somehow in their operational capability that is not evident?

A:

The Ticonderoga class was ordered in the 70s as a multi-mission guided missile cruiser capable of handling just about any mission a warship might be asked to do: air defense, tactical and strategic strike, anti-submarine warfare, carrier escort... It was built on the existing Spruance class destroyer hull. (Despite being a destroyer, Spruance destroyers were cruiser-sized; the destroyer/cruiser designation is more about role than size anyway.)
By the late 70s the Ticonderoga ships were considered too expensive to keep building (navy.mil says "about $1 billion each" but doesn't say what year's dollars those are). Their Spruance hull could no longer be easily upgraded with all the topside electronics. A new class was needed.
The Arleigh Burke class was designed to be a cheaper alternative to the Ticonderoga on a new hull with more potential for upgrades but with the same capabilities and still mounting the revolutionary AEGIS Combat System. In the early 90s the last Ticonderoga cruiser was commissioned, whereas the first Arleigh Burkes were just coming into commission.

A:

Short answer:

In addition to the above, the Ticonderoga is a large vessel suited for open ocean, while the Burke is more of a littoral combatant.
Long answer:
The important feature of both vessels was AEGIS, which is a missile system capable of engaging over 50 targets at once. In emergencies, a single button press would fire a missile at any detected target not confirmed friendly using a volley of launches from the Vertical Launch System (VLS).

Note however that early Ticonderogas did not have VLS and instead had a single SM-2 mount, without this volley fire capability:

(source: wikimedia.org)
AEGIS was in response to the highly capable Soviet bombers coming out, with AS-4 and AS-16 air to surface missiles, which would overwhelm US fleets with huge volleys of these weapons. These missiles were not trivial to jam as the earlier Styx missiles used in Arab-Israeli conflicts and would have to be shot down using a long range missile more deadly than earlier SAMs such as Terrier.
Tu-22M3:
http://tropasearmas3.xpg.uol.com.br/TU-22M3-backfire-excel.jpg
Tu-160:
http://www.vlastnihlavou.cz/obrazky/cim-rusko-polekalo-nato-galerie/bila-labut-tu-160-nejmohutnejsi-bombarder-popis-a-dolet.jpg
AEGIS was designed to data link with the Hawkeye, Nimitz class, and F-14 Tomcat systems then coming out, to provide comprehensive air defense of the fleet against these new threats.
F-14:

Intercepting a Soviet Tu-95 Bear:

Hawkeye:

(source: wikimedia.org)
The E-2 Hawkeyes would provide an Airborne Warning And Control System (AWACS) which would alert the rest of the fleet. Tomcats would scramble to intercept the bombers. AEGIS would down any missiles that got through. The Nimitz carriers would coordinate everything through their onboard Combat Information Center (CIC). These systems would all network together to defend the fleet. AEGIS has its own CIC as well, in case it needs it.
Nimitz CIC:

Ticonderoga CIC:

Fortunately, this integrated fleet defense network has never seen major use.
The Arleigh Burke was introduced after the Ticonderoga class. It was an upgraded version incorporating stealth features, such as a radar deflecting design and radar absorbment materials.

The Burke has a CIC. It is placed lower on the waterline than the Ticonderoga, and is thus more protected from an above-waterline missile hit.

The Alreigh Burke is being upgraded to carry SM-6 missiles, which Raytheon claims is capable of intercepting tactical balistic missiles such as the SCUD.

The Alreigh Burke and Ticonderoga carry the same weaponry. The Ticonderoga is larger and suited for open ocean warfare. The Burke is suited for littoral combat in shallow waters, such as the Persian Gulf or Taiwan Strait.
Note that both ships have Tomahawk, Harpoon, ASROC, and 5 inch guns to engange surface (or subsurface, for ASROC) targets. The ships also carry an antisubmarine warfare helicopter carrying torpedoes, and Phalanx Close In Weapon System (CIWS) 20mm cannon as a last line of defense.


Q:

OSSEC | How to add an exception rule

I have the standard syslog_rules.xml (OSSEC 2.6.0).
This is the standard rule for bad words in the /var/log/messages file:
<var name="BAD_WORDS">core_dumped|failure|error|attack|bad |illegal |denied|refused|unauthorized|fatal|failed|Segmentation Fault|Corrupted</var>
.....
<rule id="1002" level="2">
<match>$BAD_WORDS</match>
<options>alert_by_email</options>
<description>Unknown problem somewhere in the system.</description>
</rule>
.....

How can I add or modify this rule that uses $BAD_WORDS, but excludes the auxpropfunc error phrase? That is, something like this:
<match>$BAD_WORDS</match>
<match>!auxpropfunc error</match>
<options>alert_by_email</options>

Any ideas?

A:

Your best option is probably to write a rule to ignore that phrase. You could add something like the following to /var/ossec/rules/local_rules.xml:
<rule id="SOMETHING" level="0">
  <if_sid>1002</if_sid>
  <match>auxpropfunc error</match>
  <description>Ignore auxpropfunc error.</description>
</rule>

You could then run the entire log message through ossec-logtest to see how OSSEC will analyze it. You may need to add another option into this rule, or you may not.

A:

If you have more than one word, you could add something like the following to /var/ossec/rules/local_rules.xml
<var name="GOOD_WORDS">error_reporting|auxpropfunc error</var>

<rule id="100002" level="0">
  <if_sid>1002</if_sid>
  <match>$GOOD_WORDS</match>
  <description>Ignore good_words.</description>
</rule>


Q:

No search results are bound to material table

I'm implementing Angular 2+ Material Table to my web app and I think I got most of it down. However, I am having a little difficulty getting the binding working. Basically, what I want to do is have a bunch of dropdown values and depending which values I select, those values get sent to server via api call to fetch items that match the values I pass. The matching results should be shown in the material table. Unfortunately, with the way I have it set up, nothing gets shown in the material table I currently have. I checked to see if I get values from the api call and I do get the proper values from my api call, so not sure why the binding itself is failing.
Here's my search function and some setup for the mat table:
displayedColumns = ['Store', 'SKU#', 'Department', 'Class', 'Material', 'Style', 'Description', 'LastUpdate', 'Active', 'RetailPrice'];
PRODUCT_DATA: Array<Product>;
dataSource = new MatTableDataSource(this.PRODUCT_DATA);
product: IProduct;

search(selectedDepartment: string, selectedClass: string, selectedMaterial: string, selectedStyle: string, isActive: string,
    productSku: string) {
    this._itemPriceMangerService.getProductsBasedOnSearch(98, productSku, selectedDepartment, selectedClass,
      selectedMaterial, selectedStyle, isActive).subscribe(data => {

        this.product = data;
        this.PRODUCT_DATA = this.product._products;

        this.dataSource.filter = this.storeId + productSku + selectedDepartment + selectedClass +
        selectedMaterial + selectedStyle + isActive; }); }

Here's my search button and material table:

        <button class="search" (click)="search(selectedDepartment.value, selectedClass.value, selectedMaterial.value, selectedStyle.value, selectedActive.value, this.productSku.value)">
            {{ 'Search' | translate }}
        </button>

        <mat-table [dataSource]="dataSource">
        <ng-container matColumnDef="Store">
            <mat-header-cell *matHeaderCellDef > {{Store}} </mat-header-cell>
            <mat-cell *matCellDef="let product">{{product._storeKey}}</mat-cell>
        </ng-container>
        <ng-container matColumnDef="SKU#">
            <mat-header-cell *matHeaderCellDef >  {{ SKU# } </mat-header-cell>
            <mat-cell *matCellDef="let product">{{product._productSkuKey}}</mat-cell>
        </ng-container>
        <ng-container matColumnDef="Department">
            <mat-header-cell *matHeaderCellDef > {{ Department }} </mat-header-cell>
            <mat-cell *matCellDef="let product">{{product._department}} </mat-cell>
        </ng-container>
        <ng-container matColumnDef="Class">
            <mat-header-cell *matHeaderCellDef > {{ Class }} </mat-header-cell>
            <mat-cell *matCellDef="let product">{{product._productClass}}</mat-cell>
        </ng-container>
        <ng-container matColumnDef="Material">
            <mat-header-cell *matHeaderCellDef > {{ Material }} </mat-header-cell>
            <mat-cell *matCellDef="let product">{{product._productMaterial}}</mat-cell>
        </ng-container>
        <ng-container matColumnDef="Style">
            <mat-header-cell *matHeaderCellDef > {{ Style }}</mat-header-cell>
            <mat-cell *matCellDef="let product">{{product._productStyle}}</mat-cell>
        </ng-container>
        <ng-container matColumnDef="Description">
            <mat-header-cell *matHeaderCellDef >  {{ Description}} </mat-header-cell>
            <mat-cell *matCellDef="let product">{{product._description}}</mat-cell>
        </ng-container>
        <ng-container matColumnDef="LastUpdate">
            <mat-header-cell *matHeaderCellDef > {{ LastUpdate }} </mat-header-cell>
            <mat-cell *matCellDef="let product">{{product._lastUpdatedTimestamp}}</mat-cell>
        </ng-container>
        <ng-container matColumnDef="Active">
            <mat-header-cell *matHeaderCellDef > {{ Active }} </mat-header-cell>
            <mat-cell *matCellDef="let product">
              <select>
                <option *ngFor="let active of activeTypes" [ngValue]="active">{{product._isActive}}</option>
              </select>
            </mat-cell>
        </ng-container>
        <ng-container matColumnDef="RetailPrice">
            <mat-header-cell *matHeaderCellDef > {{'RetailPrice'}} </mat-header-cell>
            <mat-cell *matCellDef="let product">{{product._price}}</mat-cell>
        </ng-container>
            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>

When I do a console.log(JSON.stringify(this.PRODUCT_DATA)), this is what I get:
[
   {
      "_storeKey":98,
      "_productSkuKey":12345,
      "_department":234,
      "_productClass":12,
      "_productMaterial":"Material 1",
      "_productStyle":23,
      "_description":"Product Description 1",
      "_lastUpdatedTimestamp":"2018-03-16T13:54:49",
      "_isActive":"Yes",
      "_price":149.95
   }
]

So the data is there, just can't bind it?

A:

You have to update data of your data source whenever you want to update data. So in your case you have to modify search function in this way:
...
this.product = data;
this.PRODUCT_DATA = this.product._products;
this.dataSource.data = this.PRODUCT_DATA;
...

So whenever you are getting updated data from server you have to set in this.dataSource.data. I can also see you are using filter, filter should be used only when you are filtering table locally but I guess in this case you want to perform search server side.


Q:

First slide count doesn't work on clicking next for Bootstrap 4 Carousel

I'm trying to get the slide/total count and got it working somehow. However, when I click next and it goes back to the original first slide, it doesn't show 1/4 but it remains 4/4.
JSFiddel: https://jsfiddle.net/zorw7yLe/
HTML:

 -->>>

Title of the first image

Some description of the first image

Title of the second image

Some description for the second image

Title of the third image

Some description for the third image

Title of the fourth image

Some description for the fourth image

JS:
var totalItems = $('.carousel-item').length;
var currentIndex = $('.carousel-item.active').index() + 1;
var down_index;
$('.num').html(''+currentIndex+'/'+totalItems+'');

    $(".next").click(function(){
    currentIndex_active = $('.carousel-item.active').index() + 2;
    if (totalItems >= currentIndex_active)
    {
        down_index= $('.carousel-item.active').index() + 2;
        $('.num').html(''+currentIndex_active+'/'+totalItems+'');
    }
});

A:

I suggest you use bootstrap carousel events, you don't need to watch the click directly on your link :
https://getbootstrap.com/docs/4.0/components/carousel/#events
var totalItems = $('.carousel-item').length;

$('#carouselExampleIndicators').on('slide.bs.carousel', function (e) {
    $('.num').html((e.to+1)+'/'+totalItems);
});

So your counter will keep track of the current slide
Also, your counter doesn't come back to 1/4 because of your condition (totalItems >= currentIndex_active), at the last slide if you add +2 on your index, that's 5, which is higher than totalItems (4)
You'll need a else to eventualy get the right number, but just use the bootstrap events


Q:

The sequence of polynomials that generates $\sqrt{ x}$

Let $A$ be a unital C*-algebra, and $x\in A^+$. We know $\sqrt{x}$ is a unique square root of $x$, is limit of polynomials generated by $x$.
My question: What is the representation of these polynomials?
I think about using Functional calculus, and find the polynomials that generated the function $\sqrt{x}$. Thought about Maclaurin series, but I could not find anything.
Please advise me. Thanks a lot.

A:

There are many ways to find a sequence of polynomials that converge to a continuous function (the sequence is not unique). In this case, you can consider the polynomials defined inductively by
$$
p_0(t) = 0, p_{n+1}(t) = p_n(t) + \frac{1}{2}[t-p_n^2(t)]
$$
This is a sequence that converges pointwise to $\sqrt{t}$. However, they are also a monotone sequence, so by Dini's theorem, they must converge uniformly on compact sets. Hence, $p_n(x)$ converges to $\sqrt{x}$.
Note that $p_n(0) = 0$ for all $n\in \mathbb{N}$, which is also sometimes useful (if you want to show that $\sqrt{x}$ is a compact operator whenever $x$ is compact, for instance)

A:

Arveson's book on Spectral Theory has exercises that guide you through using the binomial expansion to find the square root of such an $x$ where $\|x\|\le 1$. This proof gives you a square root without requiring positivity, which allows the proof to go through in a Banach algebra. And, if you have positivity such as in a Banach $^*$ algebra or in the operators on a Hilbert space, then the sequence of approximates are positive and monotone. So you get something nice in either case.


Q:

javascript validation - first capital only - how to?

     // Validate Sentence Case
    if(dataEntryCaseId.toString().match("4")){
        var newValue = toTitleCase(value);
        if(newValue != value){
            for(var x = 1, j = value.length; x < j; x++){
                if(value.charAt(x) != newValue.charAt(x)){
                    valid = false;
                    $("#text_10").attr({"value":$("#text_10").attr("value").replace(value.charAt(x), "")});
                    finalVal = finalVal.replace(value.charAt(x), "");
                }
            }
        }
    }

    if(!valid){
        for(var x = 0, j = styleNoteJsonData.styleGroupNote.length; x < j; x++){
            if(styleNoteJsonData.styleGroupNote[x].styleName == styleGroupName){
                alert(styleNoteJsonData.styleGroupNote[x].styleNote);
                $(".styleNote").addClass("alertRed");
                SendErrorMessage(styleNoteJsonData.styleGroupNote[x].styleNote);
            }
        }
    } else {
        $(".styleNote").removeClass("alertRed");
    }

    if(finalVal.length > 0){
        return true;
    }

    return valid;

}

function toTitleCase(str){

        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}).replace(/\s/, '');

}

I need to rework this to only allow the first letter to be capitalized (it doesn't have to be)
I was trying to do this with regex - which i'm not sure is needed if the javascript validation was correct - seefunction toTitleCase(str)
regex seems overkill - but maybe because the current validation is using it, it might be easier to incorporate, but I wanted to see if their were other options within the parameters of the current code.

A:

Your question is not very clear. If you want to only keep the first uppercase, use this function:
function toTitleCase(str){
    return str.charAt(0)+str.substring(1).toLowerCase();
}

Additional notes:
Add str = str.replace(/\s/g,""); before return ... when you want to remove all white-space characters.
If you only want to remove the beginning and ending whitespace characters, add str = str.replace(/^\s+/,"").replace(/\s+$/,""); instead,


Q:

Is there any way to use LaTex formulas in a programming language to make a real calculation

We may write down the calculation formula of a distance measurement with the following LaTex string:
dist_{12} = \sqrt{ x^2 + y^2 }
dist_{13} = \sqrt{ z_{33}^2 + y^2 }

total = dist_{12} + dist_{13}

This looks good so far. If I really need to make a computer calculate these equations, then I need the following - eg. Python - code:
x = 1
y = 2
z_33 = 3
dist_12 = sqrt(x**2 + y**2)
dist_13 = sqrt(z_33**2 + y**2)
total = dist_12 + dist_13
print "Total distance is: ", total

As a result, I spent as twice as the effort actually needed.
However, if there was a way to use exact same LaTex formula (which may include integrals, derivatives, limits etc.) in a programming language (preferably Python, Javascript and Julia) we would re-use our efforts later in our real-world applications.
Is there any way to make this happen?

A:

You can

Use latex2sympy to translate latex equations to SymPy objects
Just use SymPy printing tools to get the same equations as latex

Both alternatives avoid you having to re-type the equations.


Q:

facebook connect api static url

Is there a way to use the facebook connect api in a static way?
When we use the facebook php sdk the link or button to login to facebook is something like https://www.facebook.com/dialog/oauth..................
what I want is to eliminate the include of the php sdk on every page, because it will cause some extra processing and server load in peak times.
I want to make a session check to know if the user is logged in, by checking for exemple if his facebook user id and name are stored in the session, then if not, display a static login button. then after login with facebook he gets to facebook-login.php which will include the facebook php sdk and process his data and store them in the session, so that he remains logged without including the php sdk in each page.
the url structure that I get with $facebook->getLoginUrl() is:
https://www.facebook.com/dialog/oauth?client_id={MY_APP_KEY}&scope={PERMISSIONS}&redirect_uri={MY_SITE/facebook-login.php}&state={A_32_CHAR_CODE_LIKE_MD5_MAYBE}
The final question is: WHAT WOULD BE THE URL IN THE LOGIN BUTTON?

A:

just load the sdk and do something like:
echo 'getLoginUrl( array('next'=>'http://mysite.com', 'req_perms' => 'email,read_stream,publish_stream')) . '">Connect to Facebook';

that url will always be valid for a logged out user


Q:

How to show the value for edit in a window in time format from grid in extjs 4

I am using extjs 4.1 .I have a grid that is showing date in desired time format. But when I want to show the date and intime and outtime in a window for edit then only date is displaying. but intime and outtime is not displaying. All the fields in database are datetime. Can anyone please help me on this. Here is my code below :
my grid is like below :
Ext.define('Ext4Example.view.attendence.Datagrid' ,{
    extend: 'Ext.grid.Panel',
    alias : 'widget.datagrid',
    layout: 'fit',
    border: true,
    viewConfig: {
        stripeRows: true,
        forceFit:true,
        emptyText:'No Records to display'
    },

    hideHeaders: false,
    initComponent: function() {

        this.store = 'Attendences';
        //this.width = 400;
        this.columns = [
        {
            text: 'Date',
            dataIndex: 'id',
            renderer: function(value, metaData){
                return Ext.Date.format(value, 'M d, Y');
            }
        },{
            text: 'Day',
            dataIndex : 'id',
            renderer: function(value, metaData){
                return Ext.Date.format(value, ' l');
            }
        },
        {
            text: 'In-Time',
            dataIndex: 'intime',
            renderer: function(value, metaData){
                return Ext.Date.format(value, 'h:i A');
            }
        },
        {
            text: 'Out-Time',
            dataIndex: 'outtime',
            renderer: function(value, metaData){
                return Ext.Date.format(value, 'h:i A');
            }
        }

        ];

        this.callParent(arguments);
    }
});

And the window is given below where i want the values for edit :
    Ext.define('Ext4Example.view.attendence.Editattendence' ,{
    extend: 'Ext.window.Window',
    alias : 'widget.editattendence',
    title: 'Edit Attendence',
    layout: 'fit',
    autoShow: true,
    initComponent: function () {
        this.items = [
        {
            xtype: 'form',

            bodyStyle: {
                background: 'none',
                padding: '10px',
                border: '0'
            },
            items: [
            {
                xtype: 'datefield',
                name: 'id',
                allowBlank: false,
                fieldLabel: 'Attendene ID'
            },
            {
                xtype: 'numberfield',
                name: 'intime',
                allowBlank: false,
                fieldLabel: 'IN TIME',
                renderer: function(value, metaData){
                return Ext.Date.format(value, 'h:i A');
            }
            },{
                xtype: 'numberfield',
                fieldLabel: 'OUT TIME',
                name: 'outtime',
                renderer: function(value, metaData){
                return Ext.Date.format(value, 'h:i A');
            }
            }
            ]
        }
        ];
        this.buttons = [
        {
            text: 'Save',
            action: 'save'
        },
        {
            text: 'Cancel',
            scope: this,
            handler: this.close
        }
        ];
        this.callParent(arguments);
    }
});

And the controller where I am calling this window on double click in grid row is given below :
Ext.define('Ext4Example.controller.Attendences', {
    extend: 'Ext.app.Controller',
    stores: [
    'Attendences','Months'
    ],
    models: [
    'Attendence','Month'
    ],
    views: [
    'attendence.Timeperiod','attendence.Details','attendence.Attendencewindow','attendence.Editattendence','attendence.Datagrid'  //'attendence.Months'
    ],

    refs: [{
        ref: 'stockaddForm',
        selector: 'form'
    }],

    init: function () {
        this.control({
            'datagrid': {
                itemdblclick: this.editUser,
                viewready: this.attnready
            },
            'attendencewindow button[action=save]': {
                click: this.save
            }
        });
    },

    editUser: function(grid, record){
        var view = Ext.widget('editattendence');
        view.down('form').loadRecord(record);
    },
    save: function(){
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();     //+1
        Ext.Msg.alert("Today is - ",dd+" - "+mm+" - "+yyyy);
    },
    attnready: function(grid, eOpts) {
        console.log('hello');
        var store = grid.getStore(),
        selModel = grid.getSelectionModel();
          if (store.getAt(0)) {
            selModel.select(0);
        }
    }
});

A:

Hey I have solve this problem. Just a little bit of change in the editAttendence form as follows :
Ext.define('Ext4Example.view.attendence.Editattendence' ,{
    extend: 'Ext.window.Window',
    alias : 'widget.editattendence',
    title: 'Edit Attendence',
    layout: 'fit',
    autoShow: true,
    initComponent: function () {
        this.items = [
        {
            xtype: 'form',

            bodyStyle: {
                background: 'none',
                padding: '10px',
                border: '0'
            },
            items: [
            {
                xtype: 'datefield',
                name: 'id',
                allowBlank: false,
                fieldLabel: 'Attendene ID'
            },
            {
                xtype: 'datefield',
                format:'h:i A',
                name: 'intime',
                allowBlank: false,
                fieldLabel: 'IN TIME'

            },{
                xtype: 'datefield',
                format:'h:i A',
                fieldLabel: 'OUT TIME',
                allowBlank: false,
                name: 'outtime'

            }
            ]
        }
        ];
        this.buttons = [
        {
            text: 'Save',
            action: 'save'
        },
        {
            text: 'Cancel',
            scope: this,
            handler: this.close
        }
        ];
        this.callParent(arguments);
    }
});


Q:

Jquery - CSS translation with IE

I want to translate the div called "register_bottom_bar" inside its parent div "register_tile" by 174 pixels upwards using JQuery. I got it to work perfectly in Chrome and Firefox.
How can I do the same in IE? I'm testing it on IE 8.
"register_tile" is a floating div inside a bigger div and "register_bottom_bar" lies at the bottom of "register_tile" with position:relative.
$('.register_tile').click(function () {
    $(this).css('opacity', '1');
    $(this).css('background-image', 'none');
    $('.register_bottom_bar').css('-webkit-transform', 'translate(0,-174px)');
    $('.register_bottom_bar').css('-moz-transform', 'translate(0,-174px)');
});

A:

if you need support for old version of IE (6, 7, 8) you'll need to play with the properties margin / position instead.
$('.register_tile').click(function () {
    $(this).css('opacity', '1');
    $(this).css('background-image', 'none');
    $('.register_bottom_bar').css('left', '-174px); // With absolute / relative positioning
    // OR
    $('.register_bottom_bar').css('margin-left', '-174px);
});


Q:

Run code on start with javaFX 2

I would like to know how I can run code with the start of JavaFX 2 applications.
For example the Hello World application in Netbeans. How can I set elements invisible on start?
I use JavaFx with FXML and SceneBuilder.
With java I could just use "edit code" in Netbeans to put my code in and it would run on start.

A:

With fxml you can attach a controller whose initialize method is invoked when the document is loaded (this would be the preferred way for me to initialize fxml based UIs in code).
JavaFX applications have a start method for processing initializing the GUI on startup.
In your fxml you can set the visibility property on a Node to define it's initial visible state.
You can create a CSS stylesheet and in that setup a selector which selects your node and does initial styling on it such as making it invisible.
FXML also allows you to embed scripting languages in the fxml document or external files which can be used to initialize the GUI and act on events.


Q:

java gui help actionlistener

I'm trying to set a combobox in my GUI to print the the information about a student in a JLabel.
private void studentComboBoxMouseClicked(java.awt.event.MouseEvent evt) {

    if combobox1="student1"{
        println.jlabel."name:a";
        println.jlabel.""age:12";
        println.jlabel."course:english";
    }

    if combobox1="student2"{
        println.jlabel."name:b";
        println.jlabel.""age:11";
        println.jlabel."course:maths";
    }

    if combobox1="student3"{
        println.jlabel."name:c";
        println.jlabel.""age:10";
        println.jlabel."course:science";
    }
}

A:

You have to listen for itemstatechange on your combobox,
Upon selecting your student , fetch the selected item and operate on to display appropriate messages.
Have a look at this example


Q:

Excel VBA - Error in code to copy to specific sheet, dependent on range

JNevill very kindly cleaned up and improved the macro i had put together, unfortunately its coming back with errors and i havent been able to get a response to the original post. Hopefully someone can pick up where he left off.
the fault i'm getting is - object variable or with block variable not set that is against line lastCell = Range("A" & Rows.Count).End(xlUp).Offset(1)
Sub Macro1()
'Make a variable to store the cell found
Dim lastCell as Range

'find the last cell in Column A of the active sheet
lastCell = Range("A" & Rows.Count).End(xlUp).Offset(1)

'Paste in the I16 value
lastCell.value = RangE("I16").value

'Grab whatever is hanging out in Column B next to the last cell and stick it in J20
Range("J20").value = lastCell.Offset(0,1).value

'Test to see if I16 has value "R"
If Range("I16").value = "R" Then

    'Find the last row in Sheet7, Column B and store it to the variable
    lastCell = Range("B" & Rows.Count).End(xlUp).Offset(1)

    'Copy J20 value to the lastCell in Sheet 7, Column B
    lastCell = Range("J20").value
End if

End Sub

original post is here  ORIGINAL

A:

You're just missing Set (since it's an object variable):
Set lastCell = Range("A" & Rows.Count).End(xlUp).Offset(1)

Based on comments below, I think this is the sort of thing you want:
Sub Macro1()
    Dim ws                    As Worksheet
    'Make a variable to store the cell found
    Dim lastCell              As Range

    'find the last cell in Column A of the active sheet
    Set lastCell = Range("A" & Rows.Count).End(xlUp).Offset(1)

    'Paste in the I16 value
    lastCell.Value = Range("I16").Value

    'Grab whatever is hanging out in Column B next to the last cell and stick it in J20
    Range("J20").Value = lastCell.Offset(0, 1).Value

    'Test to see if I16 has value "R"
    Select Case VBA.UCase$(Range("I16").Value2)
        Case "R"
            Set ws = sheet7
        Case "C"
            Set ws = sheet3
        Case "P"
            Set ws = Sheet1
        Case "S"
            Set ws = Sheet2
    End Select

    If Not ws Is Nothing Then
        'Find the last row in Sheet7, Column B and store it to the variable
        Set lastCell = ws.Range("B" & Rows.Count).End(xlUp).Offset(1)

        'Copy J20 value to the lastCell in Sheet 7, Column B
        lastCell = Range("J20").Value
        Application.Goto lastCell, True
    End If

End Sub


Q:

I want to find a relation between $X(l,t)$ and $Y(l,t)$

Let $X(l,t)=4t \sum_{n=0}^{l-1} \binom{2n}{n}t^n \ $ and $ \ Y(l,t)=\sum_{n=0}^{l-1}n \binom{2n}{n}t^n$, where $l \in \mathbb{N}$.
I want find an explicit relation between $X(l,t)$ and $Y(l,t)$.
My approach:
Multiplying $Y(l,t)$ by $4t$, we get
$$ 4tY(l,t)=4t \sum_{n=0}^{l-1} n\binom{2n}{n}t^n.$$
But still it is not equal to $X(l,t)$ because of the absence of the factor $n$ in $X(l,t)$.
I could not find a relation between $X(l,t)$ and $Y(l,t)$.
Can someone help me please ?

A:

$$\begin{array}{rcl}Y(l,t)&=&t\sum_{n=0}^{l-1}n\binom{2n}{n}t^{n-1}\\&=&t\cfrac{d\left(\sum_{n=0}^{l-1}\binom{2n}{n}t^n\right)}{dt}\\&=&t\cfrac{d\left(\frac{X(l,t)}{4t}\right)}{dt}\\&=&\cfrac{1}{4}t\cfrac{d\left(\frac{X(l,t)}{t}\right)}{dt}\\&=&\cfrac{1}{4}t\cfrac{\cfrac{dX(l,t)}{dt}\cdot t-X(l,t)}{t^2}\\&=&\cfrac{1}{4}\left[\cfrac{dX(l,t)}{dt}-\cfrac{X(l,t)}{t}\right]\end{array}$$


Q:

Scala 2.11: get Class (result of classOf) for type parameters in collections

Say I have an instance of a Map[K, V], val m = Map[String, Int]("asdf" -> 1)
and I have a function defined as def getType[T : TypeTag](t: T) = typeOf[T]
I can use getType(m).typeArgs to get a List[Type](String, Int)
How do I get a List[Class] for String and Int? In other words, I want List(classOf[String], classOf[Int]) as collected from a Map[String, Int], or from any other combination of Map.
My ultimate goal is to write a RichRow for a Cassandra Row, wherein I can do (r: Row).getAs[Map[String, Int]]("mymap"), and under the hood can call r.getMap("mymap", classOf[String], classOf[Int]).
Thanks, and good luck.

A:

You can get a Class from a Type as follows:
scala.reflect.runtime.currentMirror.runtimeClass(tpe)


Q:

How to permanently remove a charm from the juju charms store?

I have already added a charm in juju charms store. Now I want to remove from the charms store.  Can anyone explain how to do this?

A:

There is a subtle difference between the official Juju Charm Store and charms in the personal name space.
Once a charm has been accepted into the Juju Charm Store by the review process it is maintained by the community and can not be removed from the store.
If however you have a charm in your personal name space (lp:~username/charms/ubuntu-series/charm-name/trunk) you can delete it from Launchpad.
Go to:  https://code.launchpad.net/~username/charms/ubuntu-series/charm-name/trunk
If you own the branch and are logged in, you can delete the branch by clicking on "Delete branch" button.  The next screen will warn you that Branch deletion is permanent. and ask you to confirm.


Q:

Limiting the size of inbound buffer in netty 4 cr6

How can I limit the size of inbound buffers that are being created by netty when client sends large files? I want a client to stop sending data over the network when ByteBuf is full and resume once it becomes ready to receive more data.
Here is my handler code:
public class MyDecoder extends ChannelInboundHandlerAdapter {

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    // limit the size of recieving buffer to 1024
    ctx.channel().config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(1024));
    }

@Override public void messageReceived(ChannelHandlerContext ctx, MessageList<Object> msgs) throws Exception {
    ByteBuf byteBuf = msgs.<ByteBuf>cast().get(0);
    // stop after this line in debugger to check size of the actual payload per messageReceived invocation
    int bufferSize = byteBuf.readableBytes();
    }
}

Now suppose that in my test I write:
EmbeddedChannel ch = new EmbeddedChannel(new MyDecoder());
ch.writeInbound(Unpooled.wrappedBuffer(<<<here is a byte representation of a large file, say 100 mb>>>));
ch.readInbound(); // etc...

Now when in debugger I get to a line where bufferSize is calculated, I always get the full size of my large file. The only difference FixedRecvByteBufAllocator makes at that point is when its size is set to 0 - all other values yield same results.
In netty 4 cr2 there was a method that served that purpose, newInboundBuffer, but there is no such construct in cr6 and onwards.

A:

The FixedRecvByteBufAllocator should limit the buffer to max 1024 bytes if this is not the case its a bug.


Q:

Is it possible to write custom primitives for GNU Emacs with C?

GNU Emacs is easily extended with Emacs Lisp. In some cases you may hit a performance wall even after byte compiling. In this situation it would be useful to be able to write C functions that you could call from Emacs Lisp code. Is this possible? How do you do it? Is there example code?

A:

Is this (Writing Emacs Primitives) what you are looking for?

A:

There is no interface to do this, and unless you were aiming to do something like image/video processing in emacs, I see no way it could be useful. C does not automatically make things faster unless you can bypass expensive data structures and work on the data in its representation. If your C code had to work with elisp data structures, it would not be significantly faster than elisp, and it would probably be slower than elisp if anybody ever bothered to make the elisp environment highly-optimizing...


Q:

Expressões Regulares: função do quantificador lazy "?"

Tenho aprendido sobre o uso de Expressões Regulares e li algumas explicações sobre o uso do sinal ? (chamado lazy quantifier), como nesta documentação da Microsoft:

*? : Corresponde ao elemento anterior zero vezes ou mais, mas o menor número de vezes possível.

No RegExr me mostra a seguinte explicação:

Se eu usar tanto a expressão ^(.*)$ quanto ^(.*?)$ ou ^(.+?)$ eu consigo o mesmo resultado:

var string = "abcdef";
var re1 = /^(.*)$/;
var re2 = /^(.*?)$/;
var re3 = /^(.+?)$/;
console.log(string.match(re1));
console.log(string.match(re2));
console.log(string.match(re3));

O que não me ficou muito claro foi "...mas o menor número de vezes possível.".
Como assim, o menor número de vezes possível?
Em que situação se deve usar e quando não usar o ? para quantificar o * ou o +, já que, como nos exemplos acima, usando ou não, o resultado é o mesmo?

A:

Você obtem o mesmo resultado porque o $ força que o fim do grupo de captura seja no fim da string. Assim, o menor número possível de vezes ainda vai necessariamente até o final da string.
O ? pega o * ou + o menor número possível de vezes, em contraste com o default de regex que é ser "greedy", quer dizer, pegar o maior número possível de caracteres que se encaixam no padrão. Considere o seguinte:
var string = 'Eu quero pegar uma palavra que comece com "q" seguida por um espaço.';
var re1 = /(q.*) /;
console.log(string.match(re1));
// "quero pegar uma palavra que comece com \"q\" seguida por um"

Perceba que ao invés de pegar só o "quero", o grupo de captura pegou o quero, que começa com "q", e mais tudo até o último espaço encontrado. Por isso o regex é ganancioso: ele pega tudo o que consegue.
Vejamos agora a mesma coisa com o ? que tira a ganância do regex:
var string = 'Eu quero pegar uma palavra que comece com "q" seguida por um espaço.';
var re2 = /(q.*?) /;
console.log(string.match(re2));
// "quero"

Isso está mais em linha com o que queríamos. O regex pegou no grupo de captura a minha palavra que começa com "q", e parou no primeiro espaço; quer dizer, ele deu match no menor número de caracteres possível que satisfaz a expressão regular.
No seu exemplo original, o menor número possível de caracteres ainda era a string completa porque com o ^ e o $, você forçava o regex a começar no primeiro caractere da string e terminar no último. Assim, a menor string que satisfaz a expressão completa é a string toda.

A:

Imagine que você tenha uma página HTML gigante numa string s e você pesquise a regex /<[^>]+>.*<\/[^>]+>/. O que você vai obter? Sim, a tag html, todo o resto do documento e o fecha html, porque os quantificadores normais são gulosos.
Agora, se você tiver a mesma string s e uma regex /<[^>]+>.*?<\/[^>]+>/, o que você vai obter? Qualquer tag que abre e feche nos primeiros trechos do documento.

$(function () {

  var s = $('#conteudo').html();

  alert('Original: ' + s);
  alert('Eager: ' + s.match(/<[^>]+>.*<\/[^>]+>/gm)[0]);
  alert('Lazy: ' + s.match(/<[^>]+>.*?<\/[^>]+>/gm)[0]);

});
* { font-family: Consolas; }

Produto	Preço	Quantidade

Feijão	R$ 8,75	1

Arroz	R$ 4,99	2

Total		R$ 18,73

A:

Complementando as outras respostas, o ? como indicador de lazyness não se limita a ser usado apenas com * e +. Ele pode ser usado com qualquer outro quantificador, como o {}, por exemplo.

let s = 'a1234567890';

// sem lazy, pega a maior quantidade possível
console.log(s.match(/a\d*/)); // a1234567890
console.log(s.match(/a\d+/)); // a1234567890
console.log(s.match(/a\d{3,7}/)); // a1234567
console.log(s.match(/a\d{3,}/)); // a1234567890

As expressões acima correspondem a uma letra a seguida de determinada quantidade de dígitos (\d seguido de um quantificador).
Nos casos acima não há o ?, então os quantificadores estão no seu modo default, que é ser "ganancioso" (greedy), ou seja, eles tentam pegar a maior quantidade possível de caracteres que satisfaça a expressão. Para * e +, não há um limite máximo (o * corresponde a zero ou mais ocorrências, e o + corresponde a uma ou mais ocorrências), então a "maior quantidade possível que satisfaz a expressão" corresponde a "todos os dígitos" (1234567890).
Já \d{3,7} significa "no mínimo 3, no máximo 7 dígitos", então a maior quantidade possível que satisfaz a expressão é 7, por isso o resultado é a1234567. E \d{3,} significa "no mínimo 3 dígitos, sem limite máximo", então a maior quantidade possível que satisfaz a expressão é "pegar todos os dígitos", por isso o resultado é a1234567890.

Agora se mudarmos todos esses quantificadores para o seu modo lazy:

let s = 'a1234567890';

// com lazy, pega a menor quantidade possível
console.log(s.match(/a\d*?/)); // a
console.log(s.match(/a\d+?/)); // a1
console.log(s.match(/a\d{3,7}?/)); // a123
console.log(s.match(/a\d{3,}?/)); // a123

Agora, graças ao ? logo depois, os quantificadores se tornam "preguiçosos" (lazy), e passam a pegar a menor quantidade possível de caracteres que satisfaçam a expressão.
Como * significa "zero ou mais ocorrências", a menor quantidade de dígitos que satisfaz a expressão é zero. Por isso o resultado do match é a.
Já o + significa "uma ou mais ocorrências", então a menor quantidade de dígitos que satisfaz a expressão é um. Por isso o resultado é a1.
Por fim, {3,7} significa "no mínimo 3, no máximo 7 ocorrências" e {3,} significa "no mínimo 3 ocorrências, sem limite máximo", então para ambos a menor quantidade de dígitos que satisfaz a expressão é três, por isso o resultado é a123.

Vale lembrar que o ? também é um quantificador (que significa "zero ou uma ocorrência", que é outra forma de dizer que algo é opcional), e portanto ele também pode ser greedy (ganancioso) ou lazy (preguiçoso):

let s = 'a1234567890';

// sem lazy, pega a maior quantidade possível
console.log(s.match(/a\d?/)); // a1

// com lazy, pega a menor quantidade possível
console.log(s.match(/a\d??/)); // a

No primeiro caso, \d? indica que o dígito é opcional. Mas por default, todo quantificador é ganancioso, então ele tenta pegar a maior quantidade possível de caracteres (que nesse caso é 1), por isso no primeiro caso o retorno é a1.
Já no segundo caso, o quantificador ?? é preguiçoso (o primeiro ? indica que o \d é opcional, e o segundo ? torna o quantificador lazy) e pega a menor quantidade possível de caracteres, que no caso é zero. Por isso o retorno é a.

Quando usar? Depende
É muito comum as pessoas usarem .*? sem nem parar para pensar se é isso mesmo que precisam, simplesmente porque é "mais fácil". Isso geralmente acontece porque elas primeiro tentam com .*, que gera os problemas apontados nas outras respostas: como o ponto corresponde a qualquer caractere (exceto quebras de linha, a menos que se configure isso), ele pode acabar pegando mais caracteres do que devia, caso a regex ache necessário. E aí acabam mudando para lazy e "pronto".
Usando o exemplo da resposta do Pedro:

let string = 'Eu quero pegar uma palavra que comece com "q" seguida por um espaço.';
console.log(string.match(/(q.*) /)[1]); // quero pegar uma palavra que comece com "q" seguida por um
console.log(string.match(/(q.*?) /)[1]); // quero

O objetivo era pegar uma palavra que começa com "q", seguido por um espaço. Mas como o * é ganancioso, por padrão ele tenta pegar o maior número possível de caracteres. E como o ponto corresponde a qualquer caractere (inclusive o espaço), ele acaba pegando espaços a mais. Para evitar esse problema, usou-se o quantificador lazy, assim a regex não avança mais do que "deveria" e só pega até o primeiro espaço.
Mas nesse caso você não precisaria usar o ponto, e nem o quantificador lazy. Se você quer parar no primeiro espaço que tiver depois do "q", é melhor ser mais específico e dizer exatamente o que você quer. Nesse caso, você não quer "qualquer coisa", e sim "qualquer coisa que não seja um espaço". Sendo assim, a regex poderia ser:

let string = 'Eu quero pegar uma palavra que comece com "q" seguida por um espaço.';
console.log(string.match(/(q[^ ]*) /)[1]); // quero

Eu usei a classe de caracteres negados [^ ] (qualquer coisa que não seja espaço) - repare que há um espaço antes do ]. Sendo assim, o quantificador nem precisa ser lazy, pois o [^ ]* já me garante que a regex só vai avançar até encontrar um espaço. Isso deixa não só a regex mais clara quanto à sua intenção, mas também mais eficiente: basta comparar aqui e aqui a quantidade de passos que cada uma executa e ver que a opção com [^ ] precisa de menos passos que .*?.
Isso acontece porque, embora o quantificador lazy .*? funcione, ele cobra o seu preço. Basicamente, depois de encontrar o primeiro q (na palavra "quero"), o .*? verifica se logo depois tem um espaço (ele é preguiçoso, então primeiro ele tenta com zero caracteres depois do q). Mas como logo depois não tem um espaço, a regex volta e o .*? encontra o u, e então verifica se o próximo caractere é um espaço. Como não é, ela volta e o .*? consome a letra e, e avança para ver se tem um espaço depois. Como não tem, ela volta e pega o r, e assim por diante, até encontrar o espaço. Todo esse vai e volta é chamado de backtracking, e é um processo custoso, dependendo da regex e das strings que ela está verificando. O ponto é que a regex sempre vai testar todas as possibilidades, até encontrar um match (ou até perceber que não há nenhum). E usando o ponto, as possibilidades aumentam ainda mais, já que ele corresponde a qualquer caractere.
Já usando [^ ] (ou qualquer outra expressão mais restritiva que o ponto), as coisas mudam: como o [^ ] foi usado com um quantificador greedy, o comportamento da regex é avançar de uma vez, o máximo de caracteres que puder - e no caso, ela avança até encontrar um espaço, que é justamente o que pretendíamos (e o melhor: sem o backtracking que ocorre com .*?). Ou seja, eu me aproveitei do comportamento ganancioso do quantificador para que a regex seja mais eficiente (se eu torná-lo lazy não haverá ganho algum, pois será feito backtracking, veja). Além disso, o fato de eu usar uma expressão mais específica (qualquer coisa que não seja espaço) em vez do ponto (que pode ser qualquer coisa), me garante que a regex não vai avançar mais do que devia.
Obviamente que, para strings pequenas ou regex que serão executadas poucas vezes, em situações nas quais o desempenho não é algo tão crítico, etc, a diferença não é tão grande assim, e de qualquer forma, se eficiência é um requisito importante, devem ser feitos testes para saber se a regex é de fato o gargalo. E a quantidade exata de passos executados pela regex pode variar conforme a situação, pois algumas linguagens e engines podem fazer certas otimizações dependendo da expressão e/ou das strings envolvidas (mas o backtracking causado por um quantificador lazy continua sendo um fator que piora o desempenho, independente disso).
De qualquer forma, ainda acho que é importante saber que o uso indiscriminado de .*? nem sempre é a melhor solução. Nem sempre você quer "qualquer coisa", muitas vezes você quer "qualquer coisa, desde que não seja X, Y ou Z".
Obs: ainda tem outra diferença. O ponto, por default, não considera as quebras de linha, mas [^ ] sim (veja). Se não quiser pegar as quebras de linha, pode trocar para q\S* (o atalho \S é tudo que não for espaço ou quebra de linha - veja), ou para algo mais específico como q[a-z]* (veja). Enfim, há várias opções para não precisar do quantificador lazy.

Outro caso em que o uso do quantificador lazy não é tão interessante é quando você quer pegar "tudo até o final da linha". Como o ponto, por padrão, não considera quebras de linha, eu poderia fazer:

let string = "Vou pegar tudo depois do número 1: esse é o trecho que quero pegar, até o final da linha\nEsse trecho está em outra linha e não quero";
console.log(string.match(/\d: (.*)/)[1]); // esse é o trecho que quero pegar, até o final da linha

No caso, a regex tem \d: (um número seguido de : e espaço), e depois eu tenho (.*) (zero ou mais ocorrências de qualquer coisa). Mas por default o ponto não considera as quebras de linha, então ele avança até encontrar o \n. Eu me aproveito do comportamento greedy para fazer a regex avançar até onde quero sem precisar fazer backtracking (veja aqui ela funcionando).
Mas se eu trocar a regex para \d: (.*?), ela não pega o restante da linha (pois ele vai pegar a menor quantidade de caracteres, e nesse caso é zero, conforme os primeiros exemplos acima) - veja. Neste caso eu teria que indicar que quero tudo até a quebra de linha, mudando a regex para \d: (.*?)\n, por exemplo. Mas aí o quantificador lazy fará o backtracking para verificar se já chegou ao final da linha, tornando a regex menos eficiente, veja.
Resumindo, nem sempre o quantificador lazy é a melhor solução (aliás, nem sempre ele é a solução).

Para os seus exemplos, o resultado é o mesmo porque você usou os marcadores ^ e $ (início e fim da string), então ^.*$ e ^.*?$ vão pegar "qualquer coisa do início ao fim da string", ou seja, tanto faz, pois sempre vai encontrar um match (a diferença é que .* vai dar match em strings vazias, enquanto .+ exige que haja pelo menos um caractere). Mas ainda sim há uma diferença de desempenho, veja aqui, aqui, aqui e aqui.
E sobre o uso indiscriminado de .*? e as consequências de forçar a regex a fazer muitos backtrackings, vale ler este artigo.


Q:

Can I delete the logs in the /private/tmp folder?

Seems like there are around 5,000 wifi logs, each 2MB each, totaling nearly 10GB on my disk in /private/tmp. Can I delete these logs, or will macOS automatically delete them itself? I tried making a file using the mkfile command until I had about 2GB of disk space left, but nothing was automatically cleared.

A:

In the standard configuration, launchd will run the "periodic-daily" script once a day with a low priority. The periodic-daily script will run the /etc/periodic/daily/110.clean-tmps script, which in turn removes the files in /tmp (which is the same as /private/tmp) that haven't been accessed for 3 days.
So normally these log files will be deleted every 3 days, unless ofcourse something is still writing to them - or you yourself are opening them all the time to check them.
You do not specify the file name of the files you're worrying about. Normally it should be safe to just delete log files in /private/tmp/.


Q:

Display Table output as a grid of points

I want to create a Grid or Plot (or equivalent) from the following Table:
Module[{size = 10}, Table[If[PrimeQ[a + b], True], {a, 1, size}, {b, 1, size}]]

(*
{{True, True, Null, True, Null, True, Null, Null, Null, True},
{True, Null, True, Null, True, Null, Null, Null, True, Null},
{Null, True, Null, True, Null, Null, Null, True, Null, True},
{True, Null, True, Null, Null, Null, True, Null, True, Null},
{Null, True, Null, Null, Null, True, Null, True, Null, Null},
{True, Null, Null, Null, True, Null, True, Null, Null, Null},
{Null, Null, Null, True, Null, True, Null, Null, Null, True},
{Null, Null, True, Null, True, Null, Null, Null, True, Null},
{Null, True, Null, True, Null, Null, Null, True, Null, True},
{True, Null, True, Null, Null, Null, True, Null, True, Null}}
*)

I want the output to have the following properties:

The two 'axes' a and b are marked, and have ticks at integer values;
There is a grid of lines showing integer intervals from both axes;
At each intersection with Cartesian coordinates (a,b) where the Table output is True, there should be a Point; at Null points there should be nothing.

This seems like it should be really simple, but for some reason I can't quite get my head around the syntax...
How do I do it?

A:

Visualized as squares rather than points
ArrayPlot[data,
 Frame -> True,
 FrameTicks -> {{Range@10, Range@10}, {Range@10, Range@10}},
 DataReversed -> True,
 PlotRangePadding -> None,
 Mesh -> All]

A:

Inspired by @kglr and extending to arbitrary dimensions on the data, this may do what you want:
data = Module[{size = 11},
  Table[If[PrimeQ[a + b], True], {a, 1, size}, {b, 1, size}]];
With[{elements = Max[Dimensions[data]]},
 ListPlot[Position[data, True],
  PlotStyle -> Directive[Black, PointSize[Large]], Frame -> True,
  AspectRatio -> 1,
  FrameTicks -> {{Range[elements],
     Thread[{Range[elements], ""}]}, {Range@elements,
     Thread[{Range[elements], ""}]}},
  GridLines -> {Range[elements], Range[elements]},
  PlotRange -> {{1, elements}, {1, elements}},
  PlotRangeClipping -> False]]

Shown with size set to 11 to show that it fits the generality.


Q:

Como imprimir um webview em uma impressora bluetooth?

Estou fazendo um aplicativo que ele precisa imprimir o conteudo de uma webview , porém a impressora é bluetooth , poderiam me ajudar?

A:

Impressão em bluetooth no android não é uma coisa simples, nem tão pouco fácil de ser feito.
Vou deixar aqui um caminho para que possa atingir seu objetivo:

Existe uma library que faz a comunicação com o bluetooh diretamente já. Mas para curiosidade, você tem que listar os devices bluetooth e depois de achá-los, você tem que abrir um socket para ele e mandar a impressão. Essa library facilita todo esse trabalho.
Como uma página web é renderizada já, e como o interesse é imprimir ela formatada, não o código-fonte, você teria que gerar uma imagem deste html. Se utilizar. Esta resposta do SOen vai te mostrar como fazer isso.
Depois de ter um snapshot da sua webview, você envia para a library em 1, chamando o método printImage(Bitmap).