text:
Q: How can I style polygons with parameters inside the FeatureCollection properties on Leaflet? I have a GeoJSON file that has both the FeatureCollection and the Feature types inside it. Basically my code is the following (working sample here):
L.geoJSON(myJSON, { style: style }).addTo(mymap);

function style(featureObject) {
    return {
        fillColor: getColor(featureObject.properties.name),
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.7
    };
}

function getColor(name) {
    return name === "name1" ? "#CF8562" :
            name === "name2" ? "#FFEDA0" :
                                "#000000";
}

And a small sample of the structure of my GeoJSON is the following:
[
  {
    "type": "FeatureCollection",
    "properties": {
        "name" : "name1"
    },
    "features": [
      {
        "type": "Feature",
        "properties": {
            "randomParameter" : "text"
        },
        "geometry": {
          "type": "Polygon",
          "coordinates": [
            [
            [
            -46.6479847244904,
            -23.553060554172923
            ],
            [
            -46.6479847244904,
            -23.553060554172923
            ],
            [
            -46.64805562776844,
            -23.55318890961171
            ],
            [
            -46.64826795788915,
            -23.552928264599316
            ],
            [
            -46.6479847244904,
            -23.553060554172923
            ]
            ]
          ]
        }
      }]
  },
  {
    "type": "FeatureCollection",
    "properties": {
        "name" : "name2"
    },
    "features": [
      {
        "type": "Feature",
        "properties": {
            "randomParameter" : "text2"
        },
        "geometry": {
          "type": "Polygon",
          "coordinates": [
            [
            [
            -46.648050596629034,
            -23.55393832474017
            ],
            [
            -46.64758222900779,
            -23.554141824100373
            ],
            [
            -46.64767437978837,
            -23.554322319586415
            ],
            [
            -46.64814729501603,
            -23.55411425749883
            ],
            [
            -46.648050596629034,
            -23.55393832474017
            ]
            ]
          ]
        }
      }]
  }
]

This code is not going to work properly because it doesn't recognize the featureObject.properties.name value. This value exists only inside the FeatureCollection and not the Feature type in my GeoJSON. So, I'm not capable of coloring the polygons according to the data that I have inside the GeoJSON.
I'd like to edit the style of all elements under a FeatureCollection type. However, when I print the object arriving on the style function, I see that it only sees the elements with the Feature type. I've read answers like this one telling that we can edit the style of the FeatureCollection type but I didn't manage to make it work.
I'd like to solve this problem without having to change my GeoJSON structure or changing the properties inside FeatureCollection to Feature. Is it possible? Can I make the style function change the style of everything under the FeatureCollection type instead of the Feature type in my GeoJSON?

A: GeoJSON format specification (see https://datatracker.ietf.org/doc/html/rfc7946) knows nothing about feature collection properties attribute, so it's expected that it's not accessible in standard GeoJSON data structures.
In your case the simplest solution would be to simply iterate through array of feature collections and assign corresponding name property to all features in feature collection:
for (var i = 0; i < myJSON.length; i++) {
  var features = myJSON[i].features;
  for (var j = 0; j < features.length; j++) {
    features[j].properties.name = myJSON[i].properties.name;
  }
}

EDIT: From your comment it seems like you would like to treat each feature collection from your array of collections as a separate layer. In this case you create separate layer for each feature collection and put them together in a group layer.
To be able to access individual layer in a group layer by name, object layerNameToId is created with properties that connect name with layer internal id.
Code could then look something like this:
var layerGroup = L.layerGroup([]).addTo(map);
var layerNameToId = {};

for (var i = 0; i < myJSON.length; i++) {
  var features = myJSON[i].features;
  var layer = L.geoJSON(myJSON[i], {
    onEachFeature: function(feature) {
      feature.properties.name = myJSON[i].properties.name
    }
  });
  layer.setStyle(style);
  layerGroup.addLayer(layer);
  layerNameToId[myJSON[i].properties.name] = layerGroup.getLayerId(layer);
}

You can then remove desired layer with name name2 from the group layer simply by:
layerGroup.removeLayer(layerGroup.getLayer(layerNameToId['name2']));


text:
Q: Python Requests: downloaded image file binary not identical to original? I am saving image file from the web using Python Requests. However, saved file is a little bit binary different than the original and a bit bigger. It still is a valid jpg file, but scrambled.
Here is the code:
import requests
import shutil
import os

if __name__ == "__main__":

image_url = 'http://www.123.com/image.jpg'
filename = 'out.jpg'
username = 'myusername'
password = 'mypasword'
path = os.path.join('c:/', filename )

r = requests.get(image_url, auth=(username, password), stream=True)
if r.status_code == 200:
    with open(path, 'w') as f:
        r.raw.decode_content = False
        shutil.copyfileobj(r.raw, f)

print 'The End'

What am I doing wrong?

A: open(path, 'w')
should be:
open(path, 'wb')
The b is for "binary". This will make sure Python won't try to convert character encodings and newlines and reads or writes everything exactly as it is byte-for-byte.
Also see the open() documentation

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tomcat project cleaning error When I try to clean the project from tomcat. I'm getting this error:

Could not delete <file name>. May be locked by another process.

Is there any way to counter this problem?

A: First of all, try to just restart tomcat.
Then, try to clean everything:

*

*Clean the Tomcat server: in Eclipse, right click on Tomcat vX.Y Server > Clean.

*Clean the project: menu Project > Clean.

*Clean the resource of the server: click the ‣ next to Tomcat vX.Y Server, underneath it your project is displayed, right click it and select "Clean Module Work Directory..."

You can also try to start the server in Debug mode: right click Tomcat vX.Y Server > Debug.

A: You just try to clean your tomcat server .

*

*Go to tomcat server properties >switch to location >apply

*Then clean your tomcat directory .

*Clean Tomcat

Its work for me

A: The message is good, you have another process/application currently using the resources eclipse is trying to clean. If you're on linux, you can use lsof to find it. On windows, you have to guess or go through all applications currently opened.


text:
Q: React-Select 1.0.0-rc.5 - Select doesn't open when clicking inside after choosing an option I implemented the Select component from the react-select library with the latest version (1.0.0-rc.5).
I am able to click in the Select element to open the list. I choose a value, which closes the list and displays the value I selected. However, when I click the element again to display the list of options, nothing happens. It will only open the list after I click away (probably after the blur event).
I tried working around this issue by using the autoBlur={true} prop, but I can't tab to the next element on the page in IE 11.
I did notice that this doesn't happen on the demo page, which still uses version 0.9.1.
Anyone know why this is happening?
EDIT
This is a sample of my class
export class TestSelect extends React.Component {
    constructor(props) {
        super(props);
    }

    updateValue = (selectedItem) => {
        this.setState({ selectValue: selectedItem });

        if (this.props.onChange) {
            this.props.onChange(selectedItem);
        }
    }

    render() {
        return (

                <Select
                    options={this.props.options}
                    className="select-class"
                    clearable={false}
                    onChange={this.updateValue}
                />

        );
    }
}

This is the page that implements the class
const TestPage = () =>{

    return(
        <TestSelect
            id="select-id"
            options={testSelectOptions}
    />);

}

export const testSelectOptions = [
    { value: '1', label: 'Option 1' },
    { value: '2', label: 'Option 2' },
    { value: '3', label: 'Option 3' }
];

export default TestPage;

A: I figured it out. My input had a min-width set to 95% when an option was selected.
This causes the event.target.tagName to be INPUT when trying to click inside the dropdown, which causes the code to return before any focus events are fired.


text:
Q: google drive api TypeError: Cannot read property 'drive' of undefined or TypeError: Cannot read property 'files' of undefined import { gapi } from 'gapi-script';
    gapi.client.drive.files.create({
    "name": "settings.txt",
}).execute();

gapi.load('client', function () {
    gapi.client.load('drive', 'v2', function () {
        gapi.client.drive.files.create({
            "name": "settings.txt",
          }).execute();
    });
});

=> first : TypeError: Cannot read property 'drive' of undefined
=> second : TypeError: Cannot read property 'files' of undefined
I am trying to create a file using Google Drive api.
However, it does not run as a type error appears.
I used both typescript and Javascript, but it failed.
How do I fix it?


text:
Q: replacing mapping character using regex in java I want to replace all 'A' of a string by 'B', and all 'B' by 'Z' so that the result of "ABCAAB" will be "BZCBBZ".
Is there a way to replace the following code using the replaceAll function?
String init = "ABCAAB"
String res = "";

for (char c: init.toCharArray()){
    switch (c) {
        case 'A':res = res+'B';
        case 'B':res = res+'Z';

        default :res = res+c;

       }
    }

A: If you know that your string is in upper case letters then you can make the replacement characters lower case, thus marking them as changed. This means that you can change A to b and B to z with out changing A to Z. Once all the transformations have been done you can upper case the string.


text:
Q: Upload Image directly to bucket on s3 amazon issue I am a newbie on Amazon s3. I am facing the issue regarding uploading the image directly from frontend to amazon s3 bucket.
I also viewed many tutorials but there is no proper explanation of upload image directly to s3. They teach us how to upload image through local computer to s3.
I implemented the code but not able to identified that how I can upload image without saving to my local machine.
Here is the code which I implemented but not luck to achieve it:
s3ImageUpload: (req, res) => {
        var fs = require('fs');
        var multer = require('multer');
        var AWS = require('aws-sdk');
        var path = require('path');

        var awsCredFile = path.join(__dirname, '.', 'key.json');

        console.log('awsCredFile is');
        console.log(awsCredFile);

        AWS.config.loadFromPath(awsCredFile);

        var s3 = new AWS.S3();

        var photoBucket = new AWS.S3({params: {Bucket: 'testbucket'}});

        var sampleFile = {
            //"_id" : 345345,
            //"fieldname" : "uploads[]",
            //"originalname" : "female.JPG",
            //"encoding" : "base64",
            //"mimetype" : "image/jpeg",
            "destination" : "./public/images",
            "filename" : "female.jpeg",
            "path" : "/images/female.jpeg",
            //"size" : 251556,
            //"user" : "579fbe61adac4a8a73b6f508"
        };

        var filePathToSend = path.join(__dirname, '../public', sampleFile.path);

        function uploadToS3(filepath, destFileName, callback) {
            photoBucket
                .upload({
                    ACL: 'public-read',
                    Body: fs.createReadStream(filepath),
                    Key: destFileName.toString(),
                    ContentType: 'image/png'
                })
                // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3/ManagedUpload.html#httpUploadProgress-event
                .on('httpUploadProgress', function(evt) { console.log(evt); })
                // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3/ManagedUpload.html#send-property
                .send(callback);
        }

        multer({limits: {fileSize:10*1024*1024}});

        console.log('filePathToSend is ');
        console.log(filePathToSend);

        uploadToS3(filePathToSend, sampleFile.filename, function (err, data) {
            if (err) {
                console.error(err);
                return res.status(500).send('failed to upload to s3').end();
            }
            res.status(200)
                .send('File uploaded to S3: '
                    + data.Location.replace(/</g, '<')
                    + '
')
                .end();
        });

        console.log('uploading now...');
    }

A: Pre-signed URLs could be a good solution for you.
On your backend, you can sign an URL using the AWS SDK. Then you just have to send this URL back to the client. Finally, the client can upload to file using this URL.
https://docs.aws.amazon.com/AmazonS3/latest/dev/PresignedUrlUploadObject.html


text:
Q: Multi file assemblies What is the difference and advantage between having a single file assembly that is physically coded in multiple .cs files and a multi file assembly that has multiple .NetModules??
My prof says that the difference could be realized when these assemblies get loaded or during jitting. That not all .Netmodules of a multi file assembly will be loaded at once. But even he is not sure. Could anybody clarify me?

A: Lets assume that we have two .cs files called
RUT.cs, which contains rarely used types
FUT.cs, which contains frequently used types
Now csc /t:module RUT.cs
This line causes the C# compiler to create a RUT.netmodule file. This file is a standard DLL PE
file, but, by itself, the CLR can't load it.
Next let's compile the frequently used types into their own module. We'll make this module
the keeper of the assembly's manifest because the types are used so often. In fact, because
this module will now represent the entire assembly, I'll change the name of the output file to
JeffTypes.dll instead of calling it FUT.dll:
csc /out:JeffTypes.dll /t:library /addmodule:RUT.netmodule FUT.cs

This line tells the C# compiler to compile the FUT.cs file to produce the JeffTypes.dll file.
Because /t:library is specified, a DLL PE file containing the manifest metadata tables is
emitted into the JeffTypes.dll file. The /addmodule:RUT.netmodule switch tells the compiler
that RUT.netmodule is a file that should be considered part of the assembly. Specifically, the
/addmodule switch tells the compiler to add the file to the FileDef manifest metadata table
and to add RUT.netmodule's publicly exported types to the ExportedTypesDef manifest
metadata table.

The RUT.netmodule file contains the IL code generated by compiling RUT.cs. This file also
contains metadata tables that describe the types, methods, fields, properties, events, and so
on that are defined by RUT.cs. The metadata tables also describe the types, methods, and
so on that are referenced by RUT.cs. The JeffTypes.dll is a separate file. Like RUT.netmodule,
this file includes the IL code generated by compiling FUT.cs and also includes similar definition
and reference metadata tables. However, JeffTypes.dll contains the additional manifest
metadata tables, making JeffTypes.dll an assembly. The additional manifest metadata tables
describe all of the files that make up the assembly (the JeffTypes.dll file itself and the
RUT.netmodule file). The manifest metadata tables also include all of the public types
exported from JeffTypes.dll and RUT.netmodule
Now if some clinet code refrencing to JeffTypes.dll is executing,
When a method is called for the first time, the
CLR detects the types that the method references as a parameter, a return value, or as a
local variable. The CLR then attempts to load the referenced assembly's file that contains the
manifest. If the type being accessed is in this file, the CLR performs its internal bookkeeping,
allowing the type to be used. If the manifest indicates that the referenced type is in a different
file, the CLR attempts to load the necessary file, performs its internal bookkeeping, and
allows the type to be accessed. The CLR loads assembly files only when a method referencing
a type in an unloaded assembly is called. This means that to run an application, all of the files
from a referenced assembly do not need to be present.
So, less used source classes could be compiled in NetModules and loaded when necessary, boosting performance and less Dll file sizes eases change management and deployment process.

Images and some of the quotes from jeffrey richter


text:
Q: Cannot resolve corresponding JNI function error when using JNA with C++ This is the code I used for the native-lib.cpp file.
extern "C" {

char *libName() {
    return (char *) "My Math Shared Library";
}

}

I used this whenever implementing it in the main activity file
package com.example.tenealaspencer.example;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.sun.jna.Native;

public class MainActivity extends AppCompatActivity {

    //loading native library
    static {
        Native.register(MainActivity.class, "native-lib");
    }

    //native methods signatures

    public native String libName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //calling native methods

        System.out.println(libName());
    }
}

I changed the dependencies to compile as JNA in the gradle(module), but I am still getting this error message.


text:
Q: git-http-backend, ro for all, write requiring password? (with lighttpd) I'd like to offer up read-only access to my GIT repos for everyone (i.e. no username/password required), but require authentication for writing.  The git-http-backend man page suggests this is possible by matching against the location ^/git/.*/git-receive-pack$.  For Apache 2.x it'd look like this:
<LocationMatch "^/git/.*/git-receive-pack$">
    AuthType Basic
    AuthName "Git Access"
    Require group committers
    ...
</LocationMatch>

Now, I'm using lighttpd, but translating the above shouldn't cause a problem.  Except that my access log suggests that the above wouldn't work anyway.  This is what I see when I perform a git push:
192.168.1.84 tracsrv.local - [06/Apr/2013:20:00:20 +0200] "GET /git/foo.git/info/refs?service=git-receive-pack HTTP/1.1" 403 5 "-" "git/1.8.2"

So it looks like I need to match on the query string.  For lighty I tried this:
$HTTP["querystring"] =~ "service=git-receive-pack" {
    $HTTP["url"] =~ "^/git" {
        cgi.assign = ( "" => "" )
        setenv.add-environment = (
            "GIT_PROJECT_ROOT" => "/srv/git",
            "GIT_HTTP_EXPORT_ALL" => ""
        )

        auth.backend = "plain"
        auth.backend.plain.userfile = "/srv/tracprjs/trac.plain"
        auth.require = (
            "/" => (
                "method" => "basic",
                "realm" => "trac",
                "require" => "valid-user"
                )
            )
    }
}

$HTTP["url"] =~ "^/git" {
    cgi.assign = ( "" => "" )
    setenv.add-environment = (
        "GIT_PROJECT_ROOT" => "/srv/git",
        "GIT_HTTP_EXPORT_ALL" => ""
    )
}

No password is required for git fetch and it is required for git push.  However, the git push doesn't actually succeed.  Any pointers on how to achieve this?

A: I found a working configuration with the help of the people on the git mailing list: http://www.spinics.net/lists/git/msg203744.html


text:
Q: MySQL View with a SubQuery I have the following view that I need to port from Oracle to MySQL. This works perfectly in Oracle, but not in MySQL due to a subquery cannot exist in a view error. How can I convert this to make it work in MySQL? If I am to make another view for this, how would it impact performance? Is it advisable? If so, how can I do that? If a 2nd view is not that great of an idea, how to convert this? Thanks for your help!
CREATE OR REPLACE VIEW view_name (var1, var2, var3, var4, var5) AS
SELECT SUM(A.var1a) var1,
        SUM(A.var2a) var2,
        SUM(A.var3a) var3,
        SUM(A.var4a) var4,
        SUM(A.var5a) var5
 FROM (SELECT CASE columnx when 'abc' then COUNT(E.ID) end var1a,
     CASE columnx when 'def' then COUNT(E.ID) end var2a,
     CASE columnx when 'ghi' then COUNT(E.ID) end var3a,
     CASE columnx when 'jkl' then COUNT(E.ID) end var4a,
                    COUNT(E.ID) var5a
             FROM   <list of tables>
            WHERE   <set of conditions>
         GROUP BY   columnx) A;

A: You should be able to rewrite this using the following:
CREATE OR REPLACE VIEW view_name (var1, var2, var3, var4, var5) AS
SELECT
    sum(CASE columnx when 'abc' then 1 else 0 end) var1a,
    sum(CASE columnx when 'def' then 1 else 0 end) end var2a,
    sum(CASE columnx when 'ghi' then 1 else 0 end) end var3a,
    sum(CASE columnx when 'jkl' then 1 else 0 end)end var4a,
    COUNT(E.ID) var5a
FROM   <list of tables>
WHERE   <set of conditions>


text:
Q: При одном и том же действии приходят разные результаты Asp.net Делаю связь многие ко многим и при добавлении новой книги мне либо приходят поля самой книги ,но не приходят id издательств которые пытаюсь привязать ,либо не приходят поля ,а приходят id издательств . А разница лишь в том что меняю имя .

Как вы видите если у меня имя model ,то приходят поля
а сейчас я поменяю имя на book

и у меня приходят id издательств, хотя ввожу все тоже самое
Вот моя ViewModel
public class AddBookViewModel
{
    public int BookId { get; set; }
    public string Name { get; set; }
    public string Author { get; set; }
    public int YearOfPublishing { get; set; }

    public virtual ICollection<PublicationHouses> PublicationHouses { get; set; }

    public ICollection<int> SelectedPublicationHouses { get; set; }

    public AddBookViewModel()
    {
        PublicationHouses = new List<PublicationHouses>();
        SelectedPublicationHouses = new List<int>();
    }
}

Если будет нужно ,то пришлю саму View
я не понимаю почему из-за того что я меняю имя мне приходят разные результаты , и может кто-то подсказать как сделать так чтоб приходили и поля книги и издательства
Если нужна подробная информация и чего-то не хватает ,пишите - я добавлю
P.S был до этого похожий вопрос у меня  Ошибка биндинга - приходит пустая модель
я поменял в своем вопросе имя magazine на model и проблема решилась
Вот View
@model Library.ViewModel.BookViewModels.AddBookViewModel

@{
ViewBag.Title = "AddBook";
}

<!DOCTYPE html>

<meta name="viewport" content="width=device-width" />

<link rel="stylesheet" href="~/Content/style-form.css" type="text/css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Oswald:400,300" type="text/css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.material.mobile.min.css" />

    {

            <button class="navbar-toggle collapsed" aria-expanded="false" aria-controls="navbar" type="button" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

            </button>
            Project name

Dashboard

Settings

Profile

Help

            <form class="navbar-form navbar-right">
                <input class="form-control" type="text" placeholder="Search...">
            </form>

@Html.ActionLink("Home", "Home", "Home") (current)

Reports

Analytics

Export

@Html.ActionLink("All Publications", "AllPublications", "Home")

@Html.ActionLink("Books", "Book", "Book")

@Html.ActionLink("Magazines", "Magazine", "Magazine")

@Html.ActionLink("Brochures", "Brochure", "Brochure")

@Html.ActionLink("Publication Houses", "PublicationHouse", "PublicationHouse")

Nav item again

One more nav

Another nav item

                @using (Html.BeginForm("AddBook", "Book"))
                {
                    @Html.AntiForgeryToken()

Add new book

                            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                            @Html.LabelFor(model => model.Author, htmlAttributes: new { @class = "control-label col-md-2" })

                                @Html.EditorFor(model => model.Author, new { htmlAttributes = new { @class = "form-control" } })
                                @Html.ValidationMessageFor(model => model.Author, "", new { @class = "text-danger" })

                            @Html.LabelFor(model => model.YearOfPublishing, htmlAttributes: new { @class = "control-label col-md-2" })

                                @Html.EditorFor(model => model.YearOfPublishing, new { htmlAttributes = new { @class = "form-control" } })
                                @Html.ValidationMessageFor(model => model.YearOfPublishing, "", new { @class = "text-danger" })

                        @Html.LabelFor(model => model.PublicationHouses)
                        <select id="required" name="Book.SelectedPublicationHouses" multiple="multiple" data-placeholder="Select Publication houses">
                            @foreach (var publicationHouse in Model.PublicationHouses)
                            {
                                <option value="@publicationHouse.PublicationHousesId">@publicationHouse.Name</option>
                            }
                        </select>

                        <button class="k-button" id="get">Add new item</button>

                }


text:
Q: Display Emotion Data Properly Using Json I'm working on an emotion reader. Users press a button and the screen starts displaying emotional data.
My problem is since it is using JSON's stringify, it displays the data in one straight line:
{ "joy":50, "sadness":0, "anger:0", "surprise": 0, "fear": 0, "contempt": 0, "disgust": 0}

I want to remove the curly braces. I also want to find a way to style the text joy, perhaps by adding bold or colors to the text but I'm not familiar with modifying JSON data.
detector.addEventListener("onImageResultsSuccess", function(faces, image, timestamp) {
    $('#results').html("");
    if (faces.length > 0) {
        log('#results',
            "<b>Emotions: </b>" + JSON.stringify(faces[0].emotions, function(key, val){
             return val.toFixed ? Number(val.toFixed(0)) : val;
            })
        );
    }
});


text:
Q: Spring security deployed app on AWS ThinkPHP request I Have a spring boot app running on AWS. From time to time I see a log that pops out saying and mentioning ThinkPHP?
java.lang.IllegalArgumentException: Invalid character found in the request target [/index.php?s=/Index/\think\app/invokefunction&function=call_user_func_array&vars[0]=md5&vars[1][]=HelloThinkPHP21].
The valid characters are defined in RFC 7230 and RFC 3986.
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:491) ~[tomcat-embed-core-9.0.36.jar!/:9.0.36]

And below:
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL contained a potentially malicious String ";"
at org.springframework.security.web.firewall.StrictHttpFirewall.rejectedBlacklistedUrls(StrictHttpFirewall.java:369) ~[spring-security-web-5.3.3.RELEASE.jar!/:5.3.3.RELEASE]

Is this a reason for concern or what's happening?
There's generally no traffic happening at all - no requests incoming to the server, yet this pops out.

A: ThinkPHP is a web application development framework which has had various vulnerabilities over the years.
Your application is the target of spray and pray vulnerability scanners.
You may find web server or application log entries with requests such as the following:
GET /index.php?s=/Index/\x5Cthink\x5Capp/invokefunction&function=call_user_func_array&vars[0]=md5&vars[1][]=HelloThinkPHP21 HTTP/1.1

As to whether you should be worried or not: it's really a question of what you are running and how well you are keeping up to date with your specific security requirements. Automated scanners are unlikely to find vulnerabilities for software you don't run.


text:
Q: Projection from group algebra to an irreducible representation It is well known that given a finite group $G$ and an irreducible representation $(V,\rho)$, we have a projector
$$e_V=\frac{\chi(1)}{|G|}\sum_{g\in G}\chi(g^{-1})g\in\mathbb{C}G,$$
such that $e_V^2=e_V$ and gives the projection $\pi:\mathbb{C}G\to V^{\oplus\dim V}$, $x\mapsto xe_V$.
But how can I find a projector onto a single copy of $V$, i.e. $\pi:\mathbb{C}G\to V$? (In this case, there should be at least $(\dim V)$ of such projectors.)
If a general solution does not exist, how can I deal with a particular case? Especially I need to find it for $G=A_4$ and $V$ is the unique three dimensional irreducible representation.


text:
Q: Linq-to-SQL statement for multiple aggregate values in single expression How would I write a Linq-to-SQL statement for the following TSQL?
select
  count(*),
  sum(Amount),
  avg(Amount),
  min(Amount),
  max(Amount)
from
  TableName

A: HACK ALERT, but it works. Try to group your records by a condition all of them share:
var result = from g in db.Employees
        group g by g.Id.GetType() == typeof(int) into gg
        select new
        {
            Count = gg.Count(),
            Sum = gg.Sum(x => x.Salary)
        };

This generates the SQL:
SELECT COUNT(*) AS [Count], SUM([t1].[Salary]) AS [Sum]
FROM (
SELECT 1 AS [value], [t0].[Salary]
FROM [dbo].[Employee] AS [t0]
) AS [t1]
GROUP BY [t1].[value]

There is a subquery involved, but hey! it's only one db trip

A: You could do:
var result = new
{
    Count = db.TableName.Count(),
    Sum = db.TableName.Sum(r => r.Amount),
    Average = db.TableName.Avg(r => r.Amount),
    Min = sb.TableName.Min(r => r.Amount),
    Max = db.TableName.Max(r => r.Amount)
}

A: It's probably easier to pull the values individually but you could do with an anonymous type.
var aggregates = new {
Count = context.TableName.Count(),
Sum = context.TableName.Sum(t => t.Amount),
Avg = context.TableName.Avg(t => t.Amount),
Min = context.TableName.Min(t => t.Amount),
Max = context.TableName.Max(t => t.Amount)
};


text:
Q: C#: Storing a reference to an array location in an object I have a c# object that sets the values of 2 floating point numbers. I have many such objects.
I would like to store these floating point numbers in an array. So the layout would be something like this:
Given a float array: float[] vec = new float[6]
Object 1 sets the values of vec[0] and vec[1]
Object 2 sets the values of vec[2] and vec[3]
Object 3 sets the values of vec[4] and vec[5]
How can I store references on the objects so they will access the correct vector element? I could store an index, but in the old-fashioned c++ world I could store a pointer directly into array.

A: When I need to use a C-style pointer to the middle of an array, I just make a generic struct that contains a reference to the array and the current index, and use that.  Feel free to steal my code:
http://blogs.msdn.com/b/ericlippert/archive/2011/03/10/references-and-pointers-part-two.aspx

A: C# is specifically designed so that you cannot store references to array elements or other 'non-root' memory locations in safe, managed code.  Having such references would significantly complicate garbage collection and this capability in C is a known potential culprit for introducing nasty bugs.  For instance, you can allocate an array on the stack in C and pass a reference to an array element.  If that reference is kept around after the stack is unwound, it now points to an arbitrary location and writing to the reference could result in data corruption.

A: You may use a structure like PointF:
PointF[] points = new PointF[3];
Console.WriteLine("X:{0}, Y:{0}", points[0].X, points[0].Y);

Or you can create your own structure:
public struct Vector
{
    public int X;
    public int Y;
}


text:
Q: Error with create CSV in server with PHP I have code to create a CSV file with SQL query data and then I send it by email.
function create_csv_string($data) {
    mysql_connect("xxxx", "xxxx", "xxxx");
    echo mysql_error();
    mysql_select_db("xxxxx");
    $data = mysql_query("SELECT NOMBRE, TELEFONO, HORARIO, EMAIL FROM _LEADS WHERE ENVIADO = 0");
    echo mysql_error();
    if (!$fp = fopen('php://temp', 'w+')) {
        return FALSE;
    } else {
        echo "entra";
    }
    fputcsv($fp, array('Nombre', 'Telefono', 'Horario', 'Email'));
    while ($line = mysql_fetch_assoc($data)) fputcsv($fp, $line);
    rewind($fp);
    return stream_get_contents($fp);
}

My problem is that I executing this in local and it works, but I upload it to a server and it doesn't work. I think that the problem is in !$fp = fopen('php://temp', 'w+')) but I am not sure.

A: You need to do something like this:
<?php
    function create_csv_string() {
        echo "entssssra?";
        $connection = mysqli_connect("**","**","**","**") or die("Cannot Connect to MySQL Server");
        $data = mysqli_query($connection, "SELECT NOMBRE, TELEFONO, HORARIO, EMAIL FROM _LEADS WHERE ENVIADO = 0");
        // Build the CSV:
        $csv = "'Nombre', 'Telefono', 'Horario', 'Email'" . PHP_EOL;
        while (false != ($line = mysqli_fetch_assoc($data)))
            $csv .= array_values($line);
        echo $csv;
        return file_put_contents('temp.csv', $csv);
    }

And you don't need the $data as a parameter.


text:
Q: Esper: Using start/end-timestamps with POJOs or runtime defined event types I am trying to use the time interval algebra methods on event types directly, which, according to the docs, should be possible. I first tried to define some event types using the create schema syntax, like this:
create schema BaseEvent as (time long, name String) starttimestamp time
create schema ExtendedEvent as (moreInfo String) inherits BaseEvent

If I write a query like this
select *
    from BaseEvent.std:lastevent() as a, ExtendedEvent.std:lastevent() as b
    where a.after(b)

it actually compiles without error. But if I try to use a pattern instead of a join, like this
select *
    from pattern [ every (a = BaseEvent and b = ExtendedEvent) ]
    where a.after(b)

it gives me an error:
Date-time enumeration method 'after' requires either a Calendar,
Date or long value as input or events of an event type that
declares a timestamp property

I get the same error when I try to use POJOs that are derived from a base event type which has the timestamp properties defined as described in the documentation. While it works when I actually use the base type, it seems strange that Esper does not use the inherited time property in this case, when it does use information about inheritance it in every other case.
Am I doing something wrong? Is this a bug? Or maybe it just works as intended...

A: It actually was kind of a bug or a 'missing' feature:
There are actually two issues I got confused here. The first is that inheritance in Esper does not work that way, i.e. derived types do not automatically inherit timestamp properties. The other problem is, that the events resulting from a pattern are so called fragments, which are not supported by the date-time methods.
The good thing is, with the upcoming version of Esper, 4.6.0, both 'issues' will be fixed: ESPER-659 and ESPER-660.


text:
Q: Unable to stop TOSHIBA TransMemory I have a USB,when I choose safety remove, occur this error message.How to solve the problem?
Unable to stop TOSHIBA TransMemory
Error detaching: helper exited with exit code 1: Detaching device /dev/sdb
USB device: /sys/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.2)
SYNCHRONIZE CACHE: synchronize cache(10):  Fixed format, current;  Sense key: Key=9
 Additional sense: Logical unit not ready, cause not reportable
  Info fld=0x0 [0]
FAILED: No such file or directory
(Continuing despite SYNCHRONIZE CACHE failure.)
STOP UNIT: start stop unit: transport: Host_status=0x07 [DID_ERROR]
Driver_status=0x00 [DRIVER_OK, SUGGEST_OK]

FAILED: No such file or directory

A: Maybe you could try manually unmounting the usb drive from the terminal.
Identify
First you will need to know the mount point or the device. You have a few options but in your case I think the first will tell you what you need to know.
1.To see information about currently mounted systems, simply run:
mount

2.To see a list of your USB devices (the vendor and device ID's), run:
lsusb

3.To see all attached storage devices and their partitions, run:
sudo fdisk -l

Unmounting
Unmounting is done through the "umount" command, which can be given a device or a mount point
sudo umount /dev/sdb1

or:
sudo umount /media/external

Would both unmount the filesystem on /dev/sdb1 if it is mounted on /media/external.
Remember that a filesystem cannot be in use when it is unmounted, otherwise umount will give an error. If you know it is safe to unmount a filesystem you can use:
sudo umount -l /mountpoint

To do a "lazy" unmount
Reference Links
https://help.ubuntu.com/community/Mount/
https://help.ubuntu.com/community/Mount/USB


text:
Q: Using document ID (__name__) to query with Where < > operators I am inserting documents into a collection with Firebase using monotonically increasing alphabetically sortable IDs (that are RFC3339-formatted dates). This helps me query the oldest documents and remove them when I reach a certain number.
So my doc IDs look like these strings:

*

*"2021-05-21T18:00:00Z"

*"2021-05-21T21:00:00Z"

*"2021-05-21T22:00:00Z"

I am using cloud.google.com/go/firestore Go library to retrieve docs with IDs less than (<) a particular value (then I plan on deleting these docs in a batch operation, e.g. delete docs older than 30 days).
However, the Go package for this returns no results for my query (at least on the Firebase Emulator):
    iter := u.DB.Collection("users").Doc(uid).Collection("orders").
        Where(firestore.DocumentID, "<", "2020-04-23T02:00:00Z").Documents(ctx)

    // iter comes back empty.

I cannot tell if it is a limitation of the product (e.g. __name__ does not support querying with < or >) or if it is a shortcoming/unimplemented behavior of the Firebase Emulator.
This question probably should be about why this doesn't work ––but if anyone has suggestions around keeping max N records in a collection in a rotating fashion (like a FIFO queue with a cap) I am interested in hearing as this is why I am trying to use this query.

A: Other factor: __name__ does not do what you THINK it does. see  Firestore collection group query on documentId .  It actually is the FULL PATH INCLUDING THE documentId, and has to be matched as such.
BTW, using such ordered documentID's is HIGHLY HIGHLY HIGHLY discouraged - it WILL impact database performance.  You will run into contention and collision on both reads and writes.  Put these values into a field in the documents, and just use random Id's (such as created by .doc()) as the document Id's.  That way you can search, sort, limit and anything else you want on the data.  There is virtually NEVER a good reason to use ordered, regular Id's for documents.

A: To achieve this in a scalable format, you should maintain an indexable field inside each document that is its document ID, which appears to be a timestamp. from there, you can easily query and sort based on your needs.
This is because scraping the firestore collection to find by ID impacts read performance on Firestore, leading to long waiting times that enhance with each document added, it's much more ideal and scalable to use the index.
As for the comments about Collection Group Queries: If you are limiting your query to only 1 specific user's "orders" collection, you do not need a collection group query as this searches amongst ALL collections called "orders".


text:
Q: How to rewrite url in php I have a redirect code this one:
 header("Refresh: 5; url={$_GET['url']}");
 echo 'You are redirecting to ... page';

It works when I add any external URL at the end like this:
http://my-domain.com/URL.php?url=

This just redirects to an external domain, in this case, let's use Google as the external URL:
http://my-domain.com/URL.php?url=http//www.google.com

It just redirects directly on the page after 5 seconds but I want to change the URL format to something like these:
http://my-domain.com/URL.php?http//www.google.com
http://my-domain.com/?http//www.google.com

A: You can use parse_url like so:
$url = "http//my-domain.com/?http//www.google.com";
$query = parse_url($url, PHP_URL_QUERY);
echo $query; // outputs "http://www.google.com"


text:
Q: How to convert output string to Json and check field item in python? I'm a beginner at Python. I received a message from the Azure service bus like the below screenshot and below code.

The code for receiving messages from the Service bus is:
import logging
import json

import azure.functions as func

def main(message: func.ServiceBusMessage):

    message_content_type = message.content_type
    message_body = message.get_body().decode("utf-8")
    logging.info(message_body)
    message = "MSG Received"
    logging.info(message)

Now, I want to convert message_body from string to JSON and after that, I check the below condition:
If error = null and MSG_TYPE_TAG != Null

How can I run this scenario?

A: Convert string to JSON
message_body = json.loads(message_body)

Now, check the condition
if message_body['error'] == {} and message_body['MSG_TYPE_TAG'] != '':
    # write your logic here

Code
import json

message_body = json.loads(message_body)

if message_body['error'] == {} and message_body['MSG_TYPE_TAG'] != '':
    # write your logic here


text:
Q: webapi odata update savechanges issue - Unable to connect to remote server In my mvc webapplication, I am using webapi to connect to my database through odata.
Both MVC WebApp and Odata WebApi are on different ports of Azure cloud service webrole endpoints.
MVC WebApp - 80
Odata WebApi - 23900

When I do a odataproxy updateobject and call savechanges like
odataProxy.UpdateObject(xxx);
odataProxy.SaveChanges(System.Data.Services.Client.SaveChangesOptions.PatchOnUpdate);

I am getting a weird exception on savechanges method call - unable to connect to remote server.
When I tried to look into inner exceptions, It says that - No connection could be made as the target machine actively refused it  127.0.0.1:23901
So if you observe the port number in the exception, it shows as 23901 and obviously this error should come as the request is supposed to hit 23900.
I am facing this exception only when running on azure cloud solution. Whenever I do an update request, it fails by hitting a wrong port (added by 1).
Another thing is, apart from this updateobject -> savechanges, rest all works like fetching data and adding data.

A: FWIW, I've just run across this same thing. Darn near annoying and I really hope it doesn't happen in production. I'm surprised no other people have come across this though.
The idea of creating a new context, attaching the object(s) and calling SaveChanges really repulsed me because not only does it practically break all forms of testing, it causes debug code and production code to be fundamentally different.
I was however able to work around this problem in another way, by intercepting the request just before it goes out and using reflection to poke at some private fields in memory to "fix" the port number.
UPDATE: It's actually easier than this. We can intercept the request generation process with the BuildingRequest event. It goes something like this:
var context = new Context(baseUri);

context.BuildingRequest += (o, e) =>
{
    FixPort(e);
};

Then the FixPort method just needs to test the port number and build a new Uri, attaching it back to the event args.
[Conditional("DEBUG")]
private static void FixPort(BuildingRequestEventArgs eventArgs)
{
    int localPort = int.Parse(LOCAL_PORT);

    if (eventArgs.RequestUri.Port != localPort)
    {
        var builder = new UriBuilder(eventArgs.RequestUri);
        builder.Port = localPort;

        eventArgs.RequestUri = builder.Uri;
    }
}

Here's the original method using reflection and SendingRequest2, in case anyone is still interested.
First we create a context and attach a handler to the SendingRequest2 event:
var context = new Context(baseUri);

context.SendingRequest2 += (o, e) =>
{
    FixPort(e.RequestMessage);
};

The FixPort method then handles rewriting the URL of the internal request, where LOCAL_PORT is the port you expect, in your case 23900:
[Conditional("DEBUG")]
private static void FixPort(IODataRequestMessage requestMessage)
{
    var httpWebRequestMessage = requestMessage as HttpWebRequestMessage;
    if (httpWebRequestMessage == null) return;

    int localPort = int.Parse(LOCAL_PORT);

    if (httpWebRequestMessage.HttpWebRequest.RequestUri.Port != localPort)
    {
        var builder = new UriBuilder(requestMessage.Url);
        builder.Port = localPort;

        var uriField = typeof (HttpWebRequest).GetField("_Uri",
            BindingFlags.Instance | BindingFlags.NonPublic);
        uriField.SetValue(httpWebRequestMessage.HttpWebRequest, builder.Uri);
    }
}

A: I have found the root cause and a temporary workaround.
Cause:
When you hit WebApi through some port :23900 in Azure compute emulator and do an update or delete operation, somehow the last request is blocking the port and because of the port walking feature in Azure emulator, it is jumping to next port where there is no service available which is causing the issue.
Even this issue is found only in development emulators.
Temp Workaround:
Use a different proxy to attach to updated context object and then save from the other proxy object.
var odataProxy1 = xxx;
var obj = odataProxy1.xyz.FirstOrDefault();
obj.property1="abcd";
...//Other update assignments

var odataProxy2 = xxx;
odataProxy2.AttachTo("objEntitySet",obj);
odataProxy2.UpdateObject(obj)
odataProxy2.SaveChanges(ReplaceOrUpdate);


text:
Q: Python selenium how to confirm the javascript message to open whatsapp Web I'm making WhatsApp automation script to send a message. When I run the script it asks the javascript confirm to open WhatsApp web.
How I can do that.?
My code :
from selenium import webdriver
import pandas as pd
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import os
import mysql.connector

driver = webdriver.Chrome('/Users/evilslab/Downloads/chromedriver 3')

driver.get('https://api.whatsapp.com/send?phone=0097155000XXXX)

# Click the link to activate the alert
driver.find_element(By.LINK_TEXT, "https://api.whatsapp.com wants to open this application.").click()

# Store the alert in a variable for reuse
alert = driver.switch_to.alert

# Store the alert text in a variable
text = alert.text

# Press the Cancel button
alert.dismiss()

This not confirming that


text:
Q: C# WPF cef Access Violation on changing the text of my textbox I hope you can help me. I try to code a litle browser using cef.
The problem is, I get a access violation while changing the Text of a TextBox at public void browser_FrameLoadEnd
public partial class Internet : Page
{
    string Url;

    public Internet()
    {
        InitializeComponent();
    }

    private void surf_Click(object sender, RoutedEventArgs e)
    {
        browser.Load(uri.Text);
    }

    public void browser_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e)
    {
        uri.Text = Url;
    }

    private void browser_FrameLoadStart(object sender, CefSharp.FrameLoadStartEventArgs e)
    {
        this.Url = e.Url;
    }
}

please help me. Why it will not work ?

A: I guess that the event arrives in a different thread. Hence you have to call the Invoke method of the TextBox, e.g.
uri.Invoke((MethodInvoker)(() => uri.Text = Url));


text:
Q: Eclipse not calling sub-makefiles correctly I am trying to refactor a single makefile project to hierarchical structure. The project is imported in Eclipse as "External C/C++ project with makefile".
The new folder with the separate makefile contains source files and a makefile with the following recipe:
.PHONY: test
test:
    echo "test"

The top directory contains a the top-level makefile with the following recipe:
clean:
    @ echo ...cleaning
    cd CppAudioPeriphs && make test
    rm -f $(OBJECTS) $(NAME).lst $(NAME).elf $(NAME).bin $(NAME).s19 $(NAME).map $(NAME).dmp

When I call from Eclipse Clean project, the last line from the last recipie clearly completes correctly. However, the line, asking to go to the sub-directory and execute make clean returns with the following message:
make[1]: `build/PeriphPhysical.o' is up to date.

This is the first object file declared, and the message is the same even if recipe test does not exist.
On the other hand, from the command line, everything works. Id est open cmd.exe, go to project folder, type make clean - > the "echo test" command gets executed.
I am using gcc and binutils, compiled for Windows, for cross-compilation for arm. Where could be my problem.

EDIT: response to jimmy
These may be additional clues.
1) If I replace
    cd CppAudioPeriphs && "make test"

with
    cd CppAudioPeriphs && C:\arm_tools\tools\bin\make.exe test

, the result is:
/usr/bin/sh: C:arm_toolstoolsbinmake.exe: command not found

If I change the slashes to forward slashes, the old message of ``build/PeriphPhysical.o' is up to date.` pops back in.

A: Replaced
cd CppAudioPeriphs && C:\arm_tools\tools\bin\make.exe test

with
make -C CppAudioPeriphs test

as a workaround and now everything compiles.


text:
Q: ClickOnce Published WPF Application starts but fail to open a specific window I am trying ClickOnce publishing service. I simply publish my solution to a share folder in online only mode, run the web page and my application starts.
I cick a button that open a window fine, another one, fine too and then a third one and the window don't show up.
What I know:
It's not a missing DLL, there is no exception (exception logger) and it's working fine in Release/Debug
Do you have any hint/idea why this and how to hunt for the problem ?

A: You can add the file to your project and set the build action to "content" and "copy to output directory" to "copy always". Then, because it's an XML file, go into the Application Files dialog in the Publish tab and change the file from "Include(Data)" to "Include(Required)".
If you deploy it as data, it will put it in the DataDirectory instead of including it in the same folder as the main assemblies. Include(Data) is the default for XML files. (Annoying, isn't it?)

A: I use a file-based trace tool. I found out that there was a problem with an XML file. I found a blog post on MSDN that talks about that. I appear that the build action and the publish action ain't the same.
So the problem of the window was that it needed that XML file but didn't find it. It threw an exception but the exception logger didn't catch it because it was on another thread. (I then learned to foward exception to the main thread).
Finally, it seems you can't publish a file when it's from a DLL. It must be embedded to the DLL or moved to the main UI project (the published project).


text:
Q: jQuery Mobile - listview() with data-filter="true" and ajax content This is my html:

My JS loads the ul with data and then I call listview().
$('#page').live('pagebeforecreate', function(){
        // My Ajax code
    });
    $('#page').live("pageinit", function(){
        $('#page ul').listview();
    });

That works except the search bar at the top doesn't appear.  What am I missing?

A: You have
data-role="list-view"

When the right way is
data-role="listview"

that is why the search bar at the top doesn't appear.

A: Instead of calling $('#page').live("pageinit", function(){
            $('#page ul').listview();
        });
Do the following:
  $('#page').live("pageinit", function(){
    init();
    });

function init()
{
    type: "GET",
   $.ajax({
     url: "BirthdayInvitations.xml",
    dataType: "xml",
    success: function ParseXml(xml)
    {
         $(xml).find("event").each(function() {
     $("#mylist").append('
' +this.textContent + '
');
     });
     $("#mylist").listview('refresh');
     }});

   }

This is working i tried it out and i am using in my application.

A: I think you need to use $('#page ul').listview('refresh'); instead of just $('#page ul').listview();. You need to refresh a jQuery-Mobile component when you update it via Ajax.

A: You'd have to call:
$('#page ul').listview('create');

after you are done populating your list with jscript.
To refresh it's content (only after it's creation), you could call:
$('#page ul').listview('refresh');

see jqm documentation


text:
Q: value registerAsTable is not a member of org.apache.spark.sql.DataFrame i am running below code in Zeppelin 0.7
%spark
//val sc: SparkContext // An existing SparkContext.
sc
import sqlContext.implicits._
import org.apache.spark.sql._
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.SQLContext;
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
val people = sqlContext.jsonFile("/Users/asdf/Desktop/people.json")
people.printSchema()
people.show()
people.select("name").show()
people.toDF().registerAsTable("people")

Its working till people.select("name").show() but throws error at last line, below is the error:
 +-------+
 |   name|
 +-------+
 |Michael|
 |   Andy|
 | Justin|
 +-------+

<console>:230: error: value registerAsTable is not a member of org.apache.spark.sql.DataFrame
          people.toDF().registerAsTable("people")

asper my knowledge i imported all required and converted it to df before registering it as table. what am i missing here?

A: Add following two lines after line "people.select("name").show()"
people.toDF().createOrReplaceTempView("people")
sqlContext.sql("SELECT * from people").show()

Though spark version is displayed in spark-shell during startup you can check the version using below command.
sc.version

A: Below code worked for me, the issue was with Zeppelin that we should not create a SQLContext Zeppelin provides its own.
%spark
import sqlContext.implicits._
import org.apache.spark.sql._
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.SQLContext;

val people = sqlContext.jsonFile("/Users/asdf/Desktop/people.json")
people.printSchema()
people.show()
people.select("name").show()
people.toDF().registerTempTable("people")

Then above created Temp table can be used to Query for interactive charts in %sql notebook of Zeppelin


text:
Q: PHP - array limit $class = array('c1', 'c2', 'c3', 'c4');

$people['c1'] = 'A';
$people['c2'] = 'B';
$people['c3'] = 'C';
$people['c4'] = 'D';

foreach ($class as $key)
{
  echo "Name: ".$people[$key]."\n";
}

result :

A
B
C
D

now when i add new 50 values to $class and $people
in some host everthing fine, but with hostpapa.com
looping only run well 36 time.
from 36+ , some values are null ( $people[$key] = null )
I don't know why. Maybe a settings limit the array ?
Note: Suhosin is instlled on this host

A: My guess would be that the hosting company may be running the "security hardened" version of PHP known as Suhoshin.
Suhoshin implements a large number of security hardening features for PHP, including the ability to limit stuff like field lengths and array sizes -- see http://www.hardened-php.net/suhosin/configuration.html
It may be that something in your code is triggering one of Suhoshin's filters.
Either way, this sounds like something you need to discuss with your hosting company.

A: $class = array('c1', 'c2', 'c3', 'c4');

$people[c1] = 'A';
$people[c2] = 'B';
$people[c3] = 'C';
$people[c4] = 'D';

foreach ($class as $key)
{
  if(key() > 36) {
    break;
  }
  echo "Name: ".$people[$key]."\n";

I hadn't test this, but it's must work.
    }

A: Depending on what you do in for foreach statement it can be due to a limitation in execution time limit of you script.
If you do relatively timeconsuming stuff per loop in the foreach this could easily add up to minutes and this can run into the execution time limit in the php.ini.


text:
Q: Why do I need to eject an ipod before disconnecting it? Is there any good reason that I need to wait for iTunes to give me permission to remove an iPod from my computer?

A: Yes.  It's possible not all the writes to the device have completed.  It's possible you may leave the filesystem in an inconsistent state, corrupting it.


text:
Q: WiFi card not compatible with router? I've got a new ADB EA4201N-G router that is used by the way also for cable TV. All PC are connected to this router via WiFi without problems except one - Asus EE PC Flare series.
I have installed two OS on this laptop - Ubuntu Linux and Windows 8. Both of these systems can't connect to acces point.
Linux writes messages Authentication and then `Obtaining IP ...'and then it not connects to WiFi.
If I run Windows on this PC it just not connects to access point. This netbook connects to others access points without problems. How to solve this problem?


text:
Q: MySQL Select all distinct ID where all rows match the where close My data table structure (I will keep it as simple as possible) :
ID      col1    col2
1       1       1
1       0       1
1       1       1
2       1       1
2       0       1
3       1       1
3       1       1

I need to have every ID where all entries of that given ID, col1 = 1 and col2 = 1.
So in this case, only the ID 3 should be given, because all of it's entries that have col1=1 also have col2=1.
I've tried numbers of joins, tried to use something like selecting the min(col2) where col1=1 joining the same table on itself on a.ID = b.ID.

A: select id
from your_table
group by id
having sum(col1 = 0) = 0
and sum(col2 = 0) = 0

A: Another way:
SELECT id
FROM table1
GROUP BY id
HAVING SUM(col1) = COUNT(id)
  AND SUM(col2) = COUNT(id)


text:
Q: All sequences constructed by using the denominator as nominator and the sum of denominator and nominator as denominator converges to $\phi-1$ Assume we are given any number a. Write it in the form $a = \frac{b}{c}$ (if rational, in the usual way, if irrational, use forms like $\frac{a}{1}$).
Construct a sequence $\frac{b}{c},\frac{c}{b+c},\frac{b+c}{b+2 c},\frac{b+2c}{2b+3c}...$
The nth term is $\frac{F_{n-1}*b+F_n*c}{F_n*b+F_{n+1}*c}$ where $F_n$ is the nth Fibonacci number.
I have noticed that no matter what the starting point $a$ is, the sequence always converges to $\phi-1$ , ie. $\frac{(\sqrt{5}+1)}{2}-1$ or $\frac{(\sqrt{5}-1)}{2}$.
I would like to prove this. If $a=1$, then the nth term is $F_{n+1}/F_{n+2}$ and the limit is $\phi-1$. But If $a \not= 1$ this seems harder to show. Especially if $a < 0$.

A: Given $\displaystyle\frac{F_{n+1}}{F_n}\to\varphi$ and $\displaystyle\frac{F_{n-1}}{F_n}\to\varphi^{-1}$, your sequence converges as
$$\frac{1/F_n}{1/F_n}\cdot\frac{F_{n-1}b+F_nc}{F_nb+F_{n+1}c}=\frac{b\displaystyle\frac{F_{n-1}}{F_n}+c}{\displaystyle b+c\frac{F_{n+1}}{F_n}}\longrightarrow \frac{b\varphi^{-1}+c}{b+c\varphi}=\varphi^{-1}\frac{b+c\varphi}{b+c\varphi}=\varphi^{-1}.$$
Note that $\varphi^{-1}=\varphi-1$.


text:
Q: Google Sheets allow access to a webapp I have a very specific situation, I'm building a service (addon) with google app scripts and there is a functionality I want to try but I've been struggling with the documentation.
I'll build and deploy a webapp, that will be accessible by anyone, a simple form.  And I want this form to write a row on a google sheet, the deal is that I won't know the sheets ID, I'm building an add-on that will allow any sheet to be accesible to the webapp and recive the post or get variables and use them.
Any ideas?

A: Thank you Sandy I kinda had the same idea;
First I build an add-on that would allow the sheet to be written by the webApp and would provide a GET variable with the sheets ID.
function useWebApp() {
   var sheetID = SpreadsheetApp.getActiveSpreadsheet().getId();
   var openFile = DriveApp.getFileById(sheetID)
   openFile.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.EDIT);
   SpreadsheetApp.getUi().alert("https://  [WEBAPPLINK]  /exec?sheet="+sheetID );
 }

Second, as suggested, I build the WebApp and used the provided HTTP GET variable to write on the sheet.
function doGet(e) {
  var app = UiApp.createApplication();
  var targetSheet = e.parameter.sheet;
  var label = app.createLabel('Parameter value sheet:'+e.parameter.sheet;
  app.add(label);

  //insertSheetLine(e.parameter.sheet);    //test to insert rows directly

 PropertiesService.getScriptProperties().setProperty('targetSheet', e.parameter.sheet);  //define a global variable in the script
  return HtmlService.createHtmlOutputFromFile('index')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

This way one can avoid the OAuth deal as long as the webapp is published to impersonate the owner. With that in mind anyone can use it and write in the sheet w/o registration.
The main idea will be to publish an Add-On with the useWebApp method installable so it will work on any sheet.
Thanks again Sandy


text:
Q: OdataV3 implementation in Java I have implemented OdataV4 service using apache olingo. I am looking for a library that supports OdataV3 implementation. Clearly, apache olingo doesnt provide libraby for V3 yet. Also tried Odata4J but looks they have declared support for OdataV3 but it was never developed.
Even migration tool which can actually translate oDataV3 request to V4 will also work.


text:
Q: INSERT statement status in VBA using ADODB Say i have a table in Excel:
TableA:
ID,
Name,
Work,
DOB
I have an insert query like:
Insert into TableA(ID,Name,Work,DOB) values (....);

I have created the code to upload this data into SQL Server database using ADODB
The upload works fine but i am trying to have it fill the status of the upload such (Pending, Successful) next to each row. Is there any way to do it?
The ending part of my code is:
For lp = 0 To qryindex - 1 'this loop is used to get query from the array which is stored in previous loop
con.Open 'open the connection
con.Execute qryary(lp), dbfailonerror ' execute the query one by one according to index value
oldValue = Application.ActiveCell.Value
con.Close

Next lp
MsgBox "Data Updated Successfully"
ThisWorkbook.RefreshAll

I need it to update the coulmn(F) as each query in the array is successfully posted


text:
Q: Undefined index when saved to options $options = get_option('analytics');
if ( ! preg_match( '/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $options['analytics_startdate'] ) ) {
    $options['analytics_startdate'] = '2018-12-01';
}

Why this is throwing an error :

Undefined index: analytics_startdate ,

though i am specifying it.

A:
though i am specifying it.

You're not actually specifying it.  You're trying to use it in your regex and THEN you specified it.
You can't use it in your "if" criteria when if it doesn't exist.  You need to check to see if it exists first.
The following would set your value if it is not set OR if it IS set and doesn't match your regex:
$options = get_option( 'analytics' );
if ( ! isset( $options['analytics_startdate'] ) || ! preg_match( '/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $options['analytics_startdate'] ) ) {
    $options['analytics_startdate'] = '2018-12-01';
}


text:
Q: How to check all  boolean Checkboxes by checking one check box with javaScript I have </p:dataTable> of jsf which contains a main <p:selectBooleanCheckbox > in one header column.Under this column I have more <p:selectBooleanCheckbox >.I need to check the main <p:selectBooleanCheckbox > and then all the other check boxes should be checked.IfI uncheked the main one all others should be unchecked too.I have tried many examples but the did not work.I need this to be done with javaScript.
<p:dataTable value="#{userMassTransferBean.recordList}" var="record">
    <p:column>
        <f:facet name="header">
            <h:outputText value="Transfer To "/>
            <p:selectBooleanCheckbox id="mainCheckbox" />
        </f:facet>
        <p:selectBooleanCheckbox  id="subCheckbox" value="#{userMassTransferBean.selected}" />
    </p:column>
</p:dataTable>

I have used some javaScripts which found from internet but they gave me error like

setter not found for property class

So I used styleClass attribute inside the <p:selectBooleanCheckbox > tag,but then the script did not worked.Please do not mark this as duplicate and I need to do this with javaScript.

A: it seems you are using primefaces to create the table. If you want use only javascript Is better show the generated html. Hovewer I think is not a good idea to use the same value for the ID attribute, that must be unique in the html page. The error "setter not found for property class" is showed when you use the attribute Class that's not the style sheet class, for that aim is used the styleClass attribute that adds a css class to the component.


text:
Q: Weighted union rule Can someone check with me if I'm using the rule right in the last step (7)?
UPDATE:
Numbers inside the parentheses are the number of elements (weight(?)) of each set that takes part in the Union. Uppercase letters are names of sets.
As I understand this: we are using as our rank the number of elements? This is getting confusing, each one is using different terms for the same stuff.
We have Unions:

*

*U(1,2,A)

*U(3,4,B)

*U(A,B,C)

*U(5,6,D)

*U(7,8,E)

*U(D,C,F)

*U(E,F,G)

A: Step 7 (and the others) looks correct, but step 6 doesn't.
In step 6, 4 should be the root, as that's the bigger tree.

A: void combine(int x,int y)
{
    int xroot=find(x),yroot=find(y);
    if(rank[xroot]<rank[yroot])
        parent[xroot]=yroot;
    else if(rank[xroot]>rank[yroot])
    parent[yroot]=xroot;
    else
    {///rank of both is equal..
        parent[yroot]=xroot;
        rank[xroot]++;
    }
}

Using rank, you see the size of set, not sum of vertices, so step 6 is wrong.
But why the size?
Because if we make root of bigger set the root of smaller set , we need to update parents of smaller number of nodes.
For the best explanation, I would recommend CLRS (Introduction to Algorithms).
Hope it helps you!


text:
Q: Properity about Lebesgue integral with measurable and non-negative functions on measurable and bounded set. I am studying real analysis from the book which is written by Manfred Stoll and somewhere in Lebesgue integral properities(page:476) I stuck. I don't believe totally prove the property so I will be happy if you could tell me where i did wrong. Thanks in advance
Proposition:
$A \subset \mathbb{R}$ is a measurable bounded set and $f,g :A \rightarrow \mathbb{R}$ are measurable and non-negative functions. If $f \leq g$   $ \,$a.e. on the set A then
$\int_A f d \lambda \leq \int_A g d \lambda$ $\quad$ holds.
My attempt:
I have the definition about Lebesgue integrability and (proved) lemma which i used for proof are in below;

Definition : Let $A \subset \mathbb{R}$ bounded and  measurable set.
$f:A  \rightarrow \mathbb{R}$ non-negative real valued function.
Define , $f_n(x)= min\{f(x),n\}$ then,
$\int_A f d \lambda = lim_{n \rightarrow \infty} \int_A f_n d\lambda$
Lemma*: $ f: [a,b] \rightarrow \mathbb{R}$ is bounded and measurable function and $f \leq g$ a.e. on [a,b] then
$\int_{[a,b]} f d \lambda \leq \int_{[a,b]} g d \lambda$

Proof(of the proposition): Let $ f \leq g$ $\,$ a.e on the set bounded A. Then there exits $a,b \in \mathbb{R}$ such that $A \subset [a,b]$. We can define $g_{x_{A}}$ and $f_{x_{A}}$ as ;
$f_{x_{A}}=
 \begin{cases}
      f(x) & x \in A\\
      0 & x \notin A
   \end{cases}$
and
$g_{x_{A}}=
 \begin{cases}
      g(x) & x \in A\\
      0 & x \notin A
   \end{cases}$
Now we will define the function sequences
$f_n ,g_n :[a,b] \rightarrow \mathbb{R}$ as;
$f_n(x)= min\{f(x),n\}$ $\quad $ and $\quad$ $g_n(x)= min\{g(x),n\}$
So by using Lemma*, we can say that $f_n$ and $g_n$ function sequences are measurable  $ \forall n \in \mathbb{N}$ and $ f_n \leq g_n$ $\,$ a.e on [a,b] so that
$\int_{[a,b]} f_n d \lambda \leq \int_{[a,b]} g_n d \lambda$ $\iff$  $\int_A f_n d \lambda \leq \int_A g_n d \lambda$
Now take limit from both sides of inequility,
$\int_A f d \lambda = lim_{n \to \infty}\int_A f_n d \lambda \leq lim_{n \to \infty}\int_A g_n d \lambda =\int_A g d \lambda$


text:
Q: Promise Return function not called I am using Ionic2 rc4.  I am trying to using Firebase to Authenticate a user.  I have the following code that works with Firebase, however when it has saved the user to Firebase (loginGoogle()), I would expect it to call the setUpUser function below, but it doesn't get invoked.
Question
How can I get 'LoginPage.loginGoogle()' invoked after it has authenticated with Firebase.
import { FirebaseAuth, AuthProviders, AuthMethods } from 'angularfire2';

@Component({
  templateUrl: 'login.html'
})
export class LoginPage {
  jobModel: JobModel;
  personModel: PersonModel;

  constructor(private nav: NavController, public auth: FirebaseAuth, public utilityService: UtilityService, public personService: PersonService) {
  }

  setUpUser() {
    alert('setUpUser');
    console.log('LoginPage', window.localStorage.getItem('uid'));
    let promisePersonModel: Promise<PersonModel> = this.personService.getPersonByUid(window.localStorage.getItem('uid'));
    promisePersonModel.then((personModel: PersonModel) => {
      this.personModel = personModel;
      if (!this.personModel) {
        this.personModel = new PersonModel();
        this.personModel.uid = window.localStorage.getItem('uid');
        this.personModel.emailAddress = window.localStorage.getItem('email');
        this.personModel.userName = window.localStorage.getItem('displayName');
        this.personModel.avatar = window.localStorage.getItem('photoURL');
        this.utilityService.login(this.personModel);
        console.log('LoginPage. logged in', this.personModel);
        this.personService.savePerson(this.personModel).then((personModel: PersonModel) => {
          console.log('LoginPage.saved personModel', personModel);
        });
      }
    });
  }

  loginGoogle() {
    this.auth.login({
      provider: AuthProviders.Google,
      method: AuthMethods.Redirect
    }).then((Data) => {
      console.log('LoginPage.loginGoogle()', window.localStorage.getItem('uid'), Data);
      this.setUpUser();
      this.nav.setRoot(SearchJobsPage);
    }).catch((error) => {
      console.log(error);
    })
  }

}


text:
Q: Web API equivalent to Web Service [.asmx] I am new to Web API.  I have implemented some Web service methods [.asmx] using deprecated WebServices - with Attributes [WebMethod] and was able to place all my different methods in the .asmx file and was able to call them by the webmethod name in my ajax calls.
I am trying to move this to WebAPI, and i dont see that i could use different methods here in the WebAPI.
for ex., in my WebService.asmx file, i could declare :
 [WebMethod]
    public void LoadReport()
    {
        ...
    }

 [WebMethod]
    public void LoadReport2()
    {
      ...
    }

But in WebAPI, all i could utilize is the Get(), Put(), Post() and Delete().
How do i declare these 2 different methods in Web API ?

A: Use the attribute routing in web api.
for example:
[RoutePrefix("api/Data")]
    public class DataController : ApiController
    {
      [Route("LoadReport")]
        [HttpGet]
        public HttpResponseMessage LoadReport()
            {
                ...
            }

        [Route("LoadReport2")]
        [HttpGet]
        public HttpResponseMessage LoadReport2()
            {
                ...
            }

you can access these methods by calling
http://localhost:<port>/api/sample/LoadReport
http://localhost:<port>/api/sample/LoadReport2

if you use .Net 4.5.2, ensure that the Attribute Routing is enabled.
Add the below line under Register method of App_Start\WebAPiConfig.cs file:
public static void Register(HttpConfiguration config)
{
         config.MapHttpAttributeRoutes(); //enable Attribute routing

A: In WebApiConfig.cs :
public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

and in my Controller :
namespace WebAPIa.Controllers
{
   // [Route("api/[controller]")]
    public class DataController : ApiController
    {
        [ActionName("LoadReport")]
        [HttpGet]
        public HttpResponseMessage LoadReport()
        {

           return Request.CreateResponse("Testing LoadReport");
        }

        [ActionName("LoadReport2")]
        [HttpGet]
        public HttpResponseMessage LoadReport2()
        {
            return Request.CreateResponse("Testing LoadReport2");
        }
    }
}


text:
Q: Code without sharing information If with sharing or without sharing is not specified in the following, will only the controller run with sharing? I think only apex controller and anonymous block will respect the OWD and sharing settings of the user who is running the code.

*

*Apex Controller

*Anonymous Block

*Apex Trigger

For Apex Trigger, it doesn't matter whether the with sharing or without sharing is there or not. Triggers will always execute in System Mode.
Please correct if my understanding is wrong.

A: Note from Using the with sharing or without sharing Keywords:

The with sharing keyword allows you to specify that the sharing rules for the current user be taken into account for a class. You have to explicitly set this keyword for the class because Apex code runs in system context. In system context, Apex code has access to all objects and fields— object permissions, field-level security, sharing rules aren't applied for the current user. This is to ensure that code won't fail to run because of hidden fields or objects for a user. The only exceptions to this rule are Apex code that is executed with the executeAnonymous call and Chatter in Apex. executeAnonymous always executes using the full permissions of the current user.

So in your first paragraph, you are not quite right. For a class that does not specify a sharing setting, Execute Anonymous will enforce sharing every time. If the class is called from an Apex Trigger, it will run without sharing when not specified. For a controller extension, it will inherit the active sharing setting, which from the StandardController will be with sharing. I believe that if you write a custom Controller, it will have nothing to inherit and will actually run without sharing, but I would have to check.
As for which setting to use on Apex Classes called from an Apex Trigger, the system will enforce the class sharing setting if one is specified:

The sharing setting of the class where the method is defined is applied, not of the class where the method is called. For example, if a method is defined in a class declared with with sharing is called by a class declared with without sharing, the method will execute with sharing rules enforced.

A: If "with sharing" or "without sharing" is not mentioned in the apex controller, then current sharing rules remain in effect.
For anonymous block, code runs with Full permission of the user, So, if user does not permission to specific object or field, it will fail, which may not occur to trigger.


text:
Q: system not booting My sys has following alert msgs.booting from hard disk drive. system security, user password required.typer ur password, then press enter.
bios saving settings are hidden. no f10 key working in bios... what to do? pls tell the solution....

A: It seems you need to enter a password before you can edit the BIOS settings. I recommend looking through the manual for your chipset for a default password or, if the pc isn't yours contact your admin.
If none of those options work. There is a method of removing the BIOS battery (it should look like a watch battery) for a minute or 2. Then plug it back in and try to access the BIOS again; the password requirement should be gone. But don't do this without first looking a guide for you specific chipset.

A: See the article How to Bypass or Remove a BIOS Password
It describes 3 methods:

*

*Removing the CMOS Battery

*Using the !BIOS freeware utility

*Using the manufacturer backdoor password


text:
Q: Unable to access router throug 192.168.1.1 I have a Vigor2100G that was on a box for about three years.
Now i want to use it and the router works well, i can use it as a switch for all my computers, but the problem comes when i try to access the router configuration. I do a ping on the port 192.168.1.1 and all works fine. The PC detects the router and the router gives a response to the computer.
When i try to connect to the router through firefox on Kali Linux (tried also on Windows 10 and Windows 7) the page doesn't loads and gives back an error that says that time has exceed.
Thanks for the answer, hope it cames soon.

A: Not all routers use 192.168.1.1 as their gateway address.  The ability to ping that IP doesn't necessarily indicate that it is the router that you are pinging, only that something is using that IP and responding.  Additionally, most routers will not allow you to connect to their interface via wireless (by default, at least), so make sure you are connected with a network cable.
To make sure you are trying to hit the correct IP for your router, try this:

*

*Open a Command Prompt

*type in ipconfig

*Find the Ethernet adapter in question

*Find the default gateway for that adapter

*The default gateway may give you an IPv6 address (letters and numbers) as well as an IPv4 address (just numbers).  You want the one that is just numbers.

*Use that IP in your browser to try and connect.

Screenshot of ipconfig

A: The router's IP is probably correct according to http://www.draytek-mx.com/support/support_note/router/faq/basic/05.php .
Maybe a hardware reset will help by pressing the factory reset button as mentioned in the link.


text:
Q: Rails Routing and Action Logic for Searching in a Model/Database I'm building an app that roots to an index page where there is a form for a customer search by phone number. I'm having trouble figuring out the proper way to search for a customer and how to route them in a RESTFUL way.
I need to query the customer by phone number. If the phone number is found in the Customer Model (database), it should return the customer show page. If the customer is not found, i.e. the customer is not in the database, I need to redirect to a new_customer_path, where it has a full sign up form for a new customer.
The current logic I'm using is doing a 'post' #create method for the index search form to search the database for the customer by phone number. If the customer is not found, then my route goes to the new_customer_path to create a new customer (I also need to pass the phone number they type so it automatically assigns it to the new customer, they shouldn't have to retype their phone number after the search). And here's where I use the 'post' #create method again to save the new customer. So I'm not sure if thats the right way to do it.
Question #1: On the index page, with my search form, should I be using a 'get' route to search for the customer in the Customer Model? If so how would my form look like and what action would that be? I tried using #show by using form_tag but you need to have a customer id (which I'm already searching for to begin with by phone number). Wondering if thats the right logic or if there is a cleaner, simpler logic for this?
Index page:
<%= form_for(Customer.new) do |f| %>
<%= f.label :phone, "Your Phone Number:" %><br>
<%= f.text_field :phone %>
<%= f.submit "Search" %>
<% end %>

Controller:
def new
    @customer = Customer.new
  end

  def create
    if @customer = Customer.find_by(phone: customer_params[:phone])
      redirect_to @customer
    else
      @customer = Customer.new(customer_params)
      if @customer.save
        redirect_to @customer, notice: "Customer was successfully saved"
      else
        render 'new', notice: "Customer was unsuccessfully saved"
      end
    end
  end

  def show
    @customer = Customer.find(params[:id])
  end

Customer Model:
create_table :customers do |t|
      t.string :first_name
      t.string :last_name
      t.string :phone
      t.string :email
      t.string :zip_code
      t.string :birthday

      t.timestamps
   end
end

A: Let's say someone goes on index page, sees this form, enters his number and proceeds. He will instantly create new account, but he didn't mention it.
Later on, you for sure add validations for names, email, zip code, etc, at least :presence=>true
And then, with such logic, person enters his phone number (if he is not in db) and out of the blue gets errors that his name, email and other stuff should not be blank.
And this is just few possible ways of unexpected behavior.
That is not a way to go.
You should add some action to controller, for example:
def find_or_redirect
@customer = Customer.find_by(phone: params[:phone])
if @customer
redirect_to @customer
else
render :new
end
end

Pass params with form
<%= form_tag("/find_or_redirect", method: "get") do %>
 <%= text_field_tag "phone" %>
<% end %>

and you should provide route, in routes.rb
get '/find_or_redirect' => "customers#find_or_redirect"

This is approximate code.


text:
Q: Mutable Array sometimes working for images in UITableView I am getting a very strange array issue with LogoURL. Sometimes it works and sometimes it errors when trying to display the URL's in the array as an image. This is an Mutable array problem and its driving me crazy.
import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) MSTable *table;
@property (nonatomic, strong) NSMutableArray *items;

@property (weak, nonatomic) IBOutlet UITableView *MainTableView;

@end

@implementation ViewController

- (void)viewDidLoad
{

    [super viewDidLoad];
    // create the activity indicator in the main queue
    self.MainTableView.hidden = YES;

    UIActivityIndicatorView *ac = [[UIActivityIndicatorView alloc]
                                   initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:ac];
    [ac startAnimating];

    self.client = [MSClient clientWithApplicationURLString:@"https://mobile.net/" applicationKey:@""];
    self.table = [self.client tableWithName:@"notifications"];
    self.logoURL = [[NSMutableArray alloc] init];
    self.rowitems = [[NSMutableArray alloc] init];
    MSQuery *query = [self.table query];
    query.fetchLimit = 3;
    [query readWithCompletion:^(NSArray *items, NSInteger totalCount, NSError *error)
                                {

                                    self.rowitems = [items mutableCopy];
                                    //[self.MainTableView reloadData];

                                    int a;
                                    for (a = 0; a < 3; a++)
                                    {
                                        NSDictionary *apt = [self.rowitems objectAtIndex:a];
                                        NSLog(@"%@", apt[@"barID"]);
                                        NSDictionary *barIDDictionary = @{ @"myParam": apt[@"barID"]};
                                        self.client = [MSClient clientWithApplicationURLString:@"https://outnight-mobile.azure-mobile.net/" applicationKey:@"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
                                        [self.client invokeAPI:@"photos" body:barIDDictionary HTTPMethod:@"POST" parameters:nil headers:nil completion:^(id result, NSHTTPURLResponse *response, NSError *error) {

                                            if (error) {
                                                        NSLog(@"Error %@", error );
                                            }
                                            else        {
                                                NSString *string = [NSString stringWithFormat:@"%@", [result objectForKey:@"rows"]];
                                                NSString *stringWithoutbracketsend = [string stringByReplacingOccurrencesOfString:@")" withString:@""];
                                                NSString *stringWithoutbracketsfront = [stringWithoutbracketsend stringByReplacingOccurrencesOfString:@"(" withString:@""];
                                                NSString *completion = [stringWithoutbracketsfront stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                                                NSString *newStr = [completion substringFromIndex:1];
                                                NSString *finalstring = [newStr substringToIndex:newStr.length-(newStr.length>0)];
                                                [self.logoURL insertObject:finalstring atIndex:a];
                                                [self.MainTableView reloadData];

                                            }

                                            }];

                                    }

                                }];

                                self.MainTableView.hidden = NO;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [self.rowitems count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
  NSDictionary *stress = [self.rowitems objectAtIndex:indexPath.row];
  cell.textLabel.text = stress[@"content"];

    if (self.logoURL.count > indexPath.row) {
        [cell.imageView setImageWithURL:[NSURL URLWithString:self.logoURL[indexPath.row]] placeholderImage:[UIImage imageNamed:@"greybox40.png"]];
        NSLog(@"%@", self.logoURL[indexPath.row]);
    }
    else
        cell.imageView.image = nil;

    return cell;
}

@end

I need some fresh eyes on it, can anyone advice ?
thanks

A: I don't know much about MSQuery, but if the completion block can be in a separate thread, this is going to mess you up.
The tableView can call -tableView:numberOfRowsInSection: when you have some number of rows, and then call -tableView:cellForRowAtIndexPath: when there's a totally different number.
Also I don't know what MSClient is, but if it's running its completion block in a background thread you're reloading your tableView in a background thread, so that's gonna kill you, too.


text:
Q: Calling a no param javascript function with a param Does javascript not check function parameters when invoking.
This function "test" below fires even though it is being called with no parameter.
<input type="button" value="test" onclick="test()">

test = function(param){
 alert("test");
}

fiddle :
http://jsfiddle.net/Yazpj/1912/
Should an error not being thrown or does the javascript engine/parser not even check function parameters when finding what to call. Does this have any implications for overriding functions ?

A: No, JavaScript does not check parameters.
Extra parameters will be ignored.  Parameters declared but not passed will have a value of undefined.  All passed parameters (declared or otherwise) will appear in the arguments pseudo-array.
There are no implications for overriding functions because JS does not support overriding functions.
Libraries such as jQuery that have methods with multiple signatures use a single function that figures out the type of the passed parameters and then performs the required action.

A: You have to check on your own:
var test = function (param) {
    if (typeof param === 'undefined') {
        // do something...
    }
};

A: Javascript is a really flexible language and this is just one example of it. Unless you are not accessing the param it won t rise any error e.g. param.sender
As for your override question it is sort of true. Every Javascript function has a arguments variable which is the array of passed parameters. if you give name the parameter defining the function JS just give it to you according to order.
But overriding is another story the overriding is achieved by checking the arguments element sometimes just length of the array sometimes type of the individual item.
For example; when you call $("#name").val() as there is no item it just return the value if arguments has values this time jQuery user proper assignment e.g. element.value = arguments[0]


text:
Q: How do I show a new view after some delay amount of time SwiftUI So I am building a blackjack simulator game and my problem right now is making it more realistic. From when I press the "Hit Me" button I'd like a delay before my next card is uploaded. Similarily when the next player goes I'd also like a delay. So right now I have  aplayer view a hand view and a card view. The player and hand are both observables.
    var body: some View {
        HStack {
            VStack(alignment: .trailing, spacing: 0){
                ForEach(0..<self.player.hands.count, id: \.self) {
                    index in ZStack {
                        Spacer()
                        HandView.init(hand: self.player.hands[index])
                    }
                }
                Spacer().frame(height: 45)
                Text(self.player.id).bold().font(Font.system(size: 20))
                Spacer()
            }
            .padding(.all)
            if !player.isRobot{
                VStack{Button(action: {
                    self.player.requestCard()
                }, label: {
                    Text("Hit Me!")
                })
                    Button(action: {
                        self.player.handleInput(turn: turnPosibilities.stay)
                        self.player.objectWillChange.send()
                    }, label: {
                        Text("Stay")
                    })}
                    .offset(x: 10, y: 0)}
        }
    }

    @ObservedObject var hand:Hand
    var bust: some View {
        GeometryReader { geometry in
            Path { path in
                path.move(to: CGPoint.init(x: geometry.frame(in: .local).midX, y: CGFloat(geometry.frame(in: .local).midY)))
                path.addLine(to: CGPoint.init(x: geometry.frame(in: .local).minX, y: geometry.frame(in: .local).minY))
                path.addLine(to: CGPoint.init(x: geometry.frame(in: .local).minX, y: geometry.frame(in: .local).maxY))
                path.addLine(to: CGPoint.init(x: geometry.frame(in: .local).maxX, y: geometry.frame(in: .local).maxY))
                path.addLine(to: CGPoint.init(x: geometry.frame(in: .local).maxX, y: geometry.frame(in: .local).minY))
            }
            .fill(Color.red)
        }
    }

    var body: some View {
        ZStack
            {ForEach(0..<self.hand.cards.count, id: \.self){
                card in
                VStack(alignment: .leading, spacing: 2) {PlayingCardView(rank: self.hand.cards[card].rankRaw, suit: self.hand.cards[card].suit, isFaceUp: self.hand.cards[card].isFaceUp ).rotationEffect(Angle.init(degrees: Double(multiply(index: card, offset: 10))))
                    .offset(x: multiply(index: card, offset: 15), y: multiply(index: card, offset: 40))

                }
                }

        }
    }
}

        ZStack{
            if isFaceUp {
                Rectangle().frame(width: 130, height:182).foregroundColor(Color.init(#colorLiteral(red: 0.9999127984, green: 1, blue: 0.9998814464, alpha: 1))).cornerRadius(25).overlay(Image(self.suit.rawValue).resizable().aspectRatio(contentMode: .fit).padding(.all))
                Text(String(self.rank)).font(.custom("Poppins-SemiBoldItalic", size: 40)).offset(x: 29, y: -70)
                Text(String(self.rank)).font(.custom("Poppins-SemiBoldItalic", size: 40)).offset(x: 29, y: -70).rotationEffect(Angle.init(degrees: 180))
            }
            else {
                Rectangle().frame(width: 130, height:182).foregroundColor(Color.init(UIColor(red: 0.58, green: 0.65, blue: 0.65, alpha: 1.00)
                )).cornerRadius(25)
            }
        }.clipShape(RoundedRectangle(cornerRadius: 25)).overlay(RoundedRectangle(cornerRadius: 25).stroke(Color.black, lineWidth: 2))
    }

A: Here is possible approach
VStack{Button(action: {
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) { // 1 sec delay
         self.player.requestCard()
    }
}, label: {
    Text("Hit Me!")
})

A: This can be achieved in SwiftUI by defining a @State variable / flag and showing new view based on that. In the below code snippet showSecondView determines when to show the next view.
struct ContentView: View {
@State var showSecondView = false
var body: some View {
    Group {
        Text("Hello, World!")
            .font(.largeTitle)
            .foregroundColor(.primary)
        if showSecondView {
            Text("SecondView")
                .font(.title)
                .foregroundColor(.secondary)
        }
    }
    .onAppear() {
        Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (_) in
            withAnimation {
                self.showSecondView = true
            }
        }
    }
}


text:
Q: Difference TfsAdmin-FieldMapping and TFSFieldMapping Can anyone tell me whats the difference between those tools and the used function (shown below).To my understanding it's like that, but I don't get what's the difference:
TfsAdmin
It downloads a mapping file from the TFS Collection for Microsoft Project Server field mappings and can be found here:
%ProgramFiles(x86)%\Microsoft Visual Studio 11.0\Common7\IDE\TfsAdmin.exe ProjectServer /DownloadFieldMappings /collection:'Collection' /filePath:'filePath'
TFSFieldMapping
It downloads the mapping file from the team project for Microsoft Project Server field mappings and can be found here:
%ProgramFiles%\Common Files\Microsoft Shared\Team Foundation Server\11.0\TFSFieldMapping.exe download /collection:'Collection' /TeamProject:'TeamProject' /mappingfile:'MappingFile'
So what is the difference? Does the TFSFieldMapping provide me a subset of the fieldmappings of the collection?

A: If you have multiple Team Projects then TfsAdmin.exe will bring down all of your Mappings, bear in mind different Team Projects can be running different Templates and so could have multiple different fields.
A collection won't have any field mappings, they are controlled per Team Project / Template.
If you only have one team project in your collection, or if you only want to connect MS Project to a single Team Project, you can just use TFSFieldMapping.exe to get the mappings for that single project


text:
Q: Need Clarity on the Implementation Part of the Diamond Problem Answers for Why multiple inheritances are not possible?
If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?
Okay. Fine
Why it does not apply to Interfaces?
Because it is not implemented.
This answer is confusing to me. I have seen many articles talking about why multiple inheritances with class are not possible and they never talk about the implementation. When we ask the same question about Interfaces, they don't go with the same logic and now they are saying the code is not implemented. Why don't we go with the same logic? Its implementation is the real problem here? Please address only this part.

A: Interface is a contract that specify what method the class need to implement, so when you call this method there is only one implementation, unlike multiple inheritance where the compiler wouldn't know what method to take.
In multiple inheritance
class A
{
    public void DoSomething() {}
}

class B
{
    public void DoSomething() {}
}

class C : A, B
{
    public override void DoSomething() {} // which DoSomething() is it?
}

In multiple interfaces
interface A
{
    void DoSomething();
}

interface B
{
    void DoSomething();
}

class C : A, B {
    public void DoSomething() { }
}

DoSomething() is implemented in class C, so the contract with both interfaces is fulfilled.

A: The diamond problem arises if B and C, which each supply conflicting definitions for an inherited method, are overridden by D.  The problem would not arise if B and C inherited methods without overriding them, and D supplied overrides for the method, since D's override would affect B and C identically.
If A, B, and C are interfaces, then neither B nor C will be able to supply definitions for the methods of A.  A class which implements both interfaces may do so, but any definition it supplies for the methods of A will apply equally to those of B and C.
Another important difference between interfaces and classes is that when overriding a class member, it's possible to chain to a parent method, but when implementing an interface there's never a parent method to chain to.