text:
Q: How to kill a thread which has a while(true)? I am trying to close all my thread in my threadpool.
Usually I try:
        while(!Thread.currentThread().isInterrupted()) {...

To close the while loop...
But I have one Thread which only consists about
        while(!Thread.currentThread().isInterrupted()) {//which is true

This is how I close the threads:
pool.shutdownNow();

So how would you close such a Thread?

A: Instead of that you might use a self created flag as condition for the while loop.
public class MyClass implements Runnable
{

    private volatile boolean running = true;

    public void stopRunning()
    {
        running = false;
    }

    public void run()
    {
        while (running)
        {

        }
        // shutdown stuff here
    }

}

Now, to stop it, just call:
myClassObject.stopRunning();

This will let the code finish normally.

A: If you have implemented this as you have described, it should just work.
When you call pool.shutdownNow() it is supposed to interrupt all worker threads that are currently active.  Assuming that the application specific run() methods check the interrupted flag and terminate themselves when they find it set, your threads should shutdown.
There is really no need to add a different mechanism using an ad hoc cancel flag ... or some such.

Incidentally, there are a couple reasons why interrupt() is better than ad hoc cancellation:

*

*Standard APIs like ExecutorService use it.

*Various low-level API methods like sleep, wait, join and some I/O methods are sensitive to it.

A: You can add a volatile boolean flag.
public class Worker implements Runnable {

    volatile boolean cancel = false;
    @Override
    public void run() {

        while (!cancel) {
            // Do Something here
        }
    }

    public void cancel() {
        cancel = true;
    }
}

Now you can just call
worker.cancel();

Update:
From Java doc of shutdownNow()

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
here are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

So either you will have to define your interruption policy by preserving the interrupts
  catch (InterruptedException ie) {
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }

A: If you are using a java.util.concurrent ExecutorService implementation, then it will definitely send an interrupt signal to all the threads in its thread pool. The problem with your rogue task may be that the loop doesn't in fact iterate, but blocks somewhere within, so the interrupted status is not getting checked at all.
Yet another problem you may have: the while loop runs some code that catches InterruptedException without handling it properly, effectively swallowing the interrupt signal. This is a common coding mistake and in most cases due to the ugly truth that InterruptedException is checked.


text:
Q: Reset Versioning Settings by PowerShell On our libraries we set versioning settings = create major versions and keep 50 of them.
We'd like to remove only the "Keep the following number of major versions" setting on all libraries. Because there are many libs we'd like to execute a PowerShell script. But

*

*the major setting checkbox itself seems to be no property, we just can set
$list.EnableVersioning = $true

$list.EnableMinorVersions = $false

*we cannot just set the number of major versions to 0 (= invalid value)

*we cannot just reverse EnableVersioning (set it to false, update and afterwards set it to true again => the former number of major versions reappear)

So how to get rid of the number of major versions limit without changing the rest of the versioning settings using PowerShell?

A: Here is my test script to clean "Keep the following number of major versions" and "Keep drafts for the following number of major versions" options if enabled "Create major and minor (draft) versions".
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
#Get the web
$SourceWebURL = "http://sp:12001/"
$ListName="MyDoc"
$Spweb = Get-SPWeb $SourceWebURL
$SPList = $Spweb.Lists.TryGetList($ListName)
$SPList.MajorVersionLimit=0;
$SPList.MajorWithMinorVersionsLimit=0;
$SPList.Update();
write-host "Done"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swagger - Invalid JSON errors I'm just starting with Swagger UI and I'm trying to understand how it works.
So far I've entered some JSON (manually) and this is the result:
{
    "swagger": "2.0",
    "info": {
        "version": "1.0.0",
        "title": "PhakeApps API",
        "contact": {
            "name": "PhakeApps API team",
            "url": "http://phakeapps.com/"
        },
        "license": {
            "name": "Creative Commons 4.0 International",
            "url": "http://creativecommons.org/licenses/by/4.0/"
        }
    },
    "host": "api.phakeapps.com",
    "basePath": "/v1",
    "schemes": [
        "http"
    ],
    "produces": [
        "application/json"
    ],
    "consumes": [
        "application/json"
    ],
    "paths": {
        "/places/search": {
            "post": {
                "tags": [
                    "Places"
                ],
                "description": "Search for (a) place(s)

 id - The ID of the request.
 api_key - API Key for the platform the request is sent. Currently, not required.
 Params - Required. See model & model schema.",
                "operationId": "PlacesSearch",
                "produces": [
                    "application/json"
                ],
                "consumes": [
                    "application/json"
                ],
                "parameters": [
                    {
                        "name": "request",
                        "in": "body",
                        "paramType": "body",
                        "description": "Object containing the id, api_key and certain params.",
                        "required": true,
                        "schema": {
                            "$ref": "#/definitions/Search"
                        }
                    }
                ],
                "responses": {
                    "200": {
                        "description": "Success",
                        "schema": {
                            "$ref": "#/definitions/PlacesResult"
                        }
                    },
                    "403": {
                        "description": "Validation error or Server Failure",
                        "schema": {
                            "$ref": "#/definitions/Error"
                        }
                    }
                }
            }
        }
    },
    "definitions": {
        "PlacesResult": {
            "required": [
                "data",
                "id",
                "code"
            ],
            "properties": {
                "data": {
                    "$ref": "#/definitions/Places"
                },
                "id": {
                    "type": "integer",
                    "format": "int32"
                },
                "code": {
                    "type": "integer",
                    "format": "int32"
                }
            }
        },
        "Places": {
            "required": [
                "places"
            ],
            "properties": {
                "places": {
                    "$ref": "#/definitions/Place"
                }
            }
        },
        "City": {
            "required": [
                "id",
                "name"
            ],
            "properties": {
                "id": {
                    "type": "string"
                },
                "name": {
                    "type": "string"
                }
            }
        },
        "Neighbourhood": {
            "required": [
                "id",
                "name"
            ],
            "properties": {
                "id": {
                    "type": "string"
                },
                "name": {
                    "type": "string"
                }
            }
        },
        "Cuisine": {
            "required": [
                "id",
                "name"
            ],
            "properties": {
                "id": {
                    "type": "string"
                },
                "name": {
                    "type": "string"
                }
            }
        },
        "Place": {
            "required": [
                "id",
                "name",
                "city",
                "neighbourhood",
                "address",
                "cuisine",
                "price",
                "photos_cnt",
                "lat",
                "lng",
                "is_fav"
            ],
            "properties": {
                "id": {
                    "type": "string"
                },
                "name": {
                    "type": "string"
                },
                "city": {
                    "type": "array",
                    "items": {
                        "$ref": "#/definitions/City"
                    }
                },
                "neighbourhood": {
                    "type": "array",
                    "items": {
                        "$ref": "#/definitions/Neighbourhood"
                    }
                },
                "address": {
                    "type": "string"
                },
                "cuisine": {
                    "type": "array",
                    "items": {
                        "$ref": "#/definitions/Cuisine"
                    }
                },
                "price": {
                    "type": "integer",
                    "format": "int32"
                },
                "photos_cnt": {
                    "type": "integer",
                    "format": "int32"
                },
                "lat": {
                    "type": "double"
                },
                "lng": {
                    "type": "double"
                },
                "is_fav": {
                    "type": "boolean"
                }
            }
        },
        "Search": {
            "required": [
                "id",
                "api_key",
                "params"
            ],
            "properties": {
                "id": {
                    "type": "integer",
                    "format": "int64"
                },
                "api_key": {
                    "type": "string"
                },
                "params": {
                    "$ref": "#/definitions/SearchParams"
                }
            }
        },
        "SearchParams": {
            "required": [
                "user_id",
                "city_id",
                "people",
                "dt",
                "locale"
            ],
            "properties": {
                "user_id": {
                    "type": "string",
                    "default": "956dda4c21c72e48f5f17a7cd783a0f7"
                },
                "city_id": {
                    "type": "string",
                    "default": "4ec4b3e6098c9d23c925b0c2451eb06a"
                },
                "people": {
                    "type": "integer",
                    "format": "int32",
                    "minimum": 1,
                    "default": 2
                },
                "dt": {
                    "type": "integer",
                    "format": "int32",
                    "default": "1427742000"
                },
                "locale": {
                    "type": "string",
                    "default": "bg"
                },
                "place_id": {
                    "type": "string",
                    "default": "0"
                },
                "neighborhood_id": {
                    "type": "string",
                    "default": "0"
                },
                "cuisine_id": {
                    "type": "string",
                    "default": "0"
                },
                "kids_place": {
                    "type": "boolean",
                    "default": false
                },
                "price": {
                    "type": "integer",
                    "format": "int64",
                    "default": 1
                },
                "outdoors": {
                    "type": "boolean",
                    "default": false
                }
            }
        },
        "Error": {
            "required": [
                "code",
                "data"
            ],
            "properties": {
                "code": {
                    "type": "integer",
                    "format": "int32"
                },
                "data": {
                    "type": "array",
                    "items": {
                        "type": "array"
                    }
                }
            }
        }
    }
}

However, swagger's validator says it's not valid. The error I get is this
[
    {
        "level": "error",
        "domain": "validation",
        "keyword": "anyOf",
        "message": "instance failed to match at least one required schema among 2",
        "schema": {
            "loadingURI": "http://json-schema.org/draft-04/schema#",
            "pointer": "/properties/type"
        },
        "instance": {
            "pointer": "/definitions/Place/properties/lat/type"
        }
    }
]

Note that it works as expected (so far). It displays the data (models and models' structure) properly. Make requests and retrieves responses. Yet the validator says it's not valid. (The yellow badge saying 'Invalid', not the red one that says 'Error').
What am I missing?

A: Your spec is indeed not valid. In your Place definition, you use "type": "double" to describe the type of the lat (and also lng) property, but such a type does not exist.
If you want to describe a numeric value of 'double' size, you should change the definition as follows:
            "lng": {
                "type": "number",
                "format": "double"
            }

Do that everywhere you use the double type, and it should resolve that issue.


text:
Q: Excel: How to use Copy Paste command to selected sheet area (VBA) Extended Question from-
Excel: How to copy a row if it contains certain text to another worksheet (VBA)
I'm looking to modify the below code so that it's able to copy from sheet 2 to sheet 4, pasted adjacent (L:U)? see pictures.
pic2
Option Explicit

Sub Test()

Dim Cell As Range

With Sheets(1)
' loop column H untill last cell with value (not entire column)
For Each Cell In .Range("H1:H" & .Cells(.Rows.Count, "H").End(xlUp).Row)
    If Cell.Value = "FAIL" Then
         ' Copy>>Paste in 1-line (no need to use Select)
        .Rows(Cell.Row).Copy Destination:=Sheets(4).Rows(Cell.Row)
    End If
Next Cell
End With

End Sub

Comment Reply with picture pic3

A: Like this?
Option Explicit

Sub Test()

Dim Cell As Range

With Sheets(1)
' loop column H untill last cell with value (not entire column)
For Each Cell In .Range("H1:H" & .Cells(.Rows.Count, "H").End(xlUp).Row)
    If Cell.Value = "FAIL" Then
         ' Copy>>Paste in 1-line (no need to use Select)
        .Range("A" & Cell.Row & ":J" & Cell.Row).Copy Destination:=Sheets(4).Range("L" & Sheets(4).Cells(Sheets(4).Rows.Count, "L").End(xlUp).Row + 1)
    End If
Next Cell
End With

End Sub

Macro to copy links:
Option Explicit

Sub Test()

Dim Cell As Range

With Sheets(1)
' loop column H untill last cell with value (not entire column)
For Each Cell In .Range("H1:H" & .Cells(.Rows.Count, "H").End(xlUp).Row)
    If Cell.Value = "FAIL" Then
        .Range("A" & Cell.Row & ":J" & Cell.Row).Copy
         ' Paste as Links requires to select a destination cell
        Sheets(4).Range("L" & Sheets(4).Cells(Sheets(4).Rows.Count, "L").End(xlUp).Row + 1).Select
        ActiveSheet.Paste Link:=True
    End If
Next Cell
End With

End Sub


text:
Q: To execute query in XML format using Microsoft dynamics CRM I have designed a query using Advanced Find and downloaded the same using Download Fetch XML option.
After getting that XML, I made some changes in the downloaded XML file. Now, I want to run the query in the modified XML file, using Microsoft Dynamics CRM.
How can I do that?

A: I have used the FetchXml Tester utility from the XRM Toolbox. You can load the resulting xml into Excel if you want to look at it in tabular format.
There is also a way to manually push FetchXml into a view via the SDK or customization XML, but that is a bit more involved.


text:
Q: Is there a way of selecting elements by their title in JS? I am trying to create a program to select elements on the page, but it seems that the only thing that makes them unique are there titles. Is there any way of selecting certain things on a web page by their titles? I found this script but it will not select or click on the elements.
What am I doing wrong? Any help will do. Thanks
How can I get it to work on A and not div, sorry, that was the problem
My script that I am using --
     $(document).ready(function () {
         $("a[title=\"Learn More About Becoming A VIP\"]").click();
     });

It says Div is not defined when I try to run script. Why So?

A: There is a way to select elements by their title attribute in javascript:
document.querySelectorAll('div[title="john"]');

======
You can also select elements that have a title beginning with john:
document.querySelectorAll('div[title^="john"]');

Or elements that have the (space-bounded) word john somewhere in their title:
document.querySelectorAll('div[title~="john"]');

A: Your selector should work if title value is john. You might wan't to select element that contains certain string as follow:
$('div[title*="john"]')


text:
Q: How is <%= form_tag ... do %> implemented? I'm trying to figure out how you can herald a Ruby block in a <%= ... %> emitter.
No problem with the '<% form_tag do %>' part, but as I dig into Rails internals
and see how it uses erb to process templates, the generated Ruby code is invalid,
due to that hanging 'do'.  Is there a post-processor hiding in Rails somewhere that
straightens out the code before running it?  If yes, where is it?  If no, how does
Rails pull HTML and Ruby code out of this form?

A: Rails added a hack which uses a regular expression to figure out if what is passed to erb is a block expression and then handle it differently.
For a more detailed explanation: http://timelessrepo.com/block-helpers-in-rails3


text:
Q: Error ORA-02000 - QUERY keyword missing on MATERIALIZED VIEW this is my problem
  CREATE MATERIALIZED VIEW STRUTT_AFAM_RD (CD_ENTE, CD_STRUTTURA)
  TABLESPACE FLUSSI_SIA01D
  BUILD IMMEDIATE
  USING INDEX
  REFRESH COMPLETE ON DEMAND NEXT TO_DATE(TO_CHAR(SYSDATE + 1, 'DD-MON-
  YYYY') || ' ' || '05:00:00','DD-MON-YYYY HH24:MI:SS')
  WITH ROWID USING DEFAULT LOCAL ROLLBACK SEGMENT
  USING ENFORCED CONSTRAINTS DISABLE ON QUERY COMPUTATION DISABLE QUERY
  REWRITE
  AS (SELECT SUBSTR(S.CD_STRUTTURA_CUDES,1,3) CD_ENTE,
           S.CD_STRUTTURA_CUDES  CD_STRUTTURA
      FROM PONTE_EVESAN.STRUTTURE_FAM_AN@SEBP_PONTE_EVESAN S
     WHERE S.DT_FINE_VALIDITA IS NULL
       AND S.FL_ANNULLA = 0);

  CREATE UNIQUE INDEX I_SNAP$_SIAD_STRUTT_AFAM_RD ON STRUTT_AFAM_RD
  (M_ROW$$)
  PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS NOLOGGING
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE FLUSSI_SIAD01D ;

  COMMENT ON MATERIALIZED VIEW STRUTT_AFAM_RD  IS 'STRUTTURE AFAM';

error :ORA-02000: parola chiave QUERY mancante(QUERY keyword missing)
02000. 00000 -  "missing %s keyword"

A: Which database version do you use? What's that DISABLE line supposed to do, especially the COMPUTATION (key?)word?
This is 11g CREATE MATERIALIZED VIEW documentation, read it & follow the syntax.
Anyway: have a  look at this code which is, actually, valid. Note the difference (I marked it with a comment):
CREATE MATERIALIZED VIEW STRUTT_AFAM_RD
   (
   CD_ENTE,
   CD_STRUTTURA
   )
   TABLESPACE FLUSSI_SIA01D
   BUILD IMMEDIATE
   USING INDEX
   REFRESH COMPLETE
           ON DEMAND
           NEXT TO_DATE (
                   TO_CHAR (SYSDATE + 1, 'DD-MON-YYYY') || ' ' || '05:00:00',
                   'DD-MON-YYYY HH24:MI:SS')
           WITH ROWID
           USING DEFAULT LOCAL ROLLBACK SEGMENT
           USING ENFORCED CONSTRAINTS
   -- DISABLE ON QUERY COMPUTATION DISABLE QUERY REWRITE  --> yours
   DISABLE QUERY REWRITE                                  --> mine
AS
   (SELECT SUBSTR (S.CD_STRUTTURA_CUDES, 1, 3) CD_ENTE,
           S.CD_STRUTTURA_CUDES CD_STRUTTURA
      FROM PONTE_EVESAN.STRUTTURE_FAM_AN@SEBP_PONTE_EVESAN S
     WHERE S.DT_FINE_VALIDITA IS NULL AND S.FL_ANNULLA = 0);


text:
Q: converting the elements in an array to a customized string using PHP-Symfony I am trying to pass the elements in an array to a twig file. After it is passed, the html (in the js) code should look like

var states = ['car','van','bus']

I used the following code to do so using php symfony
/**
 * @Route("/test", name="test")
 */
public function testAction(Request $request)
{
    $products=$this->getDoctrine()->getRepository(products::class)->findAll();
    $pr_name=array();
    foreach ($products as $product){
        $name=$product->getName();
        array_push($pr_name,$name);

    }

    $pr_name2="'".implode("','",$pr_name)."'";
    dump($pr_name2);
    exit;

    return $this->render('typeahead.html.twig', array(
        'pr_name'=>$pr_name2,
    ));

}

My Twig file
<script>
 var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
        var matches, substringRegex;

        // an array that will be populated with substring matches
        matches = [];

        // regex used to determine if a string contains the substring `q`
        substrRegex = new RegExp(q, 'i');

        // iterate through the pool of strings and for any string that
        // contains the substring `q`, add it to the `matches` array
        $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
            }
        });

        cb(matches);
    };
};

var states = [{{ pr_name }}]

$('#the-basics .typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        name: 'states',
        source: substringMatcher(states)
    });

But what I get is this

How to fix this?

A: Try replacing
var states = [{{ pr_name }}]

with
var states = [{{ pr_name|raw }}]


text:
Q: Getting user info when logged in as another user Is there a way to identify / get the user Id of the actual user who is logged in as another user using the login as button? The best I can do today is to run the audit trail which gives info on who logged in as someone else, this is not a big help.
I want to block access to an external site and want to know the base user's id who has logged in as the another user. The actual user's personal data is getting exposed to the logged in user.
Its a web tab so I cannot apply sharing rules, I have delegate enabled thereby hiding a tab or any other setting on the actual user would have no effect.

A: Not sure if this is used everywhere BUT,
Since it is a web tab, if you have control over it and can access cookie information you can check for the cookie matching the salesforce instance i.e: na1.salesforce.com and look for the
RRetURL and if it is set to a user ID then you can assume they are logged in as another user.
Here is an example of that value in a recent session
RRetURL "/005A0000001oLiF?noredirect=1" cs8.salesforce.com  /   Session 38 B

Now, I am not sure if that is set elsewhere for some other purpose as well but in this case when logged in as another user this is what appears in the cookie.
Another value in the cookie is login:
login   xxx.xxx@xxx.com.stage   .salesforce.com /   October 20, 2014 at 5:32:35 PM EDT  36 B

And if that value does not match the current value of userInfo.getUserName() then you can tell they are logged in as another user
As context for my answer I am no expert is accessing cookies and if it is not possible to access this cookie in the context in which you are limited to then maybe this information, knowing it exists in a cookie, may help point you to a place where the information is more easily accessible.


text:
Q: How to read and write a vector of struct to a file? I am currently trying to read and write a vector of structs to a binary file, such that I don't spends on preprocessing it with filling it up all the time.
I seem to have some problems doing so... I though that i could std::ofstream but that doesn't seem to be the case.
#include <iostream>
#include <cstdlib>
#include <vector>
#include <fstream>

struct element
{
    std::vector<std::pair<int, int>> coord;
    element(std::vector<std::pair<int, int>> set_coord )
    {
         coord = set_coord;
    }
};

int main()
{
    std::cout << "Hello, Wandbox!" << std::endl;
    std::vector<element> matrix;

    std::ofstream datafile;
    datafile.open("path/to/file");
    datafile<<matrix;
    datafile.close();
}

https://wandbox.org/permlink/urCHoETdh7vE3xlE
I am getting an error message that the operator<< is not valid here... but why?

A: If you want to use the stream operator directly you have to overload it for your struct. Something like this:
#include <iostream>
#include <vector>

struct MyStruct {
    using coordinates = std::vector<std::pair<int, int>>;
    MyStruct(coordinates c) : c(c) {};

    friend std::ostream& operator<<(std::ostream& os, const MyStruct& m) {
        for (const auto &pair : m.c) {
            os << "First: " << pair.first << "; Second: " << pair.second;
        }
        return os;
    }

private:
    coordinates c;
};

class MyVector {
public:
    MyVector(std::initializer_list<MyStruct> list) : elements(list) {}

    friend std::ostream& operator<<(std::ostream& os, const MyVector& m) {
        for (const auto &ms : m.elements) {
            os << ms << std::endl;
        }
        return os;
    }

private:
    std::vector<MyStruct> elements;
};

int main()
{
    MyStruct m1({{1, 2}});
    MyStruct m2({{3, 4}});
    MyVector vec({m1, m2});
    std::cout << vec << std::endl;
    return 0;
}

I've edited the code so it does work with a vector as a member. And in a second edit I am using my own (very basic) vector implementation
Here is the code on wandbox


text:
Q: How to validate JWT Token in aspnet.core web api? I have created custom middleware class which validates the JWT token. I am calling this method before app.AddMvc() in configure method. ***
I would like to know what are the things that I should add to Configuration services to authenticate my web API using JWT? I have added [Authorize] in my Controller class
Do I need to call my middleware class which validates the JWT token first in Configure method? or I should call App.UseAuthentication()
I am using the following order :
 app.UseAuthentication();
 app.MessageHandlerMiddleware();
 app.UseMvc();

I am new to .net web API implementation. Could you please help me out?

A: From one of my answers you can see how we pass JWT token and how the code looks for classic .NET (non-core) ASP.NET WebAPI 2.
There are not many differences, the code for ASP.NET Core looks similar.
The key aspect is - when you add JWT config in Startup the app handles validation automatically.
services
    .AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
        x.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
            ValidAudience = _configuration.GetValidAudience(),
            ValidIssuer = _configuration.GetValidIssuer()
        };
    });

(use the above link to see the implementation of GetSymmetricSecurityKey, GetValidAudience, GetValidIssuer ext. methods)
Also very important part:
services.AddAuthorization(auth =>
{
    auth
    .AddPolicy(
        _configuration.GetDefaultPolicy(),
        new AuthorizationPolicyBuilder()
            .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser().Build()
    );
});


text:
Q: How to perform an task in the background? I want to use WorkRequest to run a task in the background on a daily basis. But I have two problems:

*

*These codes are executed again each time when the app runs.

*When the app is closed, the code will not be executed.

I also want the code to run when the program is closed

A: You can either use a Handler or you can use workManager.
WorkManager works on devices runnig Android 5.0 or higher.So, if your min sdk version is higher or equal to that , prefer using that.Work Manager is used for deferrable tasks generally like sending analytics event etc.

A: You can use WorkManager.enqueueUniquePeriodicWork() method to schedule your work. There will be only one instance of that work.
ExistingPeriodicWorkPolicy.KEEP keeps the existing work and ignore the new request each time the app is started.
Example:
   WorkManager.getInstance(this).enqueueUniquePeriodicWork(
           "UNIQUE_TAG",
           ExistingPeriodicWorkPolicy.KEEP,
           yourWorkRequest
)

Source: https://developer.android.com/topic/libraries/architecture/workmanager/how-to/managing-work#unique-work

A: There are several ways to perform a task in the background threads and not use it from the UI thread.

*

*using the AysnkTask. Tutorial : AsyncTask

*using RxJava. RxJava helps you to perform tasks in other threads and even manage the consequence of a task to perform in which thread. Tutorial RxJava


text:
Q: How to use python to invoke events on a desktop? how to use python to invoke events , like a torrent application and also feeding it with a torrent file in linux ?

A: Most bittorrent apps on Linux will accept a .torrent file as a command line parameter. With some (notable Azureus//Vuze) you may need to use a fully qualified pathname, which you can get with os.path.abspath. Then just use your favorite method of running programs from Python like the subprocess module or even os.system.
If you need to do anything more sophisticated than that you can try looking for a client that supports dbus.

A: If you want to invoke a program from python you can do it like this:
import os
cmd = '/path/to/program'
os.system(cmd)

I cannot say anything about running your bittorrent program, since you haven't said anything about which program you are using, but calling it with an url is probably straight forward (just find the right switch and add the switch and url to the cmd variable above).


text:
Q: Facelets tag for hidden input? There is a Facelets tag for <input type="text">:
<h:inputText />

Is there a Facelets tag for <input type="hidden">?

A: There's the <h:inputHidden> (please bookmark the tag documentation, it shows all available tags).
<h:inputHidden value="#{bean.input}" />

Depending on the concrete functional requirement, this may be not what you're looking for. This does for example not allow you to add an extra request parameter or something. For that you should be using <f:param> in the command component instead. Or if you just want to retain a bean property in the subsequent POST request, rather put the bean in the view scope instead.


text:
Q: keypress event does not triggered after choosing a choice from radio button Using backbone js i want to execute a function while hitting on the ENTER Key.
I have a form :

*

*When i enter a vallue in an input and hit enter, the function is triggered and works fine.

*When i choose a button radio and hitting enter my function isn't called. Not OK

I am using this code in my view:
View.FormCustomer = CommonViews.FormCustomer.extend({
    title : "Ajouter une fiche",
},

events: {
     "keypress": "getKeyCode"
},

getKeyCode: function(e){
    console.log(e.keyCode);
    if(e.keyCode == "13"){
        this.save(e);
    }
},

Does any one have any suggestions?

A: You might have to listen to that keypress event at the document and not in your events object.
...
  initialize: function(){
  var _this = this;

    $(document).on('keypress.namespace', function(){
      _this.someMethod();
    });
    },
  ...
    //you'll have to remove that event when you ditch your view, assuming you have already override your remove method...
    remove: function(){
      $(document).off('.namespace');
    }


text:
Q: Detecting user disconnection in PHP I know that since HTTP is a stateless protocol, this cannot be detected directly. What I need to know is how to achieve this indirectly.
I am making a turn based game in PHP in which two users play over the internet. Need to detect disconnections of any user so that server can end the game and do end-of-the game processes.
I am tracking the last_activity_time of a user based on session, but don't know how to use this to detect a disconnection. Have seen some similar games use this, I can write my code myself once I get the logic. Any help would be much appreciated.


text:
Q: My Local Html Ref is not working for some reason The local referencing does not work for some reason and I have tried countless things. I am using atom.io IDE, can anybody give a proper solution to this please?

CAS DESIGN TECH CLASS

Contents

1 Makey Makey

2 LittleBits

3 Lego Mindstorms

A: The issue you are facing is due to the reason that you have used absolute path name and it doesn't even contains the complete value in the path like "C:\Users\ganeshkumar\website\about.html"
While working in local system, you can try avoiding absolute pathname and use relative pathname. This will help you to overcome the issue.
You can learn more about the path approach in https://www.w3schools.com/html/html_filepaths.asp


text:
Q: What does the keyword "new" do to a struct in C#? In C#, Structs are managed in terms of values, and objects are in reference. From my understanding, when creating an instance of a class, the keyword new causes C# to use the class information to make the instance, as in below:
class MyClass
{
    ...
}
MyClass mc = new MyClass();

For struct, you're not creating an object but simply set a variable to a value:
struct MyStruct
{
    public string name;
}
MyStruct ms;
//MyStruct ms = new MyStruct();
ms.name = "donkey";

What I do not understand is if declare variables by MyStruct ms = new MyStruct(), what is the keyword new here is doing to the statement? . If struct cannot be an object, what is the new here instantiating?

A: From struct (C# Reference) on MSDN:

When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

To my understanding, you won't actually be able to use a struct properly without using new unless you make sure you initialise all the fields manually. If you use the new operator, then a properly-written constructor has the opportunity to do this for you.
Hope that clears it up. If you need clarification on this let me know.

Edit
There's quite a long comment thread, so I thought I'd add a bit more here. I think the best way to understand it is to give it a go. Make a console project in Visual Studio called "StructTest" and copy the following code into it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace struct_test
{
    class Program
    {
        public struct Point
        {
            public int x, y;

            public Point(int x)
            {
                this.x = x;
                this.y = 5;
            }

            public Point(int x, int y)
            {
                this.x = x;
                this.y = y;
            }

            // It will break with this constructor. If uncommenting this one
            // comment out the other one with only one integer, otherwise it
            // will fail because you are overloading with duplicate parameter
            // types, rather than what I'm trying to demonstrate.
            /*public Point(int y)
            {
                this.y = y;
            }*/
        }

        static void Main(string[] args)
        {
            // Declare an object:
            Point myPoint;
            //Point myPoint = new Point(10, 20);
            //Point myPoint = new Point(15);
            //Point myPoint = new Point();

            // Initialize:
            // Try not using any constructor but comment out one of these
            // and see what happens. (It should fail when you compile it)
            myPoint.x = 10;
            myPoint.y = 20;

            // Display results:
            Console.WriteLine("My Point:");
            Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y);

            Console.ReadKey(true);
        }
    }
}

Play around with it. Remove the constructors and see what happens. Try using a constructor that only initialises one variable(I've commented one out... it won't compile). Try with and without the new keyword(I've commented out some examples, uncomment them and give them a try).

A: In a struct, the new keyword is needlessly confusing. It doesn't do anything. It's just required if you want to use the constructor. It does not perform a new.
The usual meaning of new is to allocate permanent storage (on the heap.)
A language like C++ allows new myObject() or just myObject(). Both call the same constructor. But the former creates a new object and returns a pointer. The latter merely creates a temp. Any struct or class can use either. new is a choice, and it means something.
C# doesn't give you a choice. Classes are always in the heap, and structs are always on the stack. It isn't possible to perform a real new on a struct. Experienced C# programmers are used to this. When they see ms = new MyStruct(); they know to ignore the new as just syntax. They know it's acting like ms = MyStruct(), which merely assigns to an existing object.
Oddly(?), classes require the new. c=myClass(); isn't allowed (using the constructor to set values of existing object c.) You'd have to make something like c.init();. So you really never have a choice -- constructors always allocate for classes, and never for structs. The new is always just decoration.
I assume the reason for requiring fake new's in structs is so you can easily change a struct into a class (assuming you always use myStruct=new myStruct(); when you first declare, which is recommended.)

A: Using "new MyStuct()" ensures that all fields are set to some value. In the case above, nothing is different. If instead of setting ms.name you where trying to read it, you would get a "Use of possible unassigned field 'name'" error in VS.

A: Any time an object or struct comes into existence, all of its fields come into existence as well; if any of those fields are struct types, all nested fields come into existence as well.  When an array is created, all of its elements come into existence (and, as above, if any of those elements are structs, the fields of those structs also come into existence).  All of this occurs before any constructor code has a chance to run.
In .net, a struct constructor is effectively nothing more than a method which takes a struct as an 'out' parameter.  In C#, an expression which calls a struct constructor will allocate a temporary struct instance, call the constructor on that, and then use that temporary instance as the value of the expression.  Note that this is different from vb.net, where the generated code for a constructor will start by zeroing out all fields, but where the code from the caller will attempt to have the constructor operate directly upon the destination.  For example: myStruct = new myStructType(whatever) in vb.net will clear myStruct before the first statement of the constructor executes; within the constructor, any writes to the object under construction will immediately operate upon myStruct.

A: Catch Eric Lippert's excellent answer from this thread. To quote him:

When you "new" a value type, three things happen. First, the memory
manager allocates space from short term storage. Second, the
constructor is passed a reference to the short term storage location.
After the constructor runs, the value that was in the short-term
storage location is copied to the storage location for the value,
wherever that happens to be. Remember, variables of value type store
the actual value.
(Note that the compiler is allowed to optimize these three steps into
one step if the compiler can determine that doing so never exposes a
partially-constructed struct to user code. That is, the compiler can
generate code that simply passes a reference to the final storage
location to the constructor, thereby saving one allocation and one
copy.)

(Making this answer since it really is one)

A: ValueType and structures are something special in C#. Here I'm showing you what happens when you new something.
Here we have the following

*

*Code
partial class TestClass {
    public static void NewLong() {
        var i=new long();
    }

    public static void NewMyLong() {
        var i=new MyLong();
    }

    public static void NewMyLongWithValue() {
        var i=new MyLong(1234);
    }

    public static void NewThatLong() {
        var i=new ThatLong();
    }
}

[StructLayout(LayoutKind.Sequential)]
public partial struct MyLong {
    const int bits=8*sizeof(int);

    public static implicit operator int(MyLong x) {
        return (int)x.m_Low;
    }

    public static implicit operator long(MyLong x) {
        long y=x.m_Hi;
        return (y<<bits)|x.m_Low;
    }

    public static implicit operator MyLong(long x) {
        var y=default(MyLong);
        y.m_Low=(uint)x;
        y.m_Hi=(int)(x>>bits);
        return y;
    }

    public MyLong(long x) {
        this=x;
    }

    uint m_Low;
    int m_Hi;
}

public partial class ThatLong {
    const int bits=8*sizeof(int);

    public static implicit operator int(ThatLong x) {
        return (int)x.m_Low;
    }

    public static implicit operator long(ThatLong x) {
        long y=x.m_Hi;
        return (y<<bits)|x.m_Low;
    }

    public static implicit operator ThatLong(long x) {
        return new ThatLong(x);
    }

    public ThatLong(long x) {
        this.m_Low=(uint)x;
        this.m_Hi=(int)(x>>bits);
    }

    public ThatLong() {
        int i=0;
        var b=i is ValueType;
    }

    uint m_Low;
    int m_Hi;
}

And the generated IL of the methods of the test class would be

*

*IL
// NewLong
.method public hidebysig static
    void NewLong () cil managed
{
    .maxstack 1
    .locals init (
        [0] int64 i
    )

    IL_0000: nop
    IL_0001: ldc.i4.0 // push 0 as int
    IL_0002: conv.i8  // convert the pushed value to long
    IL_0003: stloc.0  // pop it to the first local variable, that is, i
    IL_0004: ret
}

// NewMyLong
.method public hidebysig static
    void NewMyLong () cil managed
{
    .maxstack 1
    .locals init (
        [0] valuetype MyLong i
    )

    IL_0000: nop
    IL_0001: ldloca.s i     // push address of i
    IL_0003: initobj MyLong // pop address of i and initialze as MyLong
    IL_0009: ret
}

// NewMyLongWithValue
.method public hidebysig static
    void NewMyLongWithValue () cil managed
{
    .maxstack 2
    .locals init (
        [0] valuetype MyLong i
    )

    IL_0000: nop
    IL_0001: ldloca.s i  // push address of i
    IL_0003: ldc.i4 1234 // push 1234 as int
    IL_0008: conv.i8     // convert the pushed value to long

    // call the constructor
    IL_0009: call instance void MyLong::.ctor(int64)

    IL_000e: nop
    IL_000f: ret
}

// NewThatLong
.method public hidebysig static
    void NewThatLong () cil managed
{
    // Method begins at RVA 0x33c8
    // Code size 8 (0x8)
    .maxstack 1
    .locals init (
        [0] class ThatLong i
    )

    IL_0000: nop

    // new by calling the constructor and push it's reference
    IL_0001: newobj instance void ThatLong::.ctor()

    // pop it to the first local variable, that is, i
    IL_0006: stloc.0

    IL_0007: ret
}

The behaviour of the methods are commented in the IL code. And you might want to take a look of OpCodes.Initobj and OpCodes.Newobj. The value type is usually initialized with OpCodes.Initobj, but as MSDN says OpCodes.Newobj would also be used.

*

*description in OpCodes.Newobj

Value types are not usually created using newobj. They are usually allocated either as arguments or local variables, using newarr (for zero-based, one-dimensional arrays), or as fields of objects. Once allocated, they are initialized using Initobj. However, the newobj instruction can be used to create a new instance of a value type on the stack, that can then be passed as an argument, stored in a local, and so on.

For each value type which is numeric, from byte to double, has a defined op-code. Although they are declared as struct, there's some difference in the generated IL as shown.
Here are two more things to mention:

*

*ValueType itself is declared a abstract class
That is, you cannot new it directly.

*structs cannot contain explicit parameterless constructors
That is, when you new a struct, you would fall into the case above of either NewMyLong or NewMyLongWithValue.
To summarize, new for the value types and structures are for the consistency of the language concept.


text:
Q: User Access Roles In Firestore I have Firestore setup as shown in the images below.

I am trying ensure that a user can only have access to projects of a specific company provided the user is authenticated (email and password), email-verified and is part of the users collection (by verifying with UID) for that company based on a specific role (eg. manager, dancer, choreographer).
I have created some rules as shown below but it is not working as expected. Thank you in advance for the contribution.
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    //create user creates own data in users collection
    match /companies/company_id/users{
        allow create: if request.auth != null && request.auth.token.email_verified == true;
    }

    //user should be allowed to create or delete own data.
    //Only managers should be allowed to delete data of others
    match /companies/company_id/users/{user_id}{
        allow read, delete: if request.auth != null && request.auth.uid == user_id;
    }

    match /companies/{company_id}/projects {
      allow write: if isManager(get(/databases/$(database)/documents/companies/{company_id}/users/$(request.auth.uid))) || isChoreographer(get(/databases/$(database)/documents/companies/{company_id}/users/$(request.auth.uid)));
      allow read: if isDancer(get(/databases/$(database)/documents/companies/{company_id}/users/$(request.auth.uid)));
    }

    match /companies/{company_id}/project/{project_id} {
      allow read, write: if get(/databases/$(database)/documents/companies/{company_id}/users/$(request.auth.uid)) == request.auth.uid;
    }

    function isManager(database){
        return database.data.role == "manager";
    }

    function isChoreographer(database){
        return database.data.role == "choreographer";
    }

    function isDancer(database){
        return database.data.role == "dancer";
    }
  }
}

Any ideas?
EDIT
I have included a curl script I used trying to access one of the firestore rules.
curl --location --request GET 'https://firestore.googleapis.com/v1/projects/project_somthin/databases/(default)/documents/companies/company_a/users/MSTJMcwggcGwrXgEgwl5' \
--header 'Authorization: Bearer token_id'

I go the error:

{
"error": {
"code": 403,
"message": "Missing or insufficient permissions.",
"status": "PERMISSION_DENIED"
} }


text:
Q: TeamCity Github one project works, the other does not Both vcs roots show success when testing the connection, but one always errors on:
git fetch command failed
I did notice that with the project that fails, when I do git bash, I must do git pull origin master instead of just git pull. I made sure both config files under the .git directories are identical (except for the url, of course). I am new to git...
Suggestions?

A: I'm not familiar with TeamCity but if this turns out to be a git problem, you might want to try the following:

*

*Run git remote -v and make sure the URLs are correct.

*Run git branch -vv and verify the branches have valid upstreams, e.g. [origin/master].

*Verify permissions and ownership of all files and directories under .git, both locally and remotely.  I remember having fetch issues caused by bad ownership but I'll admit this looks unlikely in your case.

If that doesn't help, see if you can give us more details, like extra error logs around the "'git fetch' command failed" message.

A: It seems like you set origin in the branch field of VCS root settings, so TeamCity tries to fetch branch refs/heads/origin which doesn't exist. Try to set master there.


text:
Q: Навигационная панель. Убрать через touch Навигационная панель появляется при слайде снизу вверх. Нужно чтобы при таче на экран приложения, панель свернулась обратно.

  @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }
    private void hideSystemUI() {
        // Enables regular immersive mode.
        // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
        // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE
                        // Set the content to appear under the system bars so that the
                        // content doesn't resize when the system bars hide and show.
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        // Hide the nav bar and status bar
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }

    // Shows the system bars by removing all the flags
// except for the ones that make the content appear under the system bars.
    private void showSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

A: Можно сделать через функцию:
public void FullScreencall() {
    if(Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
        View v = this.getWindow().getDecorView();
        v.setSystemUiVisibility(View.GONE);
    } else if(Build.VERSION.SDK_INT >= 19) {
        //for new api versions.
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        decorView.setSystemUiVisibility(uiOptions);
    }
}

Вот так же есть документация по вашему вопросу. Вот есть отдельно написанный класс на гитхабе. Вопрос1 + Вопрос2 по вашей теме.


text:
Q: The Czech company X or simply Czech company X at first mention Imagine the first sentence in a news report, where X and Y are company names:

Czech company X and Tatarstan-based Y have signed an agreement..

Would it be okay to omit the articles? Or would it look better as

The Czech company X and the Tatarstan-based Y have signed an agreement..

It seems to me that without the articles it looks more natural. We're introducing the companies, after all, and it is clear that there are more than one company existing in both the Czech Republic and Tatarstan.
I've googled Google News and found this:

Two other auto manufacturers that are zeroing in on Israel are Spanish company SEAT and Czech company Skoda.

But:

In the next presentation Andrey Denisyuk from the Czech company TESCAN talked about correlative microscopy techniques for electron...

And:

The subcontractor of Spartans is the Czech company Aero Vodochody, which is owned by Penta investment group.

The last two examples could've been written by non-native speakers, but they seem to be okay too..

A: If you omit the name, there is no doubt; an article is required. If we are defining the company, then it's the definite article that is needed:
The Czech company and the Tatarstan-based company have signed an agreement.
Adding the name should make no difference:
The Czech company X and the Tatarstan-based company Y have signed an agreement.
However, as you have observed, it is quite common now for some people to omit the article. My impression is that this is most common in newspapers and television new and documentaries. We seem to have free choice these days.

A: I would  write that sentence as follows:

The Czech company Widgets Inc and Tatarstan-based Gizmos LLC have
  signed an agreement.

That is, I would use the article when "Czech" is the adjective but leave the article out when -based is the adjective and the word "company" is not repeated.


text:
Q: Slow JSON parsing using iOS' NSJSONSerialization I'm seeing performance issues when parsing large JSON using iOS Foundation's NSJSONSerialization. The JSON is roughly:
{
    "things": [
        { "id": 123, "name": "Foo", "weight": 12.34, ... }
        { "id": 456, "name": "Bar", "weight": 56.78, ... }
        ...
    ]
}

There are approximately 1000 things, with each thing having about about 50 name/value pairs.
The parsing code is approximately:
let json = NSJSONSerialization.JSONObjectWithData(data, options: [])
let jsonDict = json as! [String : AnyObject]
let things = jsonDict["things"] as! [[String : AnyObject]]
for thing in things {
    ...
}

Profiling with Instruments, the majority of the time is spent on the second cast (json as! [[String : AnyObject]]), On an iPhone 6 it takes 0.75 sec, on an iPad 4 (32-bit) it takes almost 3 seconds.

Is this just a function of how much data there is? It does after all, have to convert the entire JSON hierarchy into a Dictionary (although I'm surprised the time is spent in the casting and not JSONObjectWithData). Since the JSON is so flat, perhaps I should write my own SAX style parsing.


text:
Q: Append data to wordpress get_header() In my Wordpress theme, I've got few custom post types with custom templates. These templates use additional data like specific CSS or Java Script.
Is there a way to append this kind of data to get_header() function, so i can alter it without hard-copying it inside my custom post type template?
In short, for example. Insert
<link rel="stylesheet" href="<?php echo get_bloginfo('template_url'); ?>/css/interview.css" type="text/css" media="all">
inside
get_header();

A: If I've understood the question correctly then you need something like this:-
function theme_name_scripts() {
   global $post;
   $post_type = get_post_type( $post );
   if( $post_type === 'your-custom-post-type-slug-here' ) { // edit this line as per requirements
      wp_enqueue_style( 'style-interview', get_bloginfo('template_url') . '/css/interview.css' );
   }
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

(Thanks @TopDown for the performance tip in comments.)
You just have to place the above code in your theme's Functions.php. For more info: http://codex.wordpress.org/Function_Reference/wp_enqueue_style


text:
Q: Run time Error 1004 - copy selected sheet failure I'm trying to fix this error for a coworker, but extremely rusty on the code work.
Sub SelectPricingSheet()
'Copy userform1 selected Pricing sheet after Import Sheet.

    CreateSheetList                    ' Subroutine: Build list of Price sheets
    Load UserForm1                     ' Load form to select price sheet
    UserForm1.Show                     ' Show form to select price sheet

    If SelectedSheet <> "" Then        ' Test no selected sheet
        Sheets(SelectedSheet).Copy After:=Sheets("Import") 'Copy selected sheet after Import Sheet
    Else
    End If                              ' No processing
End Sub

Errors out at this line.
Sheets(SelectedSheet).Copy After:=Sheets("Import")          ' Copy selected sheet after the Import Sheet


text:
Q: Include splitted code of react vendor.js chunk in main bundle.js This question is regarding code splitting in react, Let us take an example where I have my bundle.js file
I split it into two files bundle.js and vendor.js, and I can include this in my index.html
index.html
  <script src='./bundle.js'/>
  <script src='./vendor.js'/>

Is there a way so that I can include vendor.js file in my bundle.js file and both file then can be loaded parallel.

A: well.. if you are using webpack as your module bundler, then following piece of code is responsible for code splitting.. Just remove the code responsible for splitting into chunks.
optimization: {
//        splitChunks: {
//          cacheGroups: {
//            commons: {
//              test: /[\\/]node_modules[\\/]/,
//              name: "vendors",
//              chunks: "all"
//            }
//          }
//        }
      }

A: If you are using webpack, it does this automatically for you (If you use dynamic import or set chunks).
But if want to do this manually, you could create a script element in bundle.js. And set async or defer based on your use case.


text:
Q: Powershell loop job in Background I want to start robocopy through a Powershell script invoked by task-scheduler copying files from one server to a list of hosts. It might be that one of the hosts is not available, so I want the copy jobs to start seperatly in the Background like I can do in bash with &.
Is this possible in one Powershell script?
This is what I have:
$i = 1
While ($i -le 9) {
robocopy \\Name_of_Server\share\ \\192.168.17.$i\share\ *.json  /MIR /r:3 /w:10
$i++
}

I tried with invoke-expression, Start-Job, Start-Process,... but no success... Either it does not recognize the loop or missing whatever arguments...
I´m thankful for any hint before letting a linux box do the job... ;-)
Thanks in advance
Lotte


text:
Q: Where does $x_1/2 - x_2$ come from in German wiki branch and bound? This is a German wiki article but the math is probably understandable anyways. There is an example of branch and bound and the concept of dominance is shown. It is applied to an example and they come up with $x_1/2 - x_2$ as a term that should show dominance over the realm of all possible parameters. However, it is not explained at all where this term comes from. I would understand if $x_1$ were set equal to 2 but it is not.
Can anyone help? Here is the link: https://de.wikipedia.org/wiki/Branch-and-Bound#Dominanz


text:
Q: Why is SDL2 window fading out? I want a quick fix to this issue:
I wrote a simple program to play around with the SDL2 libraries. A cyan box moves along a blue background from left to right. Then the window closes.
The problem is that the window's color "fades out" while the program is running. The contrast decreases significantly and it's annoying. Sometimes it happens when the box is in the middle of the window. Sometimes it happens when the box reaches the right side of the window. Sometimes it doesn't happen at all. This fading of colors seems to be sporadic and random. It is a run time issue. Theoretically, I do not see any issue with the code. What is wrong?
#include "SDL.h"
#include <stdio.h>

#ifdef __cplusplus
  extern "C"
#endif
int main(int argc, char* argv[])
{
    SDL_Init(SDL_INIT_VIDEO);

    SDL_Window*   window = NULL;
    SDL_Renderer* renderer = NULL;

    window = SDL_CreateWindow("Boxes", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0);
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    SDL_Rect myBox = { 200, 150, 50, 50  };

    int go = 0;
    while (go <= 590) {
      myBox.x = go;

      SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);

      SDL_RenderClear(renderer);

      SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);

      SDL_RenderFillRect(renderer, &myBox);

      SDL_RenderPresent(renderer);

      if (go == 0)
        SDL_Delay(2000);

      SDL_Delay(100);

      go += 10;
    }

    SDL_Delay(2000);

    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(renderer);

    SDL_Quit();

    return EXIT_SUCCESS;
}

A: That's a classical SDL mistake.
You're not handling events that your window receives, and because of that your OS assumes that your program has hung up.
Inside of your while loop, add following:
SDL_Event e;
while (SDL_PollEvent(&e))
    if (e.type == SDL_QUIT)
        return 0;


text:
Q: How to obtain a safe replacement Windows executable I wish to replace a system file (specifically LogonUI.exe), and traditionally would have done this using a WIndows installation CD and a command such as
expand d:\i386\logonui.ex_ %windir%\system32\logonui.exe

However, as I have no installation media for Windows 10, is there a legal and safe way of obtaining a "vanilla" copy?


text:
Q: Load Testing in Struts2 Application - JMeter I am trying to do a load test using JMeter for the first Time.
My approach is to test each page one by one.

*

*The main page is like http://localhost:8180/myapp/login.do?actionType=login(I hardcoded the credentials)
I am able to reach this page without any problem.

*

*I created a HTTP request component and able to see the response without any issue.

*In the main page there is a button which populates the report, in the browser , the url is like
http://localhost:8180/myapp/mainmenu.do

*

*But when i create a HTTP request it is reaching but shows the security error page in the 'Response
Data' as Due to security reasons, we still recommend you to close this window.
can someone guide me how to test the other pages without these security errors. This is a struts2 Web application.

A: No matter what technology is being used under the hood of the web application you're testing you should stick to one simple rule:
Well-behaved JMeter test must send exactly the same requests as real browser
It includes:

*

*Same number/sequence/nature of the HTTP Requests

*Same HTTP Headers (including Cookies)

any dynamic values need to be properly correlated
Once JMeter will send the same requests as real browser does it should receive the same responses. So just use a 3rd-party sniffer tool like Fiddler or Wireshark to capture the requests originating from browser and JMeter and amend JMeter's configuration until the requests start looking exactly the same. This should resolve your issue.

A: Solved the issue by adding HTTP Cookie Manger and
set Cookie Policy as Standard

click HTTP Cookie Manager

and click save icon on the top.
Source
https://jmeter.apache.org/usermanual/build-web-test-plan.html#adding_cookie_support
Thanks @Dimitri T and @Roman C for their valuable suggestion.


text:
Q: How to improve rendering performance with *ngFor in Angular I am creating a chat app, and performance is slow when a lot of messages are sent at once. The messages show up but the UI becomes unresponsive for a while. Here is a simplified version of the code and how can I fix this?
HTML:
<div class="message-notification" *ngFor="let newMessage of chatMessages"; trackBy: trackByMsgs>
   <custom-notification [incomingChat]="newMessage" (dismissedEvent)="onDismiss($event)" (closedEvent)="onNotifcationClose($event)"></custom-notification>
</div>

TS:
newChatMessages: any[];

constructor(private chatService: ChatService) {}

 ngOnInit() {
    this.chatService.chatMsg.subscribe((msg:any) => {
    if (msg) {
       this.activatePopup(msg);
    }
  }

  activatePopup(message) {
    if (message.msgId !== null && message.title !== null) {
       this.setTitle(message);

    //If popup is already open then do not display a duplicate popup for the same message
         let index = this.isPopupOpen(message);
         if (index === -1) {
           newChatMessages.push(message);
         }else {
           newChatMessages[index] = message;
         }
     }
  }

   trackByMsgs(index:number, msg:any) {
     return msg.msgId && msg.title;
   }

   isPopUpOpen(message){
     let index = -1;
     if (this.newChatMessages){
      index = this.newChatMessages.findIndex(
         msg => msg.id === message.id && msg.title === message.title);
      }
    return index;
   }

A: The best in your case is to control the angular change detection manually by using OnPush Change Detection Strategy. You should carefully use it, cause when it's on, angular will detect changes only if onChanges lifecycle is been triggered or async pipe has received a new value. It also applies to all the component children.
Then you would need to detect the changes manually by injecting the ChangeDetectorRef in your component and call the method detectChanges on it each time you want to apply your data changes to your dom.
Read this article for better understanding
Another interesting article for improving the performance of your angular app https://medium.com/swlh/angular-performance-optimization-techniques-5b7ca0808f8b
Using trackBy helps angular to memorize the loaded elements in the ngFor and update only the changed once on change detection. But your trackByMsgs returns a boolean which is not what it should return. If you adjust your trackBy to return a unique key like msg.msgId or the index of the item, you might see a difference.


text:
Q: Input value from HTML not passing to modal I am trying to pass the reservation id from HTML to modal. In pictures, when I click "cancel" next to reservation:
preview of the screen A modal appears and it should contain the id number of reservation:
preview
Modal pops up but without the reservation id number. Please, what's wrong?
I followed this tutorial: https://www.geeksforgeeks.org/how-to-pass-data-into-a-bootstrap-modal/. Thank you.
Here is my code:
{% extends "layout.html" %}

{% block title %}
    Index
{% endblock %}

{% block main %}

Welcome {{ firstname }}

            Seat
            Start date
            End date
            Number of days
            Action

        {% for histor in history %}

                {{ histor.seat_name }}
                {{ histor.start_date}}
                {{ histor.end_date }}
                {{ numberofdays }}

                    <form action="/" method="post">
                        <input tupe="text" class="form-control"  id="idtocancel" name="idtocancel" autocomplete="on" selected placeholder={{ histor.booking_id }}>
                        <button type="button" id="submit" class="btn btn-success tocancel"  data-toggle="modal" data-target="#exampleModal">Cancel {{ histor.booking_id}}</button>
                    </form>

        {% endfor %}

Do you really wish to cancel this booking?

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

        <button type="button" class="btn btn-secondary" data-dismiss="modal">No, go back</button>

        <input class="form-control"  name="bookId" id="bookId"  autocomplete="on" selected>
        <button type="button" id="submit" class="btn btn-success" data-toggle="modal" data-target="#exampleModal">Yes, cancel the booking</button>

{% endblock %}

A: You are assigning value of {{ histor.booking_id }} to placeholder instead use value="{{ histor.booking_id }}" .Then , use class for click event and inside this get value of input using $(this).prev().val() and put it inside your modal.
Demo Code :

$(".tocancel").click(function() {
  var name = $(this).prev().val(); //use prev
  $("#modal_body").html(name);
  $("#bookId").val(name); //use val here
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

      Seat
      Start date
      End date
      Number of days
      Action

      A
      2-10-1
      10-1-10
      5

        <form action="/" method="post">

          <input type="text" class="form-control" name="idtocancel" autocomplete="on" selected placeholder={{ histor.booking_id }} value="1">
          <button type="button" class="btn btn-success tocancel" data-toggle="modal" data-target="#exampleModal">Cancel 1</button>
        </form>

      B
      2-10-1
      10-1-11
      5

        <form action="/" method="post">
          <input type="text" class="form-control" name="idtocancel" autocomplete="on" selected placeholder={{ histor.booking_id }} value="2">
          <button type="button" class="btn btn-success tocancel" data-toggle="modal" data-target="#exampleModal">Cancel 2</button>
        </form>

Do you really wish to cancel this booking?

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

        <button type="button" class="btn btn-secondary" data-dismiss="modal">No, go back</button>

        <input class="form-control" name="bookId" id="bookId" autocomplete="on" selected>
        <button type="button" id="submit" class="btn btn-success" data-toggle="modal" data-target="#exampleModal">Yes, cancel the booking</button>


text:
Q: Upgrading MongoEngine Document and Embedded Document Schemas I'm wondering if there is a good way to upgrade the schemas in my rigid document/embedded document schemas in Mongoengine 0.9.0 and Mongo 3.0.
I have the most problems with embedded documents, getting the FieldDoesNotExist exception when removing fields from the schema.
mongoengine.errors.FieldDoesNotExist
I have been trying to use _mark_as_changed('field_name') but does not function as I want with embedded documents.
for user in User.objects:
        user.embedded._mark_as_changed('number')
        user.embedded._mark_as_changed('name')
        user.save()

Thanks!


text:
Q: Removing characters from the dataframe python I want to replace a str from one of the column from the table. example: i want to remove b"SET and b"MULTISET from the df column. how to achieve that.
I need output like
Details are as below,
columns = ['cust_id', 'cust_name', 'vehicle', 'details', 'bill']
df = pd.DataFrame(data=t, columns=columns)
df

        cust_id     cust_name                   vehicle                             details                                                 bill
0   101         b"SET{'Tom','C'}"           b"MULTISET{'Toyota','Cruiser'}"     b"ROW('Street 1','12345678','NewYork, US')"             1200.00
1   102         b"SET{'Rachel','Green'}"    b"MULTISET{'Ford','se'}"            b"ROW('Street 2','12344444','Florida, US')"             2400.00
2   103         b"SET{'Chandler','Bing'}"   b"MULTISET{'Dodge','mpv'}"          b"ROW('Street 1','12345555','Georgia, US')"             601.10

Required Output:
    cust_id     cust_name                   vehicle                             details                                         bill
0   101         {'Tom','C'}                 {'Toyota','Cruiser'}            ('Street 1','12345678','NewYork, US')               1200.00
1   102         {'Rachel','Green'}          {'Ford','se'}                   ('Street 2','12344444','Florida, US')               2400.00
2   103         {'Chandler','Bing'}         {'Dodge','mpv'}                 ('Street 1','12345555','Georgia, US')               601.10

A: Here is a possible solution,

*

*Let's define column of interest,

columns = ['cust_name', 'vehicle', 'details']

*

*Use regex expression to extract values between {} or ()
regex_ = r"([\{|\(].*[\}|\)])"

*

*Putting together, str.decode('ascii') is to convert columns values from byte to string.

columns = ['cust_name', 'vehicle', 'details']

regex_ = r"([\{|\(].*[\}|\)])"

for col in columns:
    df[col] = df[col].str.decode('ascii').str.extract(regex_)

   cust_id            cust_name  ...                                details    bill
0      101          {'Tom','C'}  ...  ('Street 1','12345678','NewYork, US')  1200.0
1      102   {'Rachel','Green'}  ...  ('Street 2','12344444','Florida, US')  2400.0
2      103  {'Chandler','Bing'}  ...  ('Street 1','12345555','Georgia, US')   601.1


text:
Q: Validating Folder Selection In the portion of the code below I have a Function called FolderPick which returns the file path of a selected folder via a dialogue box.  I then strip the folder path down to find the name of the selected selected folder.  That all works as intended.
What I would like to do is verify that the name of the selected folder is one of the approved names.  I was initially thinking of using a series of IF statements, then I thought about using the case statement.  So I am pretty sure the syntax for my CASEs are wrong and that you can only have one value per case.
Is my only choice here an IF statement with a lot of ORs?
Also is there a format for a catch all CASE?  i.e. none of the previous cases were a match so do this?
Pickafolder:

FolderPath = FolderPick

Foldername = Left(FolderPath, Len(FolderPath) - 1)
Foldername = RIght(Foldername, Len(Foldername) - InStrRev(Foldername, "\"))

Select Case Foldername
    Case Foldername = "OPSS" Or Foldername = "SSP" Or Foldername = "OPSD" Or Foldername = "MTOD" Or Foldername = "SSD"

        'do something

    Case Foldername = "West" Or Foldername = "Eastern" Or Foldername = "Northeastern" Or Foldername = "Northwestern" Or Foldername = "Head Office"

        'inser "NSP\ before foldername

    Case Foldername = "NSP"

        'msgbox "Pick the  NSP sub folder"
        GoTo Pickafolder

    Case Foldername <> any other case

        'msgbox "Inappropriate directory to upload from. Please select one of the CPS download directories"
        GoTo Pickafolder

 End Select

A: Try this, you can use "," instead of OR
Select Case FolderName
    Case "OPSS", "SSP", "Something", "MTOD", "SSD"

        'do something

    Case "West", "Eastern", "Northeastern", "Northwestern", "Head Office"

        'inser "NSP\ before foldername

    Case "NSP"

        'msgbox "Pick the  NSP sub folder"
        'GoTo Pickafolder

    Case Else

        'msgbox "Inappropriate directory to upload from. Please select one of the CPS download directories"
        'GoTo Pickafolder

 End Select


text:
Q: looping Get-ReceiveConnector to grab multiple receive connectors This is on a Windows 2008R2 server running Exchange2010.
I would like to use powershell and "Get-ReceiveConnector" to grab information from about 20 configured receive connectors.  Ultimately we are migrating to a different exchange server, so my goal is to export them to text and then import them later.
This article: http://terenceluk.blogspot.com/2010/11/how-do-i-exportimport-exchange-20072010.html gives some good info on pulling the data from individual receive connectors, but I'd like to use foreach or something similar to loop through all receive connectors on that particular server - I'm just not sure how to do it.
Thanks!

A: This isn't too tough, it's Powershell 101 really. If you're going to be doing a bunch of Exchange work, you'll definitely need to learn PS front to back.
$conns = Get-ReceiveConnector
foreach ($conn in $conns) {$conn.name }

If you need to limit it to only a specific server, do this
$conns = Get-ReceiveConnector -server MyServerName
foreach ($conn in $conns) {$conn.name }

In the examples, above, I'm just listing the connector name in the body of the loop - the statement in between the curly brackets. You would replace that with whatever it is that you want to do with each connector.


text:
Q: How to pass a query set to the context class in Django? I am trying to pass a queryset object to django context class, but doing so results in the following error: TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
Now i understand that the context accepts only a dictionary but i am following an example from a book called django_unleashed which uses Django version 1.8 and i am using django 2.0. and i guess it was done like that in previous versions.
So my question is how should i do this step correctly using django 2.0
from django.shortcuts import render
from django.http import HttpResponse
from .models import Tag
from django.template import Context, loader

def homepage(request):
    tag_list = Tag.objects.all()
    template = loader.get_template('organizer/tag_list.html')
    context = Context({'tag_list': tag_list})
    output = template.render(context)
    return HttpResponse(output)

A: As the error suggests, you should use a regular dictionary for the context:
def homepage(request):
    tag_list = Tag.objects.all()
    template = loader.get_template('organizer/tag_list.html')
    context = {'tag_list': tag_list}
    output = template.render(context)
    return HttpResponse(output)

In practice, you would usually use the render shortcut rather than manually rendering the template:
from django.shortcuts import render

def homepage(request):
    tag_list = Tag.objects.all()
    context = {'tag_list': tag_list}
    return render(request, 'organizer/tag_list.html', context)

A: '''you have a model class named 'Tag',
wish your template is on ' Project directory/ app directory/ template/ same name of app directory'
example: let your project name is 'Website' and app name is 'organizer' then the template will be on: 'Website/ organizer/ templates/ organizer/ tag_list.html' Confirm your TEMPLATES setting is default on setting.py file."'
from django.shortcuts import render
from .models import Tag
def homepage(request):
    tag_list  = Tag.objects.all()
    context =  { 'tag_list' : tag_list}
    return render ( request, 'organizer/tag_list.html', context)


text:
Q: Anchors badly positioned I am trying to overlay some transparent boxes over a picture using TikZ within a Beamer frame. The code I use is the following:
\documentclass{beamer}
\usepackage[spanish]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usetikzlibrary{arrows,shapes,positioning}

\begin{document}
\begin{frame}
\begin{tikzpicture}[remember picture, overlay]
    \onslide<1->{
        \draw []
            (-0.95,-2.75) rectangle (1.5,-4.00)
            node (rNode) {};

        \tikzset
            {pt/.style={circle,fill=red,inner sep=0mm,minimum size=4pt}}
        \node[pt] at (rNode.center){};
        \node[pt] at (rNode.west){};
        \node[pt] at (rNode.south){};
        \node[pt] at (rNode.east){};
        \node[pt] at (rNode.north){};
    };
\end{tikzpicture}
\end{frame}
\end{document}

The problem is that the anchors of the TikZ rectangles that I create are incorrect: they seem to be the anchors of a different rectangle that I did not create). I would like to know what I am doing wrong and how to solve this problem.

A: Disclaimer
The other answers already explain the problem, but I start write the same motivation before dinner, so I left it anyway.

Actually, the behaviour you're facing is correct because when you use
\draw []
     (-0.95,-2.75) rectangle (1.5,-4.00)
     node (rNode) {};

you're placing the node just in the lower right corner, but the node does not have the dimension of the rectangle. You have already prove this with your example, but just to emphasize it a bit, here is another proof. The following example will place a cross out node exactly on rNode:
\documentclass[tikz,png,border=2pt]{standalone}
\usetikzlibrary{backgrounds,shapes.misc,positioning}

\begin{document}
\begin{tikzpicture}
    \draw []
        (-0.95,-2.75) rectangle (1.5,-4.00)
        node (rNode) {};
    \node[draw,cross out,blue,scale=1.1] at (rNode){};

    \begin{scope}[on background layer]
    \tikzset
        {pt/.style={circle,fill=red,inner sep=0mm,minimum size=4pt}}
    \node[pt] at (rNode.center){};
    \node[pt] at (rNode.west){};
    \node[pt] at (rNode.south){};
    \node[pt] at (rNode.east){};
    \node[pt] at (rNode.north){};
    \end{scope}
\end{tikzpicture}
\end{document}

The result:

Thus the correct way is to use the standard shape rectangle inside a \node:
\documentclass{beamer}
\usepackage[spanish]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usetikzlibrary{arrows,shapes,positioning}

\begin{document}
\begin{frame}
\begin{tikzpicture}[remember picture, overlay]
    \onslide<1->{
        \node[rectangle, draw, minimum height=1.25cm, minimum width=2.45cm]
           (rNode) at (0.275,-3.375){};

        \tikzset
            {pt/.style={circle,fill=red,inner sep=0mm,minimum size=4pt}}
        \node[pt] at (rNode.center){};
        \node[pt] at (rNode.west){};
        \node[pt] at (rNode.south){};
        \node[pt] at (rNode.east){};
        \node[pt] at (rNode.north){};
    };
\end{tikzpicture}
\end{frame}
\end{document}

The result:

To come back to the original question, the best thing to do is to include inside a \node your images with the inner sep option set to 0pt (to have exactly the anchors on the border); for example:
\documentclass{beamer}
\usepackage[spanish]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{mwe} % for dummy images
\usepackage{tikz}
\usetikzlibrary{arrows,shapes,positioning}
\tikzset{pt/.style={
  circle,
  fill=blue,
  inner sep=0mm,
  minimum size=1pt,
  }
}
\tikzset{legend/.style={
  rectangle,
  rounded corners,
  draw,
  top color=white,
  bottom color=#1,
  align=center,
  font=\footnotesize,
  }
}

\begin{document}
\begin{frame}
\begin{tikzpicture}[remember picture, overlay]
    \onslide<1->{
        \node[inner sep=0pt](rNode) at (2,0){\includegraphics[scale=0.3]{example-image}};

        \node[pt] at (rNode.center){};
        \node[pt] at (rNode.west){};
        \node[pt] at (rNode.south){};
        \node[pt] at (rNode.east){};
        \node[pt] at (rNode.north){};

        \node[legend={red},anchor=south west,yshift=1ex] at (rNode.north) {Some description};
        \node[legend={red},anchor=north east,yshift=-1ex,text width=1.75cm] at (rNode.south) {Some other description};
    };
    \onslide<2->{
        \node[inner sep=0pt](xNode) at (8,2){\includegraphics[scale=0.3]{example-image-a}};

        \node[pt] at (xNode.center){};
        \node[pt] at (xNode.west){};
        \node[pt] at (xNode.south){};
        \node[pt] at (xNode.east){};
        \node[pt] at (xNode.north){};

        \node[legend={cyan!60!blue!60},anchor=west,xshift=1em,text width=1cm] at (xNode.east) {Some other text};
    };
    \onslide<3->{
        \node[inner sep=0pt](yNode) at (8,-2){\includegraphics[scale=0.3]{example-image-b}};

        \node[pt] at (yNode.center){};
        \node[pt] at (yNode.west){};
        \node[pt] at (yNode.south){};
        \node[pt] at (yNode.east){};
        \node[pt] at (yNode.north){};

        \node[legend={green!60!lime!60},anchor=west,xshift=1em,text width=1cm] at (yNode.east) {Some other text};
        \node[legend={green!60!lime!60},anchor=north,yshift=-1ex] at (yNode.south) {Yet another description};

    };

    \draw<4->[-stealth,red](rNode.east)--(xNode.west);
    \draw<5->[-stealth,red](xNode.south)--(yNode.north);
    \path<6->[-stealth,red](yNode.west)edge[bend left](rNode.south);

\end{tikzpicture}
\end{frame}
\end{document}

The result:

Notice how in such a way you can access the standard anchors of the nodes you created to place arrows or descriptive text.
For completeness, if instead you have to make operations inside a single picture the best procedure is to refer to In a beamer slide highlight a region of an image with a rectangle overlay. That approach uses coordinates, but you can always use the anchors (perhaps with the help of the calc library).
An example:
\documentclass{beamer}
\usepackage[spanish]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{mwe} % for dummy images
\usepackage{tikz}
\usetikzlibrary{calc}
\tikzset{pt/.style={
  circle,
  draw=blue,
  fill=green!50!lime,
  inner sep=0mm,
  minimum size=3pt,
  }
}
\tikzset{legend/.style={
  rectangle,
  rounded corners,
  draw,
  top color=white,
  bottom color=#1,
  align=center,
  font=\footnotesize,
  }
}

\begin{document}
\begin{frame}
\begin{tikzpicture}[remember picture, overlay]
    \onslide<1->{
        \node[inner sep=0pt](rNode) at (5.5,0){\includegraphics[scale=0.75]{example-image}};

        \foreach \anchor in
        {north,south,east,west,center,north west,north east,
        south west, south east,center}{
        \node[pt] at (rNode.\anchor){};
        }

    };
    \node<2->[legend={red},anchor=south west,yshift=1ex] (x) at ($(rNode.north)!0.5!(rNode.center)$) {Some description};
    \node<3->[legend={red},anchor=north east,yshift=-1ex,text width=1.75cm]
     (y) at ($(rNode.south)!0.65!(rNode.center)$) {Some other description};

    \path<4->[-stealth,red, thick](y.west) edge[bend left, looseness=2](x.west);

\end{tikzpicture}
\end{frame}
\end{document}

The result:

A: Your problem is the definition of your node, i.e. you do not define a rectangle node.
This code:
\draw []
    (-0.95,-2.75) rectangle (1.5,-4.00)
    node (rNode) {};

means:

*

*Draw a rectangle between (-0.95,-2.75) and (1.5,-4.00)

*Then draw an empty ({}) text node at (1.5,-4.00), named rNode

Your empty text node has a rectangular shape by default, with width and height equal to 2 x inner sep.
So, when you write (rNode.south), Tikz draw at the right place :-)
You may better write your first rectangle like this:
\node[draw,minimum width=2.45cm,minimum height=1.25cm] (rNode) at (.275,-3.375) {};


text:
Q: Respond to user who made server request Say for example that a user made a log in request and I want the server to emit a message to him, but nobody else. How would I accomplish such a thing using socket.io? Here is what I have so far:
var users = []; // List of usernames

io.on("connection", handleIO);

function handleIO(socket){
    console.log('Client connected...');

    socket.on('login', function(data){ // When user presses login button
        users.push(data);

    });
}

How can I then send the user who made the 'login' request a socket event. Is there a socket.emit that just emits to the user who made the request?

A: You just use .emit() on the incoming socket:
var users = []; // List of usernames
io.on("connection", handleIO);

function handleIO(socket){
    console.log('Client connected...');

    socket.on('login', function(data){ // When user presses login button
        users.push(data);
        socket.emit("Welcome!");
    });
}


text:
Q: How to check if a div is visible state or not? I have tabs like this.
<li id="singlechatpanel-1" style="visibility: hidden;">
     //content
</li>

Trying to check it like this:
$(".subpanel a").click(function()
     {
        var chatterNickname = $(this).text();

        if(!$("#singlechatpanel-1").is(':visible'))
        {
            alert("Room 1 is filled.");
            $("#singlechatpanel-1").css({'visibility':'visible'});
            $("#singlechatpanel-1 #chatter_nickname").html("Chatting with: " + chatterNickname);
        }

If condition always returns false. How can I check visibility state of this div?

A: You can use .css() to get the value of "visibility":
 if( ! ( $("#singlechatpanel-1").css('visibility') === "hidden")){
 }

http://api.jquery.com/css/

A: Check if it's visible.
$("#singlechatpanel-1").is(':visible');
Check if it's hidden.
$("#singlechatpanel-1").is(':hidden');

A: is(':visible') checks the display property of an element, you can use css method.
if (!$("#singlechatpanel-1").css('visibility') === 'hidden') {
   // ...
}

If you set the display property of the element to none then your if statement returns true.

A: if (!$('#singlechatpanel-1').css('display') == 'none') {
   alert('visible');
}else{
   alert('hidden');
}

A: You can use (':hidden') method to find if your div is visible or not..
Also its a good practice to cache a element if you are using it multiple times in your code..
$(".subpanel a").click(function()
     {
        var chatterNickname = $(this).text();
        var $chatPanel = $("#singlechatpanel-1");

        if(!$chatPanel.is(':hidden'))
        {
            alert("Room 1 is filled.");
            $chatPanel.show();
            $("#singlechatpanel-1 #chatter_nickname").html("Chatting with: " + chatterNickname);
        }
});

A: if element is hide by jquery then use
if($("#elmentid").is(':hidden'))

A: Add your li to a class, and do $(".myclass").hide(); at the start to hide it instead of the visibility style attribute.
As far as I know, jquery uses the display style attribute to show/hide elements instead of visibility (may be wrong on that one, in either case the above is worth trying)

A: You can do it by any of these two ways:
$("#elementId").css('visibility')
and
$("#elementId").is(':visible');

if your element is visible then
$("#elementId").css('visibility') will return "visible"
and
$("#elementId").is(':visible') will return true

but if your element is NOT visible then
$("#elementId").css('visibility') will return undefined
and
$("#elementId").is(':visible') will return false


text:
Q: Drawn Squares Constantly Flicker Between Assigned Colors I am very new to GameMaker 1.4, but I have some experience with Python and C++. I have created a matrix of random ints between 1 and 5 inclusive to represent the number of stories each building on a map has. I want to use this to draw a 10x10 set of squares with lighter grey squares representing taller buildings. Unfortunately, I can't get the squares to stay the same color. They constantly flicker between colors.
How can I get them to stop flickering and represent their relevant values appropriately?
Here is my script:
// Random 2D Map Height Generator

/*
Generates a matrix which is used for determining
 the amount of stories per building in the game.

 Then draws squares of different colors to represent
 the number of stories of each building.
*/

ct = irandom(1);
// create array
for (i = 0; i <= global.height; i += 1) {
   for (j = 0; j <= global.width; j += 1) {
      mapArray[i, j] = irandom_range(1, 5);
      if (ct % 2 != 0 && mapArray[i, j] < 5) {
      mapArray[i, j] += 1;
   }
   ct += 1;
   }
}

// make colors
one = make_color_rgb(0, 0, 0);
two = make_color_rgb(51, 51, 51);
three = make_color_rgb(102, 102, 102);
four = make_color_rgb(153, 153, 153);
five = make_color_rgb(204, 204, 204);

// initialize coordinates
ex = 300;
wy = 100;

// count columns

// draw map
for (i = 0; i <= global.height; i += 1) {
   for (j = 0; j <= global.width; j += 1) {
      ex2 = ex + 30;
      wy2 = wy + 30;
      switch (mapArray[i, j])
      {
         case 1:
            draw_set_color(one);
            break;
         case 2:
            draw_set_color(two);
            break;
         case 3:
            draw_set_color(three);
            break;
         case 4:
            draw_set_color(four);
            break;
         case 5:
            draw_set_color(five);
            break;
         default:
            draw_text(200, 200,
            "ERROR: scr_mapGeneration, case not met");
            break;
      }
      draw_rectangle(ex, wy, ex2, wy2, false);
      ex += 33;
      if (j == global.width) {
         wy += 33;
         ex = 300;
      }
   }
}

I call it in an object with the draw event and execute this code with it:
script_execute(scr_mapGeneration);

I call randomize(); in my initial room's creation code. The problem occurs in another room.
Here is a picture of what is produced, obviously this picture doesn't have flickering squares.

Please let me know if you need any more information.

A: The problem was that I had included all of the text as part of a draw event. So the array was constantly remade. The solution is to separate the array-making code and execute it under a different event. I used the creation event for this.
I would provide a detailed example, but it's difficult given the nature of the GameMaker program, and the solution should be self-explanatory anyway.

A: The colors are constantly new assigned with new random values, since the draw funtion is called every frame.
randomize() does have nothing to do with your problem, random always creates a new random, it just changes the random seed. ;)
You should call the script in the create event once, and instead of drawing the rectangles you store them in e.g. a ds_grid (more info here)
In the draw funtion you just draw the saved values from the grid.


text:
Q: Why does this program stop running after two guesses? I am creating a simple C# console application game that creates a random number, then displays either "too high", "too low" or "correct", it is then supposed to ask the user to input another number & then tell them whether that number is "too high", "too low" or "correct", once the right number is guessed, it should say "correct" and then display the number of guesses it took to get the correct number (this part I'm not sure how to do). Besides that I've created the code & it will tell you whether your guess is too high or too low, and once you try to enter a second guess it automatically says it's correct. How can I get the program to read more guesses, and how do I display the number of guesses?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _5.Number_Game
{
    class Program
    {
        static void Main(string[] args)
        {
            double response, guess;
            Random random = new Random();
            int randomNumber = random.Next(1, 101);
        do
        {
            Console.WriteLine("Enter your guess for a random number between 1 & 100");
            guess = double.Parse(Console.ReadLine());
            if (guess > randomNumber)
                Console.WriteLine("Too high");

            if (guess < randomNumber)
                Console.WriteLine("Too low");

            if (guess == randomNumber)
                Console.WriteLine("Correct!");

             Console.WriteLine("Enter another number");

             response = double.Parse(Console.ReadLine());
        }
        while (response <= 1 && response >=100);
        Console.WriteLine("Correct, Goodbye!");
        Console.ReadLine();
        }
    }
}

A: Your "while" condition isn't right, it currently checks if the number is within the 1-100 range while it should check if it was the right number.
I would change it to:
while(guess != randomNumber);

or break when it is on the correct value:
if (guess == randomNumber)
{
    Console.WriteLine("Correct!");
    break;
}

I would also note that your "response" value is currently useless once you fix your algorithm.

A: You didn't need your guess as a double as the random number will only generate an integer. Also the responce variable is also not needed, as the loop can just be looped until:
while(guess != randomNumber);

Like the above answer said. If you would like to add a count of how many guesses the user takes to guess the number, add a count variable before the the opening 'do' loop.
int count = 0;
do
{

And in each guess where the user doesn't guess it correctly increment the count by one, just like this:
if (guess > randomNumber)
{
Console.WriteLine("Too high");
count += 1;
}

if (guess < randomNumber)
{
Console.WriteLine("Too low");
count += 1;
}

Then at the end when user guesses correctly
if (guess == randomNumber)
{
 Console.WriteLine("Correct!");
 Console.WriteLine("You took " + count + "guesses, to guess that number.");
}


text:
Q: Why does string.Join(" ", new object[] { null, "a", null, "b"}) retruns string.Empty? I noticed that string.Join(" ", new object[] { null, "a", null, "b"}) returns string.Empty
Notice that string.Join(" ", new string[] { null, "a", null, "b"}) returns a  b (as I would expect)
Things get vicious when concatenating characters:
string.Join(" ", new object[] { null, 'a', null, 'b'}) which also returns string.Empty
Edit: Even though the documentation says it (thanks to @elgonzo), is there a valid reason such exception was implemented in the framework ?
See https://dotnetfiddle.net/uM9SVp

A: As per the docs:

Notes to Callers
If the first element of values is null, the Join(String, Object[])
  method does not concatenate the elements in values but instead returns
  Empty. A number of workarounds for this issue are available. The
  easiest is to assign a value of Empty to the first element of the
  array, as the following example shows.

object[] values = { null, "Cobb", 4189, 11434, .366 };
if (values[0] == null) values[0] = String.Empty;
Console.WriteLine(String.Join("|", values));
// The example displays the following output:
//      |Cobb|4189|11434|0.366

I suggest you read it up, pretty interesting.


text:
Q: Grab the data exceed one more day select CASE
WHEN (shipment_date >=((to_char(shipment_date, 'dd-Mon-yyyy 08:00')::timestamp)) and shipment_date < ((to_char(shipment_date, 'dd-Mon-yyyy 20:00')::timestamp )))
THEN to_char(shipment_date, 'dd/MM/yyyy 08:00')
WHEN (shipment_date >=((to_char(shipment_date, 'dd-Mon-yyyy 20:00')::timestamp)) and shipment_date < ((to_char(shipment_date + interval '1' day, 'dd-Mon-yyyy 08:00')::timestamp )))
THEN to_char(shipment_date, 'dd/MM/yyyy 20:00')
END as shipment_date_sort,
COUNT(lotnumber)
from shipping.picklist_lots
inner join shipping.picklist on picklist_lots.picklist_id = picklist.picklist_id
where shipment_date >= '12/23/2014' and shipment_date < '12/24/2014'
GROUP BY shipment_date_sort

it doesnt give me the result which the shipment date between 24/12/2014 00:00 and 24/12/2014 08:00
i need it

A: where shipment_date >= '12/23/2014' and shipment_date < '12/24/2014'

Add a time value. According to your datetime value, 24/12/2014 00:00, it should be in format (dd/MM/yyyy 00:00)
where shipment_date >= '23/12/2014' and shipment_date <= '24/12/2014 23:59'

A: Based on logical query processing, you cannot use alias of your SELECT statement in group by because SELECT happens after GROUP BY so you need to duplicate your CASE statement into your GROUP BY part.
LOGICAL QUERY PROCESSING


text:
Q: a confusing way to define C structure I am a newbie in C and I stumbled on this c-structure:
typedef struct
{
   int dog;
   int cat;
} FOO;

typedef struct
{
   int  id;
   FOO* pRow[0]
} BAR;

I know basic c and c++ but I have no idea the motivation of the following line: "FOO* pRow[0]".
If the author wants to define a pointer to an array of FOO, then he/she should just define it as "FOO* pROW", right? Why does pROW[0] stands for in this case then?
Please enlighten me.
Thanks!

A: the pRow  is an array of pointers. the first element ,pRow[0] is pointing to a FOO struct.
if you write FOO* pRow,  then the pRow is simply one pointer