text:
Q: Submit a CheckBox generados dinámicamente en ASP.Net MVC Estoy tratando de enviar un modelo que tiene una lista de CheckBox a un controlador pero no no estoy obteniendo los valores:

            @for (var index = 0; index < Model.anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList.Count; index++ )
            {

                        @Html.HiddenFor(m => Model.anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[index].CodSecRep)
                        @Html.HiddenFor(m => Model.anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[index].IdCtaAnaSin)
                        @Html.HiddenFor(m => Model.anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[index].IdRepAnaSin)
                        @Html.EditorFor(m => Model.anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[index].BSecDisp)

                        @Html.LabelFor(m => Model.anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[index].BSecDisp,
                                            Model.anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[index].TxDescSecRep)

            }

El HTML que se genera es:
<form action="/Cuentas/ConfigurationReport/SaveConfigReport" data-ajax="true" data-ajax-failure="onFailureFormSaveConfigReport" data-ajax-method="POST" data-ajax-success="onSuccessFormSaveConfigReport" id="FormConfigReport" method="post" novalidate="novalidate"><input name="__RequestVerificationToken" type="hidden" value="OgTElcNJVXowlUWtjZDHDdhvDmsIa9PBUjOvgS2QKAB7_rEUKYjKQsRYkBypDmBoVrUoGFmc3eRI6b-SIIYA2A1appYq_VISEfX_hwDygZakfkfpKawYLMfFQG0bwb_d0Lo3GA2"><input data-val="true" data-val-number="The field IdCtaAnaSin must be a number." data-val-required="El campo IdCtaAnaSin es obligatorio." id="IdCtaAnaSin" name="IdCtaAnaSin" type="hidden" value="0"><input data-val="true" data-val-number="The field IdRepAnaSin must be a number." data-val-required="El campo IdRepAnaSin es obligatorio." id="IdRepAnaSin" name="IdRepAnaSin" type="hidden" value="0"><input id="hidden_TipoReporte" name="anaSinConfiguracionReporte.CodTypeReport" type="hidden" value="TR_BAS"><input data-val="true" data-val-number="The field IdRepAnaSinCompare must be a number." data-val-required="El campo IdRepAnaSinCompare es obligatorio." id="hidden_ComparacionReporte" name="anaSinConfiguracionReporte.IdRepAnaSinCompare" type="hidden" value="0"><input id="anaSinConfiguracionReporte_ExpRasSecRepAnaSinDtoList" name="anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList" type="hidden" value="System.Collections.ObjectModel.Collection`1[Lms.AnalizadorSiniestralidad.Entities.ExpRasSecRepAnaSinDto]">

    Tipo de Reporte

        Tipo:

        <select id="drpTipoReporte" class="valid">
                <option value="TR_BAS">Basico</option>
                <option value="TR_COM">Comparativo</option>
        </select>

            Reporte de comparación:

            <select id="drpReporte"></select>

    Secciones Disponibles

                        <input id="anaSinConfiguracionReporte_ExpRasSecRepAnaSinDtoList_0__CodSecRep" name="anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[0].CodSecRep" type="hidden" value="BALANCE_GENERAL">
                        <input data-val="true" data-val-number="The field IdCtaAnaSin must be a number." data-val-required="El campo IdCtaAnaSin es obligatorio." id="anaSinConfiguracionReporte_ExpRasSecRepAnaSinDtoList_0__IdCtaAnaSin" name="anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[0].IdCtaAnaSin" type="hidden" value="0">
                        <input data-val="true" data-val-number="The field IdRepAnaSin must be a number." data-val-required="El campo IdRepAnaSin es obligatorio." id="anaSinConfiguracionReporte_ExpRasSecRepAnaSinDtoList_0__IdRepAnaSin" name="anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[0].IdRepAnaSin" type="hidden" value="0">
                        <input class="check-box valid" data-val="true" data-val-required="El campo BSecDisp es obligatorio." id="anaSinConfiguracionReporte_ExpRasSecRepAnaSinDtoList_0__BSecDisp" name="anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[0].BSecDisp" type="checkbox" value="true"><input name="anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[0].BSecDisp" type="hidden" value="true">

                        Balance General

        <input type="button" id="btnGenerarReporte" class="ResourceButton_GenerateReport" value="Genera Reporte" onclick="sendDataForm()">

    <input type="button" id="btnRegresar" class="ResourceButton_Return">

Mi controlador con el Action es el siguiente, la lista dentro del modelo siempre viene con 0 items:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult SaveConfigReport (NuevaCargaArchivoViewModel model, CaseResponseDto caseResponseDto )
    {
        IEnumerable<string> businessExceptionArray = null;
        RasSecRepAnaSinBl rasSecRepAnaSinBl = new RasSecRepAnaSinBl();
        businessExceptionArray = rasSecRepAnaSinBl.InsertOrUpdate(model.anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList);

        if ( null != businessExceptionArray )
        {
            caseResponseDto.ValBool = !IS_GENERATE_REPORT;
            caseResponseDto.Error = true;
            caseResponseDto.Titulo = TITLE_ERROR;
            caseResponseDto.Mensaje = string.Format(MESSAGE_ERROR, businessExceptionArray.ElementAt(0));
        }
        else
        {
            caseResponseDto.ValBool = IS_GENERATE_REPORT;
            caseResponseDto.Error = false;
            caseResponseDto.Titulo = TITLE_SUCCESSFULL;
            caseResponseDto.Mensaje = MESSAGE_SUCCESSFULL;
        }

        return Json(caseResponseDto);
    }

A: El html tiene tu input con su propiedad.
 name = anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[0].IdCtaAnaSin

Lo que necesitas es que cada name sea incremental para cada input. Por ejemplo:
anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[0].IdCtaAnaSin
anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[1].IdCtaAnaSin
anaSinConfiguracionReporte.ExpRasSecRepAnaSinDtoList[2].IdCtaAnaSin

... etc.
Con eso ya el controller agarra tu lista que envíes.


text:
Q: Trying to design Billiard game in HTML to make jQuery game - My First Project I am taking a whirl at my first project.  I am learning as I go.  I am trying to build a Billiard Game with jQuery.  I am at the very beginning.  I need to line up the balls first.  Can anyone give me some ideas.  So far this is where I am.  I need to initiate the balls like 5,4,3,2,1 and at the center of the table.

(1)

(2)

(3)

(4)

(5)

(6)

(7)

(8)

(9)

(10)

(11)

(12)

(13)

(14)

(15)

Here's my CSS:
body {
background:green;
margin: 0 auto;
}

#container {

}

.table-layout {
margin-left: auto;
margin-right: auto;
width: 450px;
height: 600px;
border: 2px solid gold
}

.ball-holder {
width: 300px;
margin: -100px auto;
}

.holder-row {
display: block;
width: 300px;
text-align: center;
}

.ball {
width:30px;
height:30px;
border-radius:100%;
background-color:red;
display: inline-block;
}

.qball {
width:30px;
height:30px;
border-radius:100%;
background-color:white;
display: block;
margin-left: auto;
margin-right: auto;
margin-top: 220px;
}

h1 {
text-align:center;
font-size:10px;
font-family:arial;
color:white;
}

.pocket {
width:40px;
height:40px;
border-radius:100%;
border:2px solid black;
background-color:black;
display: inline-block;
}

.left-top {

}

.right-top {
margin-left: 405px;
margin-top: -48px;
}

.left-center {

}

.right-center {
margin-left: 405px;

}

.left-bottom {

}

.right-bottom {
margin-left: 405px;
}

A: If you want to work with what you currently have to continue to learn, you will have to think about the objects that you need when playing pool. One of the missing pieces that I would say that you could use is a holder - don't know what it is called in pool - that the balls will go into. You can see code that I have added for your review to see if it helps you:
http://codepen.io/pertrai1/pen/mkKna

redpajama_set_name: RedPajamaStackExchange


text:
Q: YouTube API user/channel human readable display name gone Previously I had been getting a YouTube user/channel's human readable name using the $t field within the entry and  title fields from an API call like the following:
http://gdata.youtube.com/feeds/api/users/_6w3OSoTacXjd42ELqLbGQ?v=2&alt=json
The documentation explains that this title tag should contain:

a human-readable title for a feed or an entry in a feed

https://developers.google.com/youtube/2.0/reference#youtube_data_api_tag_title
This used to be the case, but now the title contains the username of the channel/user instead of its human readable name. In the API call eaxmple above the title tag contains DBZ3333 but the actual human readable name is Kanal von DBZ3333 and this doesn't appear anywhere in the API response.
I cannot find any announcements or any documenation mentioning this change, is this a bug in the YouTube API?
Is there now any way of getting a user/channel's human readable name using the YouTube API?

A: EDIT: Okay, unfortunately this is something that can't easily be reverted. I'm told that in the Data API v3 there will be an additional field for display name in addition to the one for channel title (in the coming weeks), but the v2 behavior needs to stay as-is.
This was an inadvertent change in behavior, and the engineering team has just written a fix for it. It should be deployed into production in around a week.


text:
Q: Format string placeholders Do format string placeholders have a more technical name?
For example,
int currentYear = DateTime.Now.Year;
Console.WriteLine("The current year is {0}.", currentYear);

If you were reading this code out loud, or to yourself, how do you read the placeholder? Is there a correct term for representing them?

A: It's called Format Item.  Check Composite Formatting.


text:
Q: Fileupload don't open on LinkButton click i am trying use jquery function to open fileupload control,
code in head section of page
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
    function chooseFile() {

       document.getElementById("#<%=FileUpload1.ClientID%>").click();
       alert('test');

   }
</script>

code in aspx page
<asp:LinkButton OnClientClick='chooseFile();' ID="lnkBtnUploadImage" runat="server">Upload</asp:LinkButton>

i tried putting alert in function before document.getElementById it shows alert but not opening fileupload. if i put alert after document.getElementById it won't show alert or fileupload

A: what about this:
function chooseFile() {
$('#<%=FileUpload1.ClientID%>').trigger('click');
}


text:
Q: ARKit – Cannot decode ARAnchor in MCSession I'm testing out Apple's Multiuser AR demo app with ARKit 2.0 that was introduced in WWDC 2018: Creating a multiuser AR experience.
The documentation says that after each device relocalizes to the same World Map, only the information needed to recreate each user action is shared among devices (e.g. if the user taps on the screen and a 3D object appears, only that new object's ARAnchor should be sent to other devices). For me, while it shows all the 3D characters that were placed by the sending device before it captured and sent a World Map, it doesn't show any objects that are added after the World Map has been sent. The error I'm getting says:
// can't decode data recieved from peer.

Has anyone had this issue and knows what it's about?
I haven't changed anything in the demo code.

A: I had the same trouble but I kind of solved it in this way.
(1)first create a variable to check if the world map has send.
var worldMapHasInited: Bool = false
(2)Then in func shareSession(_ button: UIButton) add this line to the end below
self.multipeerSession.sendToAllPeers(data)
self.worldMapHasInited = true
(3)And finally in func receivedData(_ data: Data, from peer: MCPeerID)
check if the world map has sent, if is sent, skip checking if the data contains   world map or not.
    if !worldMapHasInited {
        if let worldMap = try NSKeyedUnarchiver.unarchivedObject(ofClass: ARWorldMap.self, from: data)
        {
            //....
            // when received world map, set the receiver's
            // worldMapHasInited to true
            self.worldMapHasInited = true
        }
    }
    else
        if let anchor = try NSKeyedUnarchiver.unarchivedObject(ofClass: ARAnchor.self, from: data) {
            // ...
    }

This will directly check if the data contains anchor or not.

A: In MultipeerConnectivity ARSession several peers share data among each other. But sent and received data must be, at first, archived and then unarchived using two instance methods of NSKeyedArchiver and NSKeyedUnarchiver classes:
func archive(worldMap: ARWorldMap) throws {

    let data = try NSKeyedArchiver.archivedData(withRootObject: worldMap,
                                         requiringSecureCoding: true)

    try data.write(to: worldMapURL, options: [.atomic])
}

and:
func unarchive(worldMapData: Data) -> ARWorldMap? {

    guard let unarchievedData = try? NSKeyedUnarchiver.unarchivedObject(ofClass: ARWorldMap.self,
                                                                           from: worldMapData)
    else { return nil }

    return unarchievedData
}

Hence, if you get the following message in Xcode Console:
"can't decode data received from peer"

it means the error occurred while transferring or unarchiving a ARWorldMap data.


text:
Q: Block all network traffic from/to laptop except explicit apps/protocols/targets? Usually I connect my WinXP laptop via WiFi to my home LAN, but sometimes I have to use tethering with cellular phone where traffic prices are very high ($1 = 2 MB traffic counted in both directions).
The first problem - most software firewalls have some whitelist to allow common targets, like microsoft updates.
The second problem - manual whitelisting desired application (like firefox) causes all hidden activity of this application (plugin upgrades, new version checking) goes through too.
How do you deal with this issue? I'd like to use as low bandwidth as possible, even if there are some inconvenience, but even basic internet activity like browsing adds unexcpected overhead for all common browsers...

A: Most of the major firewall software packages are two products in one. They are application gateways and packet filters.
The rules you are talking about for allowing/disallowing specific applications is part of an application gateway. What you need to do is find the settings for the packet filter part of the firewall. If you post what firewall you are using someone might be able to guide you on how to setup the packet filter rules for that package.
Alternatively you can look specifically at a packet filter only firewall. GhostWall is one I've used in the past and can say is fairly easy to set up and doesn't have any negative effects on performance. It works by configuring a list of "rules" that state exactly what types of packets (and their destination/source addresses) are allowed through, these rules are processed in order, so you just specify your allow list of known IPs that you want to use, and then make your final rule "and block everything else". (Or you specify your block list, and make the last rule "allow everything else")
You will always struggle to prevent all unwanted traffic, because you either have to allow stuff, and block what you don't want, and there will always be something you haven't blocked. Or you block everything by default and only allow specifically what you do what, but you'll spend ages configuring it for all the websites you want to use (unless you use a very small subset of the web like your work VPN or something and that's all you need).
I would suggest looking at two plugins for your browser:
1) An ad blocker of some kind. This will reduce the ad traffic on any site you browse.
2) NoScripts. This will block scripts on all sites you visit until you allow them. This often has the effect of the site falling back to their simpler HTML only version which will more often than not require less downloading.
Finally, you could consider looking at a hosts file blacklist. The hosts file is a list of IP address and domains and how they should be resolved and can be used to blacklist certain sites that you don't want visited. If you Google around you should be able to find a community maintained hosts file that blacklists all the major ad servers.


text:
Q: Product Selections as Ordered Tree I have a product with optional variants like this:
SANDALS

*

*Color: red, green, blue

*Size: small, medium, large

*Brand: brandX, brandY

every product variant is related to a set of selections.
Example: if I select Color: red, Size: large, Brand: brandX, this will related to a product with an id of 820.
The way that the option tree should look like is this:
"optionTree": [
        [
            0,
            0,
            [
                820,
                0
            ]
        ],
        [
            0,
            [
                0,
                821
            ],
            [
                823,
                0
            ]
        ],
        [
            [
                824,
                825
            ],
            0,
            0
        ]
    ]

As can be seen, there are 3 product options to choose from, thus the depth of the tree is 3 deep.
every level of the array relates to a product option. The first depth deals with Color, the second deals with Size, and the third with Brand (there could be a variable number of options not just 3). Thus, traversing the entire array to the bottom will result in a product id which matches all 3 choices.
(the index of the choices relate to the indexes in the 'optionTree' array, also 0s are used to represent dead-ends)
Question: how do i order product selection variants in an array tree in such a way that they relate to their respective choices?
lets say i have an array of products which i would like to insert into an empty tree:
$products_to_add = [
            [
                "choices" => ['red', 'medium', 'brandX'],
                "product_id" => 820
            ],
            [
                "choices" => ['red', 'small', 'brandY'],
                "product_id" => 821
            ],
            [
                "choices" => ['green', 'small', 'brandX'],
                "product_id" => 822
            ],
            [
                "choices" => ['blue', 'large', 'brandY'],
                "product_id" => 823
            ],
        ]

How would i transform the array above into a coherent 'optionTree' like the one showed previously? (php or javascript is fine)

A: You can use a loop in which you mutate the final tree as you go. Before starting it, you could prepare a helper structure which translates the name of a variant (like "red") to an index in the relevant (sub)array of the target structure. In PHP:
$props = [
    array_flip(["red", "green", "blue"]),
    array_flip(["small", "medium", "large"]),
    array_flip(["brandX", "brandY"])
];

Then in the main loop, you can benefit from the =& assignment for having a pointer walk through the result tree and adding null references (I prefer this than a 0) when arriving for the first time at a certain branch.
$optionTree = null;
foreach($products_to_add as $product) {
    $node =& $optionTree;
    foreach ($product["choices"] as $depth => $name) {
        if ($node == null) $node = array_fill(0, count($props[$depth]), null);
        $node =& $node[$props[$depth][$name]];
    }
    $node = $product["product_id"];
}
unset($node); // Safety, since it is a reference

After running this code, $optionTree will have the desired value.


text:
Q: Uncommon question with "Ethical hacking" challenge I have a rather unusual question, but I still don't understand much in programming to understand if it is possible to do what I want. So I feel like I need a little story. My name is Nick, I live in Ukraine and am currently studying as a student in one of the IT firms. Now is the middle of my studies and, if everything goes good, they will give me a chance to get a job in 2 months. But not only me, but 300 more students from all over the country, since the training is online, and the company in which we will get one of the largest in the CIS.
This is where I come closer to the task. To complete the course, we have to complete 8 practical sessions with 5-6 tasks in each. Upon their implementation, we upload the code to the git lab. For this, the company has opened an account for each of us. Then the electronic program for checking assignments - E-Mentor compiles our code, provides input data to fill each class and checks the task. In case of an error, it creates log, which often does not provide complete information. Since some of the test data is always hidden. At the end, the program sets progress points for us. And we all want to get 100%)
**Task: Get input data from the E-Mentor server in the form of a file and automatically push it from the server side to my Git Lab account.**

I am not asking for the complete code, but I am asking you to help me write pseudo code so that I can implement it in full.
I represent it like this:

*

*The server clones my code

*Compiles it

*Runs tests

*At this time, a file is created that copies all incoming information from tests

*Somehow the created file is being pushed to my gitlab
For example:
GitBash is started on the server and logs into the gitlab under my login. In this case, it is restricted to rewrite the password and login used by the server itself, as it will be immediately noticed.
This is the coolest challenge that I want to try to do and share it with all students)


text:
Q: There is already an object named 'PersonalData' in the database during migration I created a migration:

Add-Migration InitPersonDataMigration -Project
  PersonalData.Dal -StartupProject ConsoleApp3 -OutputDir
  Migrations/PersonalDataMigrations -Context PersonalDataContext

when the database did not exist.
Next, I try to migrate:

Update-Database -migration 20200323075750_InitPersonDataMigration
  -Project PersonalData.Dal -StartupProject ConsoleApp3 -Context PersonalDataContext

But...:

There is already an object named 'PersonalData' in the database

It seems that this table is trying to be created 2 times.
What am I doing wrong?

A: Problem was here:
public PersonalDataContext()
{
      Database.EnsureCreated(); //<<---
}

First, the regular creation of the database was performed, and then the migration of creating the database was rolled.


text:
Q: Basic Probability How to find the conditional/joint probabilities of two variables from their empirically estimated marginal ones and an assumed correlation?

A: Iva: The marginal kernel density doesn't really help you with conditional densities. If you are conditioning on the occurrence of a specific event ( which could be values taken on by a related random variable) then you have to separate out the samples for which that event occurred and fit a distribution to that data.  The correlation between X and Y does not give enough information either.  The conditional probability P[Y in A|X in B]  is
P[Y in A and X in B]/P[X in B].  But there is no specific algebraic manipulation that will convert this into simply a function of P[Y in A] and Cov(X,Y).


text:
Q: set alpha channel for pyplot objects? In R, you can set the alpha channel by
rgb(r=.1,g=.5,b=.5,alpha=.5,max=1)

for any object that takes a color argument. patch objects in pyplot have a set_alpha method, but can this be done for lines on a plot, for instance? like pyplot.plot(x,y,color=???) or h = pyplot.plot(x,y) and do something with h.

A: Appears that
h = plt.plot(x,y)

returns a list of matplotlib.lines.Line2D objects in h even if there is one element plotted, so h[0].set_alpha() is the method to use.

A: plt.plot(x,y,'ro-',alpha=0.3)
if you want to mix up your own color, you can pass a hex value or an rgb tuple http://matplotlib.sourceforge.net/api/colors_api.html


text:
Q: Trying to find loading symbols in angular I am trying to find all loading symbols (spinners) in a webpage's pagesource (it is using angular). I currently trying to detect (fast) if a page is loading, what I have so far is to look for spinner-border ml-3 md-spinner. What else can I search for?
    public static bool IsLoading(IWebDriver driver)
    {
        List<string> xsIdentifiers = new List<string>(new string[]
        {
            "spinner-border ml-3 md-spinner",
        });

        foreach (var identifier in xsIdentifiers)
        {
            if (driver.PageSource.Contains(identifier))
            {
                Console.WriteLine($"Loading... Found identifier: {identifier}");
                Thread.Sleep(2000);
                return true;
            }
        }
        return false;
    }

A: I use the following technique to find elements that are loaded fast and you cannot detect them with locators.

*

*In Chrome go to Network

*Change the speed from No throttling to the slowest

*Open Elements tab

*Reload the page and check which elements are changed while your page is being loaded.

This is great method which saved me many times.


text:
Q: AWS ECS Fargate Task CPU and Memory Resource for single threaded app I am trying to understand resource allocation and right sizing at a high level, as well as, specifically for ECS Tasks.
My question is, is it a good assumption that if the code that runs in my ECS Task is completely single threaded; so makes not use of parallelization/multi-threading - would provisioning the task with a CPU value that would allocate more than just a single 1 vCPU have no effect on the execution time/performance of the work being done and essentially would be wasteful?
With equivalent Memory values, the same single thread app/code running in a Task with 1024 (1 vCPU) versus 2048 (2 vCPU) - would not make use of the second vCPU, right?
Reference: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html#fargate-tasks-size


text:
Q: JSON processing - Javascript I have the following script that holds a json.
$http({
      url: '/mpdValidation/mpdValidate',
      method: "POST",
      data: { 'message' : mpdData }
    ).then(function(response) {
    console.log(response.data.searchResults[0].customers);
    $rootScope.mpdValidatedData = response.data.searchResults[0].customers;
    var partyAddressesArray = $rootScope.mpdValidatedData['partyAddresses '];
    console.log(partyAddressesArray.length);
});

I will be viewing this in a table.
My concern is that, there are few arrays inside this json which I'm not able to iterate/process.
That is,
My json:
{
  "searchResults": [
    {
      "id": 1,
      "firstName": "kelly",
      "lastName": "johnson",
      "facets": {
        "totalCustomerfound": 118541
      },
      "customers": [
        {
          "score": 20,
          "fullName": "kelly kelly",
          "firstName": "kelly",
          "lastName": "kelly",
          "dob": "1963/01/22",
          "memNum": "42900711",
          "phoneList": [
            {
              "phoneType": "homephonenumber",
              "phoneExchange": "222",
              "phoneAreaCode": "111",
              "phoneNumber": "9198",
              "phoneFullNumber": "1112229198"
            },
            {
              "phoneType": "primaryphonenumber",
              "phoneExchange": "444",
              "phoneAreaCode": "333",
              "phoneNumber": "9198",
              "phoneFullNumber": "3334449198"
            }
          ],
          "partyAdresses": [
            {
              "addressType": "home",
              "address1": "22 IRON KETTLE ST",
              "zipCode": "89130-2222",
              "city": "LAS VEGAS",
              "state": "NV"
            },
            {
              "addressType": "mailing",
              "address1": "11 SANDPIPER LN",
              "zipCode": "80601-1111",
              "city": "BRIGHTON",
              "state": "CO"
            }
          ],
          "policyList": [

          ],
          "membershipList": [
            {
              "termEffectiveDate": "2015/12/16",
              "termExpirationDate": "2016/12/16",
              "contractTransactionTimeStamp": "2017/09/05 19:46:29.722",
              "policyInceptionDate": "2015/12/16",
              "policyNumber": "112233",
              "policyStatus": "INACTIVE",
              "prodTypeCode": "MSHP",
              "productCode": "MSHP",
              "memType": "PREMIER",
              "contractAddress": [

              ],
              "roleList": [
                {
                  "roleType": "PRIMARY MEMBER",
                  "sourceId": "4290011",
                  "roleStatus": "INACTIVE",
                  "roleStartDate": "2015/12/16",
                  "membershipNumber": "4290011"
                }
              ]
            }
          ]
        }
        ]
    ]
}

My table:

*MPD - Validated customer returns

         First name
         Last name
         Date of birth
         Policy number
         Policy status
         Address type
         Address
         Phone number

Since partyAddresses in my json is an array, it is not getting shown in row.address. I need address1,address2,city,state,zipCode of home addressType from the json as a single string to be displayed in the row.address column.
Likewise the same for phoneNumber, the homePhone must be viewable.
The first name, last name are populating as expected but not the address and phone numbers. Can someone help?

A:
You can try ng-repeat in the particular row, like this

         {{addr. address1}}, {{addr. address2}} ...so on

similarly for phoneNumber etc.,

A: Inside your controller you can use the spread operator [...array] to convert your array into a string before passing it to your view, for more infos check the following link :
Spread Operator Doc on MDN


text:
Q: how to use jQuery plug in content pages? I have a master page and 3 content pages, i have used a jQuery plug in for persian calendar, when i use the plug in in master page every thing seems fine, the problem is i want to use this plug in just in ONE of my content pages, so i cant use it in master page, but the plug in wont work when used in content page.Here is my code in content page:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Content.aspx.cs" Inherits="WebApplication3.WebForm4" %>

<script src="jquery-1.11.3.min.js" type="text/javascript"></script>

<link href="Compressed/skins/aqua/theme.css" rel="stylesheet" type="text/css" />

<script src="Compressed/jalali.js" type="text/javascript"></script>

<script src="Compressed/calendar-setup.js" type="text/javascript"></script>
<script src="Compressed/lang/calendar-fa.js" type="text/javascript"></script>
<input id="date_input" type="text" onclick="return date_input_onclick()" runat="server" /><input id="date_btn" type="button" runat="server"/>

 <script type="text/javascript" >
    Calendar.setup({
        inputField: 'date_input',
        button: 'date_btn',
        ifFormat: '%Y/%m/%d',
        dateType: 'jalali'
    });
  </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

could anyone help me?


text:
Q: Android : Upload large files using MultipartEntity According this answer "Android upload video to remote server using HTTP multipart form data" I do all steps.
But I don't know how I code for server side! I mean a PHP simple page that serve my reauest foe upload.
And another question is that : YOUR_URL (3rd line of following snippet) must be address of that PHP page?
private void uploadVideo(String videoPath) throws ParseException, IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(YOUR_URL);

    FileBody filebodyVideo = new FileBody(new File(videoPath));
    StringBody title = new StringBody("Filename: " + videoPath);
    StringBody description = new StringBody("This is a description of the video");

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("videoFile", filebodyVideo);
    reqEntity.addPart("title", title);
    reqEntity.addPart("description", description);
    httppost.setEntity(reqEntity);

    // DEBUG
    System.out.println( "executing request " + httppost.getRequestLine( ) );
    HttpResponse response = httpclient.execute( httppost );
    HttpEntity resEntity = response.getEntity( );

    // DEBUG
    System.out.println( response.getStatusLine( ) );
    if (resEntity != null) {
      System.out.println( EntityUtils.toString( resEntity ) );
    } // end if

    if (resEntity != null) {
      resEntity.consumeContent( );
    } // end if

    httpclient.getConnectionManager( ).shutdown( );
}

A: This code worked properly and PHP code I should use is as simple as this:
<?php

    $file_path = "uploads/";

    $file_path = $file_path . basename( $_FILES['videoFile']['name']);
    if(move_uploaded_file($_FILES['videoFile']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "upload_fail_php_file";
    }
 ?>

NOTE that videoFile must match exactly with
reqEntity.addPart("videoFile", filebodyVideo);
And the MOST Important problem you probably face to, is default value of post_max_size and upload_max_filesize in the server config! As default is too small and when you try to upload large files, the PHP script return : "upload_fail_php_file" with no error or exception throwing. So remember to set these values as big as enough...
Enjoy coding.


text:
Q: Possible to expose CONSTANTS defined in webservice to consuming client (.Net both sides) I have several constant defined for a webservice, and I would like to make these available to consuming client.  Both the server and client are .Net.
I think it is possible to achieve this by using enum's, but many of my constants are text string with spaces, so I would have to write an extra function to convert the enum into the equivalent text string.
So, is there any way of defining the constants in the web service so they would then be available to the client??
Update (Kev):  I want to expose them to the client via the web service itself, not via a separate assembly.
Update #2 (Paige): So if I understand you, I will then have a new List object containing the constants, but how does the client use that?  Wouldn't it look like (roughly):
dim constants as List = mywebservice.GetConstants()
dim someresult as Integer = mywebservice.somefunction(constants(3))
Unless I misunderstand you, that totally defeats the point of defining constants.

A: The answer seems be.....cannot be done.

A: You could implement these constants in a standalone assembly and reference the assembly from both the web service and the client.

A: You could write the "constants" into a dictionary and then have a web method that returns the keys.
Or, using Kev's answer above:
Class:
public class Win32Message   {
    public const int WM_ACTIVATE =0x0006;
    public const int WM_ACTIVATEAPP = 0x001C;
    public const int WM_AFXFIRST = 0x0360;
    public const int WM_AFXLAST = 0x037F;
    public const int WM_APP = 0x8000;
    public const int WM_ASKCBFORMATNAME        = 0x030C;
}

And then in the web service use a web method like:
[WebMethod]
public System.Collections.Generic.List<string> GetConstants(System.Type type)
{
    System.Collections.Generic.List<string> constants = new
        System.Collections.Generic.List<string>();

    System.Reflection.FieldInfo[] fieldInfos = type.GetFields(
        System.Reflection.BindingFlags.Public | BindingFlags.Static |
        System.Reflection.BindingFlags.FlattenHierarchy);

    // Go through the list and only pick out the constants
    foreach (System.Reflection.FieldInfo fi in fieldInfos)
    if (fi.IsLiteral && !fi.IsInitOnly)
        constants.Add(fi.Name);

    return constants;
}

I found this on Wes' Puzzling Blog
Of course, you can return it as an array, arraylist or however you'd like.

A: I don't know that there's any way to expose constants per se.
But perhaps you could just implement some functions which always return the same value and just give them a special naming convention? For example:
public int FLAG_READONLY()
{
   return 3;
}

I may be misunderstanding your need.

A: As i see it, the real point of webservices is being able to retrieve data or execute processes on a server in a LANGUAGE and MACHINE-independent way, using xml or json or whatever as the language for data representation. When you call a service to list products, you just want to get the products, you don't want (or need) to know if you're calling a stored SQL procedure or a C# business function in the server. So i don't think it makes sense to share 'constants' from the client to the server unless you have a web method that lists those constants to you (again, in a text-only way).
I think the whole Microsoft web service .asmx stack just sucks because it relies on the 'remote procedure call' metaphor instead of the 'service' part of the web service concept.
I agree this is subjective :P


text:
Q: How to add a new column to an existing pandas dataframe I got a pandas data frame with spam messages.
I want to create an extra column next to the column of the messages and show the amount of words each message has.
For Example:
Index      Content           Amount of words
0          Hi I am cool      4
1          What up?          2
2          Are you happy?    3

I can count the amount of words per each message:
count = data['INHALT'].str.split().str.len()
count.index = count.index.astype(str) + ' words:'

But if I want to add it as a column to my data frame, it only shows me NaN-values. Why? And how can I solve this issue?

A: You can add a new row using append function
df = df.append(new_row, ignore_index=True)

A: Ah I think I've made a mistake.
because by using the code
my_dataframe.append(row_to_append, ignore_index = True)
I add every number to a row. But actually I want ONE row with the name "numer of words" and then every number should be added for every message in each column.
The problem is: the numbers are still shown as NaN values.
This is my column I want to add:
DOC_ID
0 words:     1125
1 words:      745
2 words:     1874
3 words:     1129
4 words:     1614
             ...
78 words:    1649
79 words:     872
80 words:    1624
81 words:     866
82 words:    1327
Name: INHALT, Length: 83, dtype: int64

I just want the numbers as a row called "number of words" to be add next to the row "messages"
Again the example:
Index      Content           Amount of words
0          Hi I am cool       4
1          What up?           2
2          Are you happy?     3

I hope, that I could make it more clear right now


text:
Q: Arredondamento de 5 em 5 centavos Em um sistema PHP que estou desenvolvendo, preciso atualizar uma coluna da tabela de preço. O campo preço está no formato float e o administrador informa o percentual de aumento.
Exemplo: Informa que terá 10% de aumento.
$valor_antigo = 4,25;

$novo_valor = round(($valor_antigo + ($valor_antigo / $percentual)),2);

Assim, o valor após o aumento será de 4,68. Definindo para deixar apenas duas casas após a vírgula.
O que preciso agora é arredondar esse valores de cinco em cinco centavos. Se eu utilizar ceil ou `floor, terei esse arredondamento apenas de 1 em 1.
Por exemplo, o valor de 4,68 acima, precisa ser salvo como 4,70.
`
Se o valor fosse 5,22; ficaria 5,20. 7,46, ficaria 7,45.
Como posso fazer isso?

A: Tem que normalizar no ponto que deseja. Se quer a cada 5 centavos divide-se o valor por 0,05 arredondando ele e aí multiplica-se novamente por 0,05 (5 centavos), assim volta-se ao valor original sem a parte fracionada indesejada.
round($value / 0.05, 0) * 0.05

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Usar float para valores monetários é pedir para ter problemas.


text:
Q: get virtual memory size of process in AIX in program I write app on AIX 5.3 using C++. I want to get current size of process virtual memory. I use getprocs64 function, but with this data I can't get result as svmon shows.
Please help me.
Thanks.

A: I have found partially solution that is suitable for me.
I ran small test app and see that pi_dvm, the member of procentry64 structure, will increase if we allocate memory on stack (for example: char arr[1024];) for size of allocated object and some overhead. Noiw, we want to calculate used heap size. We should use mallinfo() function from malloc.h that returns mallinfo struct. We are interested in two fields of mallinfo structure: usmblks and uordblks (about this fields you could read here). Some example code:
pid_t pid = getpid();
struct procentry64 p_info;
if (getprocs64(&p_info, sizeof(p_info), NULL, 0, &pid, 1) < 0) {
  printf("Error!");
}
proc_size = p_info.pi_dvm*getpagesize() + p_info.pi_tsize;
struct mallinfo m = mallinfo();
proc_size += m.usmblks + m.uordblks;
return proc_size; // proc_size in bytes

P.S. I don't know Why we sum pi_tsize (if anybody knows, please tell us). I get this idea from pg_top sources, but there is a bug, they multiply pi_tsize by 4, but it's incorrect, because pi_tsize is in bytes.
I hope this solution may help someone :)


text:
Q: running a project in Dev c++ I have a folder that contains a few .h and .cpp files along with a makefile. How can I run them in dev C++. I have just started using dev C++, hence, a bit clueless about this.
the make file is
 CC=g++
 CV=-I/usr/include/opencv
 CV2=-lml -lcvaux -lhighgui -lcv -lcxcore

 all:
    $(CC) main.cpp HOG.cpp HOGFeaturesOfBlock.cpp $(CV) $(CV2) -o featureExtractor

and I'm getting the error main.cpp, hog.cpp: no such file or directory.

A: *

*Create a new project using File >> New Project. You can ignore the C/C++ options if you use a custom makefile. Also, an empty project will do.

*Add the source and header files to the new project using Project >> Add to Project or the '+' sign in the middle of the top toolbar.

*Go to Project >> Project Options (Alt+P) >> Makefile and tick the 'Use custom makefile' option. Then point Dev-C++ to the custom makefile below.

Also, be sure to update your IDE to the following version, which fixes an immense list of bugs compared to the ancient 4.9.9.2 version, ships with GCC 4.6.1 or 4.7.0, and is fully portable: http://sourceforge.net/projects/orwelldevcpp/


text:
Q: Why procduces my two identical systemctl timers different amount of outputs? I have two raspberry pi with almost identical setup.
On both I have a systemctl service and a timer which run every 15 seconds.
The job calls a go script, which reads out the system temperature and creates a log entry in my mariadb database. The database is running on one of the raspberries. Therefore the only difference in the two go scripts are the hostname of the database and an identifier variable so I can see in the database from which the database entry is coming from. The rest is identical.
The problem is that raspberry1 produces more database entries than raspberry2.
When I start with a fresh database with zero entries. Then 1 have about 120 entries from raspberry1 and about 70 entries from raspberrie two. The error continues. After more time I get for example 1000 entries and 700 entries.
Does anyone know where the differences could coming from?
Maybe when both jobs want to create a new entry in the mariadb at the same time?
But I'm almost sure that this is handled somehow by mariadb.
Here are the details:
FanLog.service
[Unit]
Description=Lüfter Temperatur Logger Service
After=network.target

[Service]
ExecStart=/root/go/temperatur_logger
WorkingDirectory=/root/go
StandardOutput=append:/var/log/TempLogger.log
StandardError=append:/var/log/TempLogger_error.log
User=root

FanLog.timer
[Unit]
Description=Fanlogger Timer

[Timer]
# OnBootSec=15min
# Wochentage-dd-mm hh:mm:ss
# OnCalendar=*-*-* *:05:00
# OnUnitActiveSec=1min
# OnCalendar=minutely
OnCalendar=*-*-* *:*:0/15
# OnCalendar=*-*-* *:0/0:20

[Install]
WantedBy=timers.target

The output of "systemctl status FanLog.timer" seems to be okay.
I can see at maximum the 15 seconds down to a few ms and then again 15 seconds if I repeat.
 ⚡ root@DeskPi  /etc/systemd/system  systemctl status FanLog.timer
● FanLog.timer - Fanlogger Timer
   Loaded: loaded (/etc/systemd/system/FanLog.timer; enabled; vendor preset: enabled)
   Active: active (waiting) since Mon 2021-09-20 06:07:22 CEST; 39min ago
  Trigger: Mon 2021-09-20 06:46:45 CEST; 13s left

Sep 20 06:07:22 DeskPi systemd[1]: Stopping Fanlogger Timer.
Sep 20 06:07:22 DeskPi systemd[1]: Started Fanlogger Timer.

temperatur_logger.go
package main

import (
    "context"
    "database/sql"
    "fmt"
    "log"
    "os"
    "os/exec"
    "time"

    "github.com/stianeikeland/go-rpio"

    _ "github.com/go-sql-driver/mysql"
)

const (
    username   = "TempLogger"
    password   = "XXXXXXXXXXXXX"
    hostname   = "192.168.1.20:3306" // Different on other device
    dbname     = "TempLog"
    table      = "TempLog"
    DeviceName = "OctoPi" // Different on other device
)

var (
    // Use mcu pin 24, corresponds to GPIO3 on the pi
    pin = rpio.Pin(24)
)

func add(x int, y int) int {
    return x + y
}

func get_temp(temperatur string) string {
    var outputlaenge int
    var aktuelle_temperatur string
    // Befehl
    cmd := exec.Command("sudo", "/usr/bin/vcgencmd", "measure_temp")
    // run command
    if output, err := cmd.Output(); err != nil {
        fmt.Println("Error", err)
    } else {

        outputlaenge = len(output)
        aktuelle_temperatur = string(output[outputlaenge-7 : outputlaenge-3])
        // fmt.Println(string(output[outputlaenge-7 : outputlaenge-3]))
    }
    return aktuelle_temperatur
}

func dsn(dbName string) string {
    return fmt.Sprintf("%s:%s@tcp(%s)/%s", username, password, hostname, dbName)
}

func dbConnection() (*sql.DB, error) {
    db, err := sql.Open("mysql", dsn(""))
    if err != nil {
        log.Printf("Error %s when opening DB\n", err)
        return nil, err
    }
    defer db.Close()

    ctx, cancelfunc := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancelfunc()
    if err != nil {
        log.Printf("Error %s when creating DB\n", err)
        return nil, err
    }

    db.Close()
    db, err = sql.Open("mysql", dsn(dbname))
    if err != nil {
        log.Printf("Error %s when opening DB", err)
        return nil, err
    }

    db.SetMaxOpenConns(20)
    db.SetMaxIdleConns(20)
    db.SetConnMaxLifetime(time.Minute * 5)

    ctx, cancelfunc = context.WithTimeout(context.Background(), 5*time.Second)
    defer cancelfunc()
    err = db.PingContext(ctx)
    if err != nil {
        log.Printf("Errors %s pinging DB", err)
        return nil, err
    }
    log.Printf("Connected to DB %s successfully\n", dbname)
    return db, nil
}

type temperatur_eintrag struct {
    DeviceName  string
    record_date string
    temperature string
    fan         bool
}

func insert(db *sql.DB, p temperatur_eintrag) error {
    query := "INSERT INTO " + table + "(device_name, record_date, temperature, fan) VALUES (?, ?, ?, ?)"
    ctx, cancelfunc := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancelfunc()
    stmt, err := db.PrepareContext(ctx, query)
    if err != nil {
        log.Printf("Error %s when preparing SQL statement", err)
        return err
    }
    defer stmt.Close()
    res, err := stmt.ExecContext(ctx, p.DeviceName, p.record_date, p.temperature, p.fan)
    if err != nil {
        log.Printf("Error %s when inserting row into products table", err)
        return err
    }
    rows, err := res.RowsAffected()
    if err != nil {
        log.Printf("Error %s when finding rows affected", err)
        return err
    }
    log.Printf("%d log entry created ", rows)
    return nil
}

func main() {
    currentTime := time.Now()
    var tempi string
    var myFan bool

    db, err := dbConnection()
    if err != nil {
        log.Printf("Error %s when getting db connection", err)
        return
    }
    defer db.Close()
    log.Printf("Successfully connected to database")

    // Open and map memory to access gpio, check for errors
    if err := rpio.Open(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    // Unmap gpio memory when done
    defer rpio.Close()
    // pin.PullUp()

    if pin.Read() == 1 {
        fmt.Println("Pin High")
        myFan = true
    } else {
        fmt.Println("Pin Low")
        myFan = false
    }

    p := temperatur_eintrag{
        DeviceName:  DeviceName,
        record_date: currentTime.Format("2006-01-02 15:04:05"),
        temperature: get_temp(tempi),
        fan:         myFan,
    }
    err = insert(db, p)
    if err != nil {
        log.Printf("Insert failed with error %s", err)
        return
    }
}

A: I have found the solution:
One of these two options made it work:
Persistent=true
AccuracySec=2sec

Not sure which one exactly as I didn't have tested more.
FanLog.timer looks now so:
[Unit]
Description=Fanlogger Timer

[Timer]
OnCalendar=*:*:0/10
Persistent=true
AccuracySec=2sec

[Install]
WantedBy=timers.target


text:
Q: Can I trust initramfs and vmlinuz images? I am running an Arch Linux installation on my laptop with the following partition scheme:

*

*/dev/sda1 is my /boot partition, which is also my ESP

*/dev/sda2 is my LUKS encrypted root partition

I use systemd-boot as my bootloader.
As I was thinking about the security of this setup, I became paranoid, because the vmlinuz and initramfs images could be modified, as they are stored on an unencrypted partition. My concern is, that the images could be replaced with modified and malicious images from an attacker. Other than locking down the UEFI and disallowing boot from USB drives I don't have an idea to prevent booting modified images.
My questions are:

*

*Is this a real problem or is there already a security measure against this?

*If not, is there anything I can do to detect unauthorized changes when booting (something like signed images)?

*Are there any other security considerations when using this kind of a setup?

EDIT:

*I have a TPM in my laptop. Is there anything I can do with that?

A:
My concern is, that the images could be replaced with modified and malicious images from an attacker.

Yep, they could. To prevent that, you could boot from a removable drive yourself (which you remove when leaving the computer), or have the firmware securely check the boot binaries (like UEFI Secure Boot tries to do).
That still wouldn't prevent the attacker from installing a keylogger, or modifying the firmware of your system. With the signed boot approach, you'd also need to be sure that the attacker would not be able to modify the signing keys the computer accepts.

Are there any other security considerations when using this kind of a setup?

Cold boot attacks are pretty bad. Don't let your laptop get stolen when it's powered on.
Also, strictly speaking, encryption doesn't mean authentication in itself, and full-disk encryption usually doesn't authenticate the data since that would require changing the data size (the addition of authentication tags). The lack of authentication leads to malleability, the degree of which depends on the encryption algorithm (CTR and CBC modes are bad, and there's mentions of practical attacks against CBC-based disk encryption).
So, if you're paranoid enough, you probably shouldn't use the laptop after an attacker has had their time with it. But all of this depends on your threat model, the value of your data, and how advanced you expect your attackers to be.

A: There is no defence against physical access!
You can do whatever you want but even full disk encryption can be circumvented by a hardware key logger installed on one of your internal USB ports (on a laptop: soldered straight onto your motherboard)
¯\_(ツ)_/¯


text:
Q: Как создать шаблон компонента список новостей, что бы генерировалась неоднородная структура блоков в Битрикс 1с? Понравилось мне вот такой дизайн списка новостей, ниже картинки представлен его код, но видимо bootstarpa не хватает что бы правильно отображался, поэтому прикрепил картинкой как это должно выглядеть. Так вот как мне на битриксе это реализовать, сложность в том что структура блоков не однородная и как их правильно сгенерировать что бы он автоматически их так расставлял, может порядковые номер как то присвоить или еще как то?

.blog-item {
    height: 277px;
    position: relative;
    border-radius: 10px;
    margin-bottom: 30px;
    -webkit-box-shadow: 0px 0px 30px rgb(11 12 48 / 15%);
    box-shadow: 0px 0px 30px rgb(11 12 48 / 15%);
}

.set-bg {
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top center;
}

.blog-item .bi-tag {
    font-size: 12px;
    font-weight: 600;
    color: #ffffff;
    display: inline-block;
    padding: 3px 20px 5px;
    border-radius: 2px;
    position: absolute;
    left: 20px;
    top: 20px;
}

.bg-gradient, .bd-text .bd-tag-share .s-share a:hover, .bh-text .play-btn, .schedule-table-tab .nav-tabs .nav-item .nav-link.active, .newslatter-inner .ni-form button, .latest-item .li-tag, .price-item .price-btn:hover, .price-item .pi-price, .price-item .tr-tag, .schedule-tab .nav-tabs .nav-item .nav-link.active, .site-btn {
    background-image: -o-linear-gradient(330deg, #ee8425 0%, #f9488b 100%), -o-linear-gradient(330deg, #ee8425 0%, #f9488b 100%);
    background-image: linear-gradient(120deg, #ee8425 0%, #f9488b 100%), linear-gradient(120deg, #ee8425 0%, #f9488b 100%);
}

.blog-item .bi-text {
    position: absolute;
    left: 0;
    bottom: 18px;
    width: 100%;
    padding: 0 20px;
}
.blog-item .bi-text h5 {
    margin-bottom: 10px;
}
.blog-item .bi-text h5 a {
    color: #ffffff;
    line-height: 24px;
    font-weight: 600;
    display: block;
}

.blog-item .bi-text span {
    font-size: 14px;
    color: #ffffff;
    display: block;
}

.blog-item .bi-text span i {
    color: #f44949;
}

.fa {
    display: inline-block;
    font: normal normal normal 14px/1 FontAwesome;
    font-size: inherit;
    text-rendering: auto;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
.blog-item.large-item {
    height: 575px;
}

.blog-item .bi-text h3 a {
    font-size: 28px;
    color: #ffffff;
    font-weight: 600;
    line-height: 36px;
    display: block;
}

.primary-btn {
    display: inline-block;
    font-size: 16px;
    font-weight: 600;
    padding: 12px 40px;
    color: #ffffff;
    text-align: center;
    border-radius: 50px;
    background-image: -webkit-gradient(linear, left top, right top, from(#ee8425), to(#f9488b)), -webkit-gradient(linear, left top, right top, from(#ee8425), to(#f9488b));
    background-image: -o-linear-gradient(left, #ee8425 0%, #f9488b 100%), -o-linear-gradient(left, #ee8425 0%, #f9488b 100%);
    background-image: linear-gradient(to right, #ee8425 0%, #f9488b 100%), linear-gradient(to right, #ee8425 0%, #f9488b 100%);
}

.load-more .primary-btn {
    padding: 12px 45px;
}
.load-more.blog-more {
    padding-top: 20px;
}

.load-more {
    text-align: center;
    padding-top: 10px;
}

Foody

Google's AI Assistant Aims to Transcend the Smart Speaker

                                     19th May, 2019

Foody

Free Classifiends Using Them To Promote

                                     19th May, 2019

Business

"Inspired By Modiji, Will Make Biopic": BJP's Ravi Kishan

                             19th May, 2019

Foody

The ZenBook With a Touchpad That Lights Up

                                     19th May, 2019

Foody

Is the Detel Posh a Posh Speaker?

                                     19th May, 2019

Marketing

Lok Sabha Elections 2019 - In BJP, Only ''Tai'' Can Admonish Me: PM Modi On Sumitra
                                Mahajan

                             19th May, 2019

Design

The Biggest Stories Of January 06, 2019

                                     19th May, 2019

UX/UI

Alexa Can Now Show You Things!

                                     19th May, 2019

Marketing

"Still Waiting For BJP To Make Me Chief Minister": Goa Assembly Speaker

                             19th May, 2019

                Load More


text:
Q: Javascript remove image on click var b = 1;
for(var i= 0; i < 5; i++){
    fisk(b);
}

function getRandomPosition(element) {
    var x = document.body.offsetHeight-element.clientHeight;
    var y = document.body.offsetWidth-element.clientWidth;
    var randomX = Math.floor(Math.random() * x);
    var randomY = Math.floor(Math.random() * y);

    return [randomX,randomY];
}

function fisk(skala) {
    var img = document.createElement('img');
    img.setAttribute("style", "position:fixed;");
    img.setAttribute("src", "http://i.imgur.com/K9egEbW.jpg");
    document.body.appendChild(img);
    var xy = getRandomPosition(img);
    img.style.top = xy[0] + 'px';
    img.style.left = xy[1] + 'px';
}

With this code above i have made a tiny game where i am supposed to click on some fished that spawns with this code and when you click them all you win. But i'm having trouble finding out how to make the images disappear when i click them. Here is a jsbin link that shows all i've done so far so it's easier to understand. https://jsbin.com/josamuxoce/edit?html,css,js Anybody have a clue on how to make the fishes that spawn disappear when i click on them with the fishing rod?
Thanks

A: Add $(img).click(function(){ $(this).remove();}); to function fisk(skala);
But. img will never get click becaurse all clicks will be handled by #fiskespo.
Use fiskespo image as cursor image instead of extended img object (Using external images for CSS custom cursors). Should work;


text:
Q: Calculate element in matrix incrementally, using neighbors I have this Java problem, which I suspect it relates to a higher-level algorithm, but my searches haven't been able to come up with anything practical.
You construct an array as follows:
1
1   1
1   2   1
1   3   3   1
1   4   6   4   1
1   5   10  10  5  1

Basically, Ai,j = Ai-1,j-1+Ai-1,j. It's supposed to return the element at index (l, c): for (4, 1) it should return 4, (5, 2) returns 10, etc. My solution is straightforward, but it is not enough:
static long get(int l, int c){
    long[][] matrix = new long[l+1][l+1];
    matrix[0][0]=1;
    matrix[1][0]=1;
    matrix[1][1]=1;
    for(int i=2;i<=l;i++){
        matrix[i][0]=1;
        for(int j=1;j<=i;j++){
            matrix[i][j] = matrix[i-1][j-1]+matrix[i-1][j];
        }
    }
    return matrix[l][c];
}

It doesn't work for large values of l and c. Using BigInteger doesn't work. My searches have led me to loop skewing and scalarization, but I don't know where to start. Any steer in the right direction is really appreciated.
PS: Sorry for the newbie-vibe, this is my first question!

A: You don't need to use a loop, this is simply pascal's triangle, the formula:
(n, k) = n! / ( k! * (n-k)!)

Will generate your answer for the position (n, k).

A: You are describing Pascal's triangle, for which a closed formula exists:
matrix[n][k] = n!/(k! * (n-k)!)

P.S. If these numbers seem familiar, it is because they are also from the binomial theorem, where the common examples are:
(x+y)^2 = 1* x^2 + 2xy + 1*y^2
(x+y)^3 = 1*x^3 + 3*xy^2 + 3yx^2 + 1*y^3

A: Try this:
static long get(int l, int c) throws Exception {
    if (l != c)
         throw new Exception("l != c");
    long[][] matrix = new long[l+1][l+1];
    matrix[0][0]=1;
    for (int i = 1; i <= l; ++i) {
         for (int j = 0; j <= i; ++j) {
              if (j - 1 >= 0) {
                    matrix[i][j] = matrix[i - 1][j] + matrix[i - 1][j - 1];
              } else {
                    matrix[i][j] = matrix[i - 1][j];
              }
         }
    }
    return matrix[l][c];
}


text:
Q: Can I have multiple Exchange servers in the same Domain? I'm pretty sure that I know the answer to this, but is it possible to have two Exchange 2010 servers in the same domain that are not aware of each other? I want to have another Exchange server that is insulated from my main Exchange server without having to set up another DC, but I don't think this is possible.

A: Exchange is tied to Active Directory. You can't install Exchange separate from the AD Forest.


text:
Q: Why can "!=" not be compared to a long? I've got code like this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
. . .
if (null != request.UserAgent)
{
    str = String.Format("userAgent == {0}", request.UserAgent.ToString());
    MessageBox.Show(str);
}
. . . // many other similar ones, comparing null to string, etc. types

But this one:
if (null != request.ContentLength)
{
    str = String.Format("contentLength == {0}", request.ContentLength.ToString());
    MessageBox.Show(str);
}

...fails with a compile-time error of, "Operator '!=' cannot be applied to operands of type '' and 'long'"
I can append a ToString() to get it to compile:
if (null != request.ContentLength.ToString())
. . .

...but that seems kind of weird. Why is HttpWebRequest's ContentLength (a long) uncomparable to null?

A: ContentLength is an Int64 which is not a nullable type. A string can be null, hence the conversion to a string allows the comparison.

A: That's because long is a value type and value types can never be null.
If you would like to assign null to a primitive type such as int, long, double etc you can by declaring it like this:
 long? myLong = null;


text:
Q: Change output of random list shuffle slightly when changing seed slightly Problem:
I would like to randomly shuffle a list, but using a seed value s so that, when changing s only slightly, the shuffle's output also only changes slightly.
Details:
I have a sorted list of elements, for example:
[0,1,3,5,7]

This list should be shuffled multiple times, each time using a seed value s. When two seed values s1 and s2 = s1 + d lie close to each other, then the shuffled lists should also be "similar".
By "similar", I mean that elements in the new shuffled list are either the same as they were when using the original seed value s1, or they are replaced only by values which are close to them in the original list (for example their direct neighbors in the original list).
Edit: The output should still be deterministic, i.e. using the same seed s1 when shuffling the same input list should result in the same shuffled list.
Example for the above list (note how adding the small value d only perturbs the list slightly, i.e. many values stay the same and if they change, they are usually replaced by their neighbors in the original list. As the offset increases, the "difference" between the lists may increase further, and values beyond the neighbors may be selected as well):

Seed:
Output:

s
[5,0,1,7,3]

s + d
[5,0,3,7,1]

s + 2d
[7,0,3,5,1]

s + 3d
[7,0,1,3,5]

Is there an algorithm for this? Is there a common name for this problem (or other search terms I could use)?
Edit2:
The output should also not depend on what the original seed was, i.e. if s = s3 + d = s4 - 0.5*d then the shuffle result should be the same whether I shuffle using s, s3 + d or s4 - 0.5*d as a seed. In other words, I only pass the final seed to the algorithm, not the original seed s3 or s4. The reason is that I want to interpolate between the seeds and the result should be an "interpolation" between the list's permutations.
Ideas I had thus far:
I could use simplex/perlin noise to sample elements: I generate a number between 0 and 1 and then use it to choose the next element from the list (0 meaning I choose the first element, 1 meaning I choose the last). Since these noise types can be "smooth", adding d will change the random value only slightly, meaning it will usually select elements in proximity of the ones it picked before adding d. However, I have a very hard time choosing a "good" frequency for the noise (high frequencies will remove the smoothness I need, low frequencies will result in no change when adding d). Also, once the list shrinks as I pick elements, the effect of d will decrease, because the range 0 to 1 will be mapped to fewer elements - and I don't really know if this is a problem yet...?

A: Generate and set aside a random shuffle R of the list. Then, every time the generator is invoked with seed s:

*

*Let s = s % factorial(N) where N is the length of the list (or just require that s should be between 0 and N!-1).

*Find the factorial representation  of s

*Convert the factorial representation to a permutation p

*Apply p to R and return the result.

The construction is such that the permutations p(s) and p(s+1) are adjacent in lexicographic order. The steps can be implemented efficiently.
You could use the same idea with other orderings of the set of permutations, which minimize changes even more, such as the Heap ordering or the Steinhaus-Johnson-Trotter ordering, but I don't know whether step 3. can be implemented efficiently in those cases.

A: If you can bear changing your definition of "similarity" to become defined as the number of swaps between elements of a permutation then we can use the
Trotter-Johnson permutation ordering where successive permutations differ by only one swap of two items in the perms.
There are algorithms to associate consecutive integer ranks with successive perms of the ordering and further algorithms that can generate the perm from the rank and vice-versa. usinf the seed as the rank value then two seeds that differ by n would need n swaps of items to go between their respective perms.
A lot of searching gives mention of the book:

D.L. Kreher and D.R. Stinson, Combinatorial Algorithms: Generation,
Enumeration, and Search, CRC Press, 1999.

I have turned it into the following Python:
# -*- coding: utf-8 -*-
"""
Created on Thu Jun  3 08:44:56 2021

@author: Paddy3118
"""

from typing import List

Perm = List[int]

_fact = [1]     # factorials cache

def print_perm(T: Perm) -> None:
    print(T)

def tj_unrank(n: int, r: int) -> Perm:
    "Returns the r-ranked Trotter-Johnson permutation of integers 0..n-1"
    global _fact

    for i in range(len(_fact), n+2):    # Extend factorial cache if necessary.
        _fact.append(_fact[i - 1] * i)

    pi: Perm = [0] * (n+2)
    pi[1] = 1
    r2 = 0
    for j in range(2, n+1):
        r1 = (r * _fact[j]) // _fact[n]
        k = r1 - j*r2
        if ((r2 % 2) == 0):
            for i in range(j-1, j - k - 1, -1):
                pi[i+1] = pi[i]
            pi[j-k] = j
        else:
            for i in range(j - 1, k, -1):
                pi[i+1] = pi[i]
            pi[k + 1] = j
        r2 = r1

    return [i - 1 for i in pi[1:-1]]

def tj_rank(n: int, p: Perm) -> int:
    "Returns the ranking of the Trotter-Johnson permutation p, of integers 0..n-1"
    assert set(p) == set(range(n)), f"Perm {p} not a perm of 0..{n-1}."

    pi = [0] + [i+1 for i in p] + [0]
    r = 0
    for j in range(2, n + 1):
        i = k = 1
        while pi[i] != j:
            if (pi[i] < j):
                k += 1
            i += 1
        if ((r % 2) == 0 ):
            r = j*r+j-k
        else:
            r = j*r+k-1

    return r

def tj_parity(p: Perm) -> int:
    "Returns the 0/1 parity of the Trotter-Johnson permutation p, of integers 0..n-1"
    n = len(p)
    assert set(p) == set(range(n)), f"Perm {p} not a perm of 0..{n-1}."

    pi = [0] + [i+1 for i in p] + [0]
    a, c = [0] * (n + 1), 0
    for j in range(1, n+1):
        if a[j] == 0:
            c += 1
            a[j] = 1
            i = j
            while ( pi[i] != j ):
                i = pi[i]
                a[i] = 1

    return (n-c) % 2

if __name__ == '__main__':
    from sys import argv
    import re

    if not (len(argv) == 2 and re.match(r'\d+', argv[1])):
        raise SystemExit('ERROR. Call needs an integer >0 argument')
    n = int(argv[1])
    if n <=0:
        raise SystemExit('ERROR. Call needs one integer >0 argument')

    print(f"Testing rank/unrank n={n}.\n");
    for i in range(len(_fact), n+2):    # Extend factorial cache if necessary.
        _fact.append(_fact[i - 1] * i)

    for r in range(_fact[n]):
        p = tj_unrank(n, r)
        rank = tj_rank(n, p)
        parity = tj_parity(p)
        print(f"  Rank: {r:4} to perm: {p}, parity: {parity} to rank: {rank}")

Sample output for n == 4
Testing rank/unrank n=4.

  Rank:    0 to perm: [0, 1, 2, 3], parity: 0 to rank: 0
  Rank:    1 to perm: [0, 1, 3, 2], parity: 1 to rank: 1
  Rank:    2 to perm: [0, 3, 1, 2], parity: 0 to rank: 2
  Rank:    3 to perm: [3, 0, 1, 2], parity: 1 to rank: 3
  Rank:    4 to perm: [3, 0, 2, 1], parity: 0 to rank: 4
  Rank:    5 to perm: [0, 3, 2, 1], parity: 1 to rank: 5
  Rank:    6 to perm: [0, 2, 3, 1], parity: 0 to rank: 6
  Rank:    7 to perm: [0, 2, 1, 3], parity: 1 to rank: 7
  Rank:    8 to perm: [2, 0, 1, 3], parity: 0 to rank: 8
  Rank:    9 to perm: [2, 0, 3, 1], parity: 1 to rank: 9
  Rank:   10 to perm: [2, 3, 0, 1], parity: 0 to rank: 10
  Rank:   11 to perm: [3, 2, 0, 1], parity: 1 to rank: 11
  Rank:   12 to perm: [3, 2, 1, 0], parity: 0 to rank: 12
  Rank:   13 to perm: [2, 3, 1, 0], parity: 1 to rank: 13
  Rank:   14 to perm: [2, 1, 3, 0], parity: 0 to rank: 14
  Rank:   15 to perm: [2, 1, 0, 3], parity: 1 to rank: 15
  Rank:   16 to perm: [1, 2, 0, 3], parity: 0 to rank: 16
  Rank:   17 to perm: [1, 2, 3, 0], parity: 1 to rank: 17
  Rank:   18 to perm: [1, 3, 2, 0], parity: 0 to rank: 18
  Rank:   19 to perm: [3, 1, 2, 0], parity: 1 to rank: 19
  Rank:   20 to perm: [3, 1, 0, 2], parity: 0 to rank: 20
  Rank:   21 to perm: [1, 3, 0, 2], parity: 1 to rank: 21
  Rank:   22 to perm: [1, 0, 3, 2], parity: 0 to rank: 22
  Rank:   23 to perm: [1, 0, 2, 3], parity: 1 to rank: 23

(Notice how successive perms differ by one swap of two items in the perms above).

A: It is kinda difficult to give a metric to "similar" in this case. [Ex: Apple had a problem with their first shuffle implementation - people did not feel like the songs were mixed randomly enough].
I would reformulate the problem in a different way "How we can modify some simple shuffling algorithm so we achieve the desired result?".

Here is my idea:

*

*We will need a baseline seed s - (something large, comparable to list sizes that are generally used in your case/data, this value could be either hardcoded or passed as a parameter, but should stay fixed if we vary s1)

*d = abs(s1 - s) - (how far is s1 from s)

*do a default shuffle with s as seed - (any function from random library of your language choice will suffice.)

*Now iterate over the list and swap any element with some probability p (0,1) with any other element that is at distance d from your position.
Ex: d = 2
1 2 3 4 5 6 7
element 5 can be swapped with 3,4,6 or 7. Basicaly element at pos i will be swaped with any element(could be also chosen randomly) in this range [i-d,i+d] with probability p.

*Manipulate p and s until your "similarity" score/feel is satisfied.


text:
Q: AngularJS: What is proper way of serving async AJAX request without $http Assume we have some service that fetch data from server. It's async and is not using AngularJS $http service.
When we deal with async stuff in Angular - we use $q promises. But there is one problem: promises are resolved only after $digest.
There are 2 possible ways to fix it:
1) $timeout

var defer = $q.defer();
$.getJSON('http://example.com/my.json')
    .success(function (data) {
       $timeout(function () {
         defer.resolve(data);
       });
    });
return defer.promise;

2) $rootScope.$apply()
var defer = $q.defer();
$.getJSON('http://example.com/my.json')
    .success(function (data) {
       defer.resolve(data);
    });
if (!$rootScope.$$phase) $rootScope.$apply();

In AngularJS $http service second variant is used.
What the difference between both is and what is proper way to do such stuff?
You are able to try both methods in action: http://jsbin.com/otakaw/3/edit


text:
Q: How to make Robots.txt and Sitemap.xml only accessable through search engine bots Several website like Quora, Stackechange, and including Stackoverflow (https://stackoverflow.com/sitemap.xml) only access through the search engine crawlers (Google, Yahoo, Bing, etc).

*

*How can i do same for my website robots.txt and sitemap.xml

*What are the user-agents these crawlers use and where i can find a list

*Google and Bing crawlers do not use any static IP's, they are dynamic and lot of IP's. How this big site like Stackoverflow manage whitelisting IP's of crawlers.

*How big site content indexed instantly on Google. like my this question will get indexed instantly after publishing it. where my website usually take 2-7 days for indexing.


text:
Q: How do I change the amount of items retrieved from a flickr feed? Does anyone know the parameter to change (decrease) the amount of items retrieved in the flickr feed?
It always returns 20 items by default. Example:
http://api.flickr.com/services/feeds/photos_public.gne?format=json
The documentation is rather scarce:
http://www.flickr.com/services/feeds/

A: Not possible it seems.

A: There doesn't seem to be a way to control this from the flickr API, however, I did come up with another site which offers RSS of flickr feeds (precisely because the flickr API is limiting)
http://www.degraeve.com/flickr-rss/


text:
Q: Java Animated transparent splash screen I'd like to make a splash screen with an animated gif. My animated gif has a transparent background so I'd like to display only the visible part of my gif as a splash screen.
First of all, I must specify that I'm using Matlab so it is not possible (or I haven't found how) to override components/functions.
Here my sample code :
 win = javax.swing.JWindow;
 jl = javax.swing.JLabel(javax.swing.ImageIcon('C:\Users\ME\Documents\loader512-.gif'));
 win.getContentPane.add(jl);
 win.setAlwaysOnTop(true);
 win.pack;
 %% set the splash image to the center of the screen
 screenSize = win.getToolkit.getScreenSize;
 screenHeight = screenSize.height;
 screenWidth = screenSize.width;
 % get the actual splashImage size
 imgHeight = 512;
 imgWidth = 512;
 win.setLocation((screenWidth-imgWidth)/2,(screenHeight-imgHeight)/2);
 win.show

It works very well shwing the image, however its background is ether white or gray depending on the transparency of the window.
I also tried to play with the background of the JLabel without success.
Please help !

A: The problem with your code is that every given window has a particular defined shape. Without changing the shape every Window object has a rectangular canvas in which it draws upon. The transparency only applies if you draw a object behind your GIF image. If transparency is enabled the renderer merely draws the background colour (which is normally black or white or some light gray) if nothing else is present.
Since the release of Java 7 a new method called setShape(Shape); appeared for Window objects. If your animated GIF has a fixed transparency "zone" I advise creating a custom java.awt.Shape object in which you pass to the win object via set shape.
Example:
win = javax.swing.JWindow;
jl = javax.swing.JLabel(javax.swing.ImageIcon('C:\Users\ME\Documents\loader512-.gif'));
win.getContentPane.add(jl);
Shape S = createCustomShape(); //Create your shape
win.setShape(S);
win.setAlwaysOnTop(true);
//{rest of code...}

If the animated GIF has a changing transparency background, you must create a complex implementation in which the Shape object updates on a frame by frame basis in response to the GIF. In my opinion, if this is the case, I wouldn't bother. :)
Read more on the Shape object here.
N.B. The Shape "object" is actually a interface, either use one of the implementing subclasses or create your own.


text:
Q: Key pressed and click in the same time how can I merge keypress and on click? I mean when a user press enter and click somewhere in the same time I need to invoke a function.
$(document).keypress(function(e) {
    var code = e.keyCode || e.which;
    if(code == 13) {
        alert('keypress');
    }
});
$(document).on( "click", function() {
    alert('click');
});

I have this code but I am not able to merge it (usually I don't work with jQuery/javascript).

A: Here's an example that will work if enter is pushed first or if the mouse is clicked first or if they are both pressed within a certain threshold of time apart (I set it to 100 ms, but this can be easily adjusted):
var enterDown = false;
var mouseDown = false;
var lastEnter = false;
var lastMouseUp = false;

var triggerOnNextUp = false;
$(document).on({
    keydown: function(e) {
        enterDown = true;
    },
    keyup: function(e) {
        if(e.which == 13) {
            lastEnter = (new Date()).getTime();
            enterDown = false;
            detectEnterAndClick();
            if (mouseDown) {
                triggerOnNextUp = true;
            }
        }
    },
    mousedown: function() {
        mouseDown = true;
    },
    mouseup: function() {
        lastMouseUp = (new Date()).getTime();
        mouseDown = false;
        detectEnterAndClick();
        if (enterDown) {
            triggerOnNextUp = true;
        }
    }
});

function detectEnterAndClick() {
    if (Math.abs(lastEnter - lastMouseUp) < 100 || triggerOnNextUp) {
        // Reset variables to prevent from firing twice
        triggerOnNextUp = false;
        enterDown = false;
        mouseDown = false;
        lastEnter = false;
        lastMouseUp = false;

        $("body").append("Clicked and pushed enter<br>");
    }
}

See it on JSFiddle

A: Something like this may do the trick
var pressingEnter = false;
$(document).on({
    keydown: function(e) {
        if(e.which == 13) {
            // enter is being pressed, set true to flag variable
            pressingEnter = true;
        }
    },
    keyup: function(e) {
        if(e.which == 13) {
            // enter is no longer pressed, set false to flag variable
            pressingEnter = false;
        }
    },
    click: function() {
        if (pressingEnter) {
           console.log('click and enter pressed');
        }
    }
});

BTW: there is no need to do var code = e.keyCode || e.which; since jQuery resolves that for you. You can use e.which on any browser.
EDIT
This version should allow any order of key pressed / mouse click. I'm assuming only left click is captured. Logic to handle enter + mouse click is placed on keydown and mousedown (it could be moved to keyup and mouseup if makes more sense)
Changed alert  by console.log since the first prevents mouseup event to be triggered. Nowdays we have hundred of better ways to show a message to user than built-in alert pop ups so I'll assume making it work for it is not a requirement.
var pressingEnter = false;
var clickingMouseButton = false;
$(document).on({
    keydown: function(e) {
        if(e.which == 13) {
            pressingEnter = true;
        }

        if (clickAndEnterPressing()) {
            console.log('click and enter pressed');
        }
    },
    keyup: function(e) {
        if(e.which == 13) {
            pressingEnter = false;
        }
    },
    mousedown: function(e) {
        if (e.which == 1) {
            clickingMouseButton = true;
        }

        if (clickAndEnterPressing()) {
            console.log('click and enter pressed');
        }
    },
    mouseup: function(e) {
        if (e.which == 1) {
            clickingMouseButton = false;
        }
    }
});

function clickAndEnterPressing() {
    return pressingEnter && clickingMouseButton;
}

A: There is no way to 'merge' events. However you could for example debounce your handler. For example (using lodash):
var handler = _.debounce(function(event) { alert(event.type); }, 100);
$(document)
  .on('click', handler)
  .on('keypress', handler);

A: you can use the event.type to determine what triggered the event
Demo
$(function(){
    $(document).on("click", ClickAndKeyPress);

  $(document).on("keypress", ClickAndKeyPress);
});

function ClickAndKeyPress(event){
  $("div").text(event.type);
}


text:
Q: javascript selector for item when next is not visible Say I have a list of nodes
A
B
B
A
A
A
B
B

I want a selector querySelector or function that will match all A items where they are followed by a visible B item.
jQuery has a $(".a ~ .b:visible") except this returns a list of the .b selectors and I want the .a. And it's jQuery, not pure javascript.

A: You can use combination of :has() and + adjacent sibling selector.

$('.a:has(+ .b:visible)').css('color', 'red')

A

B

B

A

B

B

Or you can select .b:visible and then prev(.a) element.

$('.b:visible').prev('.a').css('color', 'red')

A

B

B

A

B

B

A: have you tried the .next() method?
var list
$(".a")each(function(index, obj)  {
   if($(obj).next().is(":visible")) {
      list += obj
   }
})

A: I think this is easier way to do that:
$('.a + .b:visible').prev()


text:
Q: Save the variable in a JSON file I am very new in Javascript and trying to learn by experiencing it. Sorry if this question is a multiplication or super-easy one. I am using an open source server and I need to make some additions.. following is the part of code:
    /**
 * Event listener
 *
 * @param {SceneJS.node} hit Selected SceneJS node
 */
pick: function(hit) {
    this.unselect();
    this.highlighted = this.SYSTEM.scene.findNode(hit.nodeId);
    var groupId = this.highlighted.findParentByType("translate").data.groupId;
    strID = (hit.nodeId);
    alert(strID);
........

I defined the strID variable as a global. In the final use, I select a node of a 3D model in browser, and the nodeID of the selected element is appeared on screen as an alert. How can I write the selected entity's "nodeId" (or "strID" variable) in a JSON file, and save the file in a folder in local drive. So I can use this JSON file for further steps.
Maybe I don't know which keywords to search.. I checked couple of ways like JSONstringify but couldn't succeed. Any helps are appreciated.

A: You should check localStorage, to save this data between sessions.
localStorage.setItem('strID', strID);

and
strID = localStorage.getItem('strID');

A: Sorry, I didn't read about node, but lets try it:
    /**
 * Event listener
 *
 * @param {SceneJS.node} hit Selected SceneJS node
 */
pick: function(hit) {
    this.unselect();
    this.highlighted = this.SYSTEM.scene.findNode(hit.nodeId);
    var groupId = this.highlighted.findParentByType("translate").data.groupId;
    strID = (hit.nodeId);
    alert(strID);
    var fs = require('fs');
    fs.writeFile("/data/strID", strID, function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
    });
........

To read it use readFile. It it is giving problems about the data format of strID, use JSON-JS to transform to readable before saving


text:
Q: Python/R: Matching list of strings with other list of strings I need to extract a subset of IDs (strings) from a complete dataset with more than 4000 IDs. I have my list of IDs (eg. 'NDR895', 'NDR361',...) that I need from the bigger dataset saved as dataframe (or list), and the IDs in the bigger dataset are slightly different (eg. 'sb-NDR895_T1', 'sb-NDR361_T1',...). I tried it with grepl() and regex() but both options don't really work, because the strings are different.
Does anyone know how I could fix this using python or R?
In R, I tried something like this:
match <- NULL
for (i in 1:length(ID1$ID)) {
match = as.data.frame(rbind(match, grep(I, ID2$ID, value = T)))
}

But this doesn't work!?
Thanks for the help!

A: In R:
You can use grepl() to find a pattern in a string:
a <- "NDR895"
b <- "NDR361"

ids <- c("sb-NDR895_T1", "sb-NDR361_T1")

grepl(a, x = ids)
#> [1]  TRUE FALSE
grepl(b, x = ids)
#> [1] FALSE  TRUE

You could define a pattern based on your target strings, where | means 'or':
targets <- c(a, b)

pattern <- paste(targets, collapse = "|")
pattern
#> [1] "NDR895|NDR361"

grepl(pattern, ids)
#> [1] TRUE TRUE

General example of using this approach to subset a dataframe:
df[grepl(pattern, df$ids),]


text:
Q: Opening a modal using dialog API in Outlook 365 shows a "new window" alert I'm implementing the login system in my new Outlook 365 add-in, but I have a problem with an alert "{Addin name} wants to display a new window" shown when users try to open the modal login window. This doesn't happen in other Outlook 365 add-ins.
Following the documentation there's no mention of any restrictions: (https://learn.microsoft.com/en-us/office/dev/add-ins/develop/dialog-api-in-office-add-ins) but it's nevertheless showing up as you can see:

I included my domain in "AppDomains" in manifest in case that's the problem, but the problem persists.
Any suggestions would be appreciated.
Update: Here's the relevant piece of code:
export const modalLogin = () => dispatch => {
    return new Promise(resolve => {
        Office.context.ui.displayDialogAsync(urls.login, {height: 50, width: 50},
            function (asyncResult) {
                let dialog = asyncResult.value;
                dialog.addEventHandler(Office.EventType.DialogMessageReceived, (arg) => {
                    let messageFromDialog = JSON.parse(arg.message);
                    if (messageFromDialog.outcome === "success") {
                        dispatch(requestDone(resources.login, messageFromDialog.response));
                    } else {
                        dispatch(requestError(resources.login, messageFromDialog.response));
                    }
                    dialog.close();
                    resolve();
                });
            }
        );
    })
};

A: Just set promptBeforeOpen:false in the displayDialogAsync.
https://learn.microsoft.com/en-us/javascript/api/office/office.dialogoptions?view=office-js#promptbeforeopen

A: This is by design. If the page you are trying to open can open in an iframe, you should set displayInIFrame: false (default value).

A: You should not use displayInIframe: true if the dialog will at any point redirect to a page that cannot be opened in an iframe.
For example, the sign in pages of many popular web services, such as Google and Microsoft Account, cannot be opened in an iframe.


text:
Q: Gulp-protractor keep saying "Spec patterns did not match any files" I'm trying to run my end to end tests written with protractor and jasmine. It works perfectly when I call protractor protractor.config.js directly.
However, when I use gulp-protractor, I keep getting the "Spec patterns did not match any files" error and the tests do not run.
This is my protractor runner gulp task:
gulp.task('protractor-run', function (done) {
    return gulp.src(["./e2e-tests/**/*-spec.js"])
        .pipe(protractor({
            configFile: "./config/protractor-config.js",
            args: ['--baseUrl', 'http://127.0.0.1:8000']
        }))
        .on('error', function(e) { throw e })
});

and this is the error:
WARNING - pattern C:\path\to\app\e2e-tests\login\login-spec.js did not math any files.
[launcher] Process exited with error code 1
C:\path\to\app\node_modules\protractor\node_modules\q\q.js:126
                   throw e;
                   ^

Error: Spec patterns did not match any files.

What am I missing?

A: I managed to get it working. By providing an empty readable stream. Then you specify your spec files in the config file instead.
var protractor = require('gulp-protractor').protractor;

gulp.task('protractor', ['webdriverUpdate'],function(){
      return gulp.src([])
          .pipe(protractor({
            configFile: __dirname + '/protractor.conf.js'
          }));
});

also don't forget the webdriverUpdate
var webdriverUpdate = require('gulp-protractor').webdriver_update;

gulp.task('webdriverUpdate', webdriverUpdate );

and in the config file this:
seleniumServerJar: './node_modules/protractor/selenium/selenium-server-standalone-2.47.1.jar',

With this I stopped getting the error.
Update
The issue #2551 is closed and fixed since 2.5.0

A: I resolved this in a gulpfile that launches protractor tests by putting a file path into the parameter of gulp.src(['file_path_goes_here']).  The task I was trying to run had no file path between the brackets, and was throwing the error.
gulp.task('works', 'Run some tests', function() {
  gulp.src(['path/to/test.spec.js'])
    .pipe(protractor({
      configFile: __dirname + '/../test/protractor.conf.js',
      args: ['--baseUrl', 'http://localhost:9099']
    }))
});

gulp.task('error', 'Run feature tests locally', function() {
  gulp.src([''])
    .pipe(protractor({
      configFile: __dirname + '/../test/protractor_local.conf.js',
      args: ['--baseUrl', 'http://localhost:9099']
    }))
});


text:
Q: Jquery hide all elements that are not in array Is it possible to hide all elements that are NOT in an array using Jquery?
I have over 40 inputs/selects on a form and I want to hide some of them when I use a select on the form.

$("#type").on('change', function() {
      if ($("#type").val() === "Blue") {
        var elements = [$("#id-element"), $(".class-element), ... , ... ]; // these elements should be visible and the remaining elements on the form I want to hide them.
          }
        });

<select id='type'>
        <option> Blue </option>
        <option> Red </option>
    </select>

A: you can use jquery's not

$("#type").on('change', function() {
  if ($(this).val() === "Blue") {

  //note that this is a single string with comma sepreating between different selectors
    var elements = "#id-element,.class-element";

    //select all inputs
    $("input").not(elements).hide();
  }
});

<select id='type'>
        <option> select one </option>
        <option> Blue </option>
        <option> Red </option>
</select>

<input id="id-element" value="#id-element" />

<input class="class-element" value=".class-element" />

<input id="other-id" value="#other-id" />

<input class="other-class" value=".other-class" />


text:
Q: Helpers for walk through and searching node in the tree structure (D3.js way) When I working with tree-structured data in the d3.js I often need to call forEach or filter analog on the data.
For example, here is the data:
data = {
  id: 0,
  children: [ {
    id: 1,
    children: [ ... ]
  }, {
    id: 2,
    children: [ ... ]
  }]
}

To check if the node with id = 5 exists in the data I have to implement the recursive search function through all the children. Something like this:
function hasNodeWithId(node, id) {
    if (node.id === id) {
        return true;
    } else {
        return _.any(node.children || [],
            function(n) { return hasNodeWithId(n, id); });
    }
}

The search of the node inside the tree is such a common task so I wonder if there are some sort of helper functions in the d3.js library for this. If not, then how do others approach this sort of problems?
P.S.
Sometimes I can use the tree.nodes function to get a flat array:
var theId = 5,
    tree = d3.layout.tree(),
    nodes = tree.nodes(data), // makes a flat array of all the nodes in the data
    theNode = nodes.filter(function(d) { return d.id === theId; });

But calling tree.nodes(data) every time I need to walk through the data is overwhelming and has some side effects (x, y, depth fields) on data.


text:
Q: How to change Scala version in SBT/Android Plugin/Project? I'm using SBT v0.13 with jberkel/android-plugin, which I am trying to modify.
In order to do that, I need to work with Scala 2.10.0-20120710-144914-026a70d555 in my test project.
So far, I've used Scala 2.9.1, and I need to switch to 2.10.0-20120710-144914-026a70d555 now, but I'm not so proficient with this stuff.
I've ran into this question, but that doesn't work for me.
I get the following output when I try to compile and push my test application to device:
[info] Wrote C:\Users\Administrator\myProject\target\scala-2.10.0-20120710-144914-026a70d555\src_managed\main\scala\com\google\summer\TR.scala
[info] Updating {file:/C:/Users/Administrator/myProject/}My Project...
[info] Resolving org.scala-lang#scala-library;2.10.0-20120710-144914-026a70d555 ...
[warn]  module not found: org.scala-lang#scala-library;2.10.0-20120710-144914-026a70d555
[warn] ==== local: tried
[warn]   C:\Users\Administrator\.ivy2/local/org.scala-lang/scala-library/2.10.0-20120710-144914-026a70d555/ivys/ivy.xml
[warn] ==== public: tried
[warn]   http://repo1.maven.org/maven2/org/scala-lang/scala-library/2.10.0-20120710-144914-026a70d555/scala-library-2.10.0-20120710-144914-026a70d555.pom
[info] Resolving org.scalatest#scalatest_2.10.0-20120710-144914-026a70d555;1.8.RC1 ...
[warn]  module not found: org.scalatest#scalatest_2.10.0-20120710-144914-026a70d555;1.8.RC1
[warn] ==== local: tried
[warn]   C:\Users\Administrator\.ivy2/local/org.scalatest/scalatest_2.10.0-20120710-144914-026a70d555/1.8.RC1/ivys/ivy.xml
[warn] ==== public: tried
[warn]   http://repo1.maven.org/maven2/org/scalatest/scalatest_2.10.0-20120710-144914-026a70d555/1.8.RC1/scalatest_2.10.0-20120710-144914-026a70d555-1.8.RC1.pom
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.scala-lang#scala-library;2.10.0-20120710-144914-026a70d555: not found
[warn]  :: org.scalatest#scalatest_2.10.0-20120710-144914-026a70d555;1.8.RC1: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[error] {file:/C:/Users/Administrator/myProject/}My Project/*:update: sbt.ResolveException: unresolved dependency: org.scala-lang#scala-library;2.10.0-20120710-144914-026a70d555: not found
[error] unresolved dependency: org.scalatest#scalatest_2.10.0-20120710-144914-026a70d555;1.8.RC1: not found
[error] Total time: 1 s, completed 11.07.2012. 08:55:13

A: I think you need

set scalaVersion := "2.10.0-SNAPSHOT"

It will automatically pick the latest published scala version.


text:
Q: ngrx - marble testing and withLatestFrom I'm using Angular 8 and ngrx 8. I'm trying to write unit tests for an effect that uses withLatestFrom to get some values from the state. I'm using rxjs/testing/TestScheduler for this. In there, I have a marble diagram like this:
actions$ = hot('aa', { a: actions.fetchUser({ id: 1 }));

and my effect is similar to this:
fetchUser$ = createEffect(() => this.actions$.pipe(
  ofType(actions.fetchUser),
  withLatestFrom(this.store.select(selectors.user)),
  mergeMap(([{ id }, user]) => {
    console.log(user);
    if (user.id === id) {
      return of(user);
    }
    return this.userService.getUser(id).pipe(
      map((user) => actions.updateUser({ user })),
      catchError(() => of(actions.updateUser({})))
    )
  })
))

The inial user in the store is an empty object.
The idea is the first marble frame goes through by calling userService and updates the state; then the second frame happens and it sees the user.id, which is set during the first frame, and so instead of calling userService, it returns the user instance that is already in the state. (This is just an example; the final goal is to avoid duplicate HTTP calls in the service or cancel the previous one if the user id changes).
The issue is that it seems the state doesn't update during the marble diagram and the user object returned from withLatestFrom is always the one from the initial state set in the tests.
I'm new to Angular and ngrx testing, so I'm not sure if that's the expected behavior or I'm doing something wrong.
It'd also be great if anyone can recommend a better way of handling and testing such a scenario.

A: I saw this note in the documentation for the mock store that says "All dispatched actions don't affect the state", so I guess the state doesn't change during a marble diagram.
I changed my test so it sets the state with a user before getting into the marble stuff. It's now something like this:
it('should use the user in store when called with the same id', () => {
  scheduler.run(({ hot, expectObservable }) => {
    const fetchUser = actions.fetchUser({ id: 1 });
    const updateUser = actions.updateUser({ user });

    store.setState({
      user
    });

    spyOn(userService, 'getUser').and.callThrough();

    actions$ = hot(
      `a`,
      { a: fetchUser }
    );

    // The result should come immediately because the user with the given id is already in the store
    const expectedMarble = `a`;
    const expectedValues = { a: updateUser };

    expectObservable(effects.fetchUser$).toBe(expectedMarble, expectedValues);
    });

  expect(userService.getUser).not.toHaveBeenCalledWith(1);
});