Q: Проблемы с json У меня возникала проблема с обработкой json, есть ссылка:
http://arizona-recovery.react.group/desktop/ping/Arizona/ping.json

Код запроса:
    private String connect(String url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("User-Agent", "Mozilla/5.0");
    try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        String result = in.lines().collect(Collectors.joining());
        //System.out.println(result);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return url;
}

Сама ошибка:
Exception in thread "main" org.json.JSONException: JSONObject["query"] not found.
at org.json.JSONObject.get(JSONObject.java:572)
at org.json.JSONObject.getString(JSONObject.java:859)
at Controller.dataParse(Controller.java:47)
at Controller.start(Controller.java:16)
at Main.main(Main.java:6)

Для обработки использую JSONObject
Буду рад за любую помощь с вашей стороны

A: Делайте проще: заставляйте сериализатор превращать ответ сразу в объект. Я использую lombok для генерации геттеров, сеттеров и др. стандартных методов, вы можете добавить их сами,если не хотите пользоваться lombok . В качестве десериализатора возьмите гугловую библиотеку Gson. Она очень простая в использовании и очень производительная. Скачать ее можно отсюда https://mvnrepository.com/artifact/com.google.code.gson/gson
Дальше дело техники. Любой онлайн сервис с легкостью превратит в джейсон в джава-класс. Создаем эти классы, чтобы подкинуть их десериализатору. Остается только создать метод, который будет отправлять запросы и преобразовывать их в объекты уже созданных нами классов. Поскольку не очень хочется вязаться на конкретный класс, для большей универсальности используем дженерики. Теперь в нашем метод 2 параметра: урл, на который нужно отправить запрос, и целевой класс для десереализации ответа. Из метода получаем готовый объект. Разумеется, здесь создаются лишние объекты, да и рест-клиентов более, чем достаточно (чтобы не писать самому логику отправки запросов), например, тот же ретрофит. Но, поскольку вы решили сделать это именноо таким способом, оставлю как есть, это тоже работает.
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) throws IOException {
        QueryWrapper result = connect("http://arizona-recovery.react.group/desktop/ping/Arizona/ping.json",QueryWrapper.class);
        System.out.println(result);
    }

    private static <T> T connect(String url, Class<T> clazz) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            final String json = in.lines().collect(Collectors.joining());
            return new Gson().fromJson(json, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

@lombok.Data
class QueryWrapper {
    private Query[] query;
}

@lombok.Data
class Query {
    private String number;
    private String password;
    private String port;
    private String ip;
    private String name;
    private String online;
    private String maxplayers;
}


Q: How to delete published branch without creating pull request on github console Is there any way to delete the published branch without creating a pull request and merging it into the default branch on the GitHub console.
One way I know is to create a pull request and then close it, then I am able to delete that branch.
Edit :-
I could not find exisiting question on SO with below conditions -

*

*How to delete branch without raising pull request.

*How to do it on GitHub website.

Thanks.

A: Just found a solution for this.
Click on the branches tab shown below -

Delete your published banch from the list -


Q: cant able to print first 20 even and odd numbers in assemble language I am using procedures for printing even and odd numbers but it is not working
what is wrong with my code? since I am new to assembly language
This is my main funtion:
.data
S BYTE ?
.code
main proc
call ven
MOV AH,4ch
INT 21h
main endp

this is my procedure:
ven proc
MOV S,0  \\ S is a variable
L1:
JE ter
MOV AX,S
MOV bl,2
DIV bl
CMP AH,0
JE EVE
JNE ODD
EVE:
MOV AH,2
MOV DL,AL
INT 21h
jmp L1
ODD:
MOV AH,2
MOV DL,AL
INT 21h
jmp L1
ter:
RET
ven ENDP
END MAIN

is there is something with my ven procedure aur I am linking it with main with a wrong manner.

A: there are some little errors in you code, I fixed them and pointed them with arrows (◄■■■) :
.stack 100h       ;◄■■■ PROCEDURES REQUIERE STACK.
.data
S dw ?            ;◄■■■ DW, NOT BYTE, BECAUSE AX IS TYPE DW.
.code
main proc
call ven
;call outdec
MOV AH,4ch
INT 21h
main endp

ven proc
MOV S,0
L1:
INC S             ;◄■■■ S+1
CMP S,20          ;◄■■■ IF S > 20...
JA ter            ;◄■■■ ...JUMP TO TER.
MOV AX,S
MOV bl,2
DIV bl
CMP AH,0
JE EVE
JNE ODD
EVE:
MOV AH,2
MOV DL,AL         ;◄■■■ HERE YOU PRINT "AL", BUT THE NUMBER
INT 21h           ;◄■■■ TO PRINT IS "S". USE "CALL OUTDEC".
jmp L1
ODD:
MOV AH,2
MOV DL,AL         ;◄■■■ HERE YOU PRINT "AL", BUT THE NUMBER
INT 21h           ;◄■■■ TO PRINT IS "S". USE "CALL OUTDEC".
jmp L1
ter:
RET
ven ENDP
END MAIN


Q: Is it possible to modify the behavior of Finder UI elements with AppleScript? I wrote an AppleScript that scans my entire iTunes library and tags those files with their Genre (so I can easily access them in Finder by just clicking the right tag).
The next step on my list would be to "modify" the Finder behavior. What I exactly mean is that I want to be able to double click a tag in the Finder window and then all music files that are tagged should be added to a playlist and that playlist should be started.
I have no idea if that is even possible. But if it is, I would really like to get some ideas where I have to start to achieve my goal.
I already googled a bit but couldn't find anything that goes into that direction.
One of my thoughts would be a kind of 'broadcast feature' where AppleScripts may register for specific UI elements and if the user triggers something the script gets informed.
Hopefully someone has a clue and might be able to help me out!

A: This is currently not possible with AppleScript. AppleScript can't bind itself to the UI in that way.


Q: Android google maps API 2 got JSONException:org.json.JSONException: Index 0 out of range [0..0) at org.json.JSONArray.get(JSONArray.java:263) I am drawing route between 18 locations to draw the google map v2.When i start fetching routes it draws route but some times it is not drawing route and it gives JSONException :org.json.JSONException: Index 0 out of range [0..0)  at org.json.JSONArray.get(JSONArray.java:263)
and also it gives "error_message" : "You have exceeded your daily request quota for this API."
"routes" : []
"status" : "OVER_QUERY_LIMIT"
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    public String getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        Log.d("JSON_RUTA", json);
        return json;

    }
}

private String makeURL(double sourcelat, double sourcelog, double destlat,
        double destlog, String mode)
{
    StringBuilder urlString = new StringBuilder();

    if (mode == null)
        mode = "driving";

    urlString.append("http://maps.googleapis.com/maps/api/directions/json");
    urlString.append("?origin=");// from
    urlString.append(Double.toString(sourcelat));
    urlString.append(",");
    urlString.append(Double.toString(sourcelog));
    urlString.append("&destination=");// to
    urlString.append(Double.toString(destlat));
    urlString.append(",");
    urlString.append(Double.toString(destlog));
    urlString.append("&sensor=false&mode=" + mode + "&units=metric");
    return urlString.toString();
}

private List<LatLng> decodePoly(String encoded)
{

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len)
    {
        int b, shift = 0, result = 0;
        do
        {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do
        {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
}

try
    {
        // Tranform the string into a json object
        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
        encodedString = overviewPolylines.getString("points");

               List<LatLng> list = decodePoly(encodedString);
    } catch (JSONException e)
    {
        e.printStackTrace();
    }

for (int z = 0; z < list.size() - 1; z++)
{
 LatLng src = list.get(z);
 LatLng dest = list.get(z + 1);

 Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude),
 new LatLng(dest.latitude, dest.longitude)).width(4)
.color(Color.BLUE).geodesic(true));
 line.isVisible();
 }

Can any one suggest me what ll be the solutions for this?
Thanks in advance.

A: I faced the same problem before, and it was not because of Json. It was because of sending too much requests to google in a period. So I just slow down the frequency of sending post to Google, and never seen this message again.

A: what @ohyes means is that you send multiple (too much) requests to google using your API key in too short of a time (for example, over 100 in a minute - just an example).
for that you are receiving the OVER_QUERY_LIMIT and the empty JSON array
while you should consider changing the time between the requests, you should also verify that the array received in fact has any elements
try
{
    // Tranform the string into a json object
    final JSONObject json = new JSONObject(result);
    JSONArray routeArray = json.getJSONArray("routes");
    if(routeArray.size() > 0) {
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
        encodedString = overviewPolylines.getString("points");

        List<LatLng> list = decodePoly(encodedString);
    }
} catch (JSONException e)
{
    e.printStackTrace();
}

That would solve the exception being thrown, but it won't solve the fact that you are getting no result, probably because of the too much requests
EDIT:
The OVER_QUERY_LIMIT thing happens (probably) because of too fast calls to getJSONFromUrl() function. Please add the code that makes these calls so we could try and be more helpful on that.
Probably 500 ms delay is not enough (I'm assuming you're doing this on a background thread and not Sleeping the UI thread as this is a bad habbit). try increasing the delay to something very high, such as a minute (60000 ms) and see if this helps. If it does, lower that number to the lowest one that works.
And add the code please.


Q: WPF UI to Screenshots I have a WPF application which has a toolbox with items same as Visual Studio. These items can be dragged on to the gird and configured. Each item has its own configuration i.e., different textboxes, dropdowns etc. Similar to Visio user will connects items if required (two or more). We call this as a Playlist (collections of items with different configurations).
I have a requirement to present the configuration of a playlist in a report.  The customer will be using this playlist report to recreate the playlist.
All configurations are saved in XML. I am able to deserialise the XML and show it in the report but ideally the customer would like screenshots of each item in the report or some other format.
How can i achieve it? Sorry if it is a very wide question.
Thanks in advance.


Q: Unknown register name "r0" in asm I'm in the process of converting an iOS 32-bit app to a 64-bit binary. I was able to build and test the app fine on the simulator and device however when I build for distribution to the App Store I get an error:
Unknown register name "r0" in asm

The debugger points to this line:
    VFP_VECTOR_LENGTH_ZERO
                          : "=r" (result), "=r" (m2)
                          : "r" (m1), "0" (result), "1" (m2)
                          : "r0", "cc", "memory", VFP_CLOBBER_S0_S31
                          );

I saw a similar post here however i'm unsure what the solution is.
Any assistance would be much appreciated.


Q: How to copy multiple element values from XML value into a table? I have following script, and I want to fill AddOnFeatureEnum values in #rewardscusts table :
    DECLARE @AddOnFeatures AS VARCHAR(1500)

    DECLARE @AddOnFeaturesXML AS XML

   SET @AddOnFeatures =
    '<p1:Addons
xmlns:p1="http://www.alarm.com/WebServices"><p1:AddOnFeatureEnum>WeatherToPanel</p1:AddOnFeatureEnum><p1:AddOnFeatureEnum>EnterpriseNotices</p1:AddOnFeatureEnum></p1:Addons>'

SET @AddOnFeaturesXML = CAST(@AddOnFeatures AS XML)

SELECT @AddOnFeaturesXML

CREATE TABLE #rewardscusts (AddOnFeature VARCHAR(100) primary key)

-- I want to fill AddOnFeatureEnum values in #rewardscusts table please

DROP TABLE #rewardscusts

A: This is one possible way by shredding the XML on p1:AddOnFeatureEnum elements (reference nodes() method for this part), then use value() method on the shredded elements to extract the varchar(100) values :
;WITH XMLNAMESPACES('http://www.alarm.com/WebServices' as p1)
INSERT INTO #rewardscusts
SELECT enum.value('.','varchar(100)')
FROM @AddOnFeaturesXML.nodes('/p1:Addons/p1:AddOnFeatureEnum') as T(enum)

This is full working demo codes :
DECLARE @AddOnFeatures AS VARCHAR(1500)
DECLARE @AddOnFeaturesXML AS XML

SET @AddOnFeatures =
'<p1:Addons
xmlns:p1="http://www.alarm.com/WebServices"><p1:AddOnFeatureEnum>WeatherToPanel</p1:AddOnFeatureEnum><p1:AddOnFeatureEnum>EnterpriseNotices</p1:AddOnFeatureEnum></p1:Addons>'

SET @AddOnFeaturesXML = CAST(@AddOnFeatures AS XML)

DECLARE @rewardscusts TABLE(AddOnFeature VARCHAR(100) primary key)

;WITH XMLNAMESPACES('http://www.alarm.com/WebServices' as p1)
INSERT INTO @rewardscusts
SELECT x.value('.','varchar(100)')
FROM @AddOnFeaturesXML.nodes('/p1:Addons/p1:AddOnFeatureEnum') as T(x)

SELECT * FROM @rewardscusts

output :
|      AddOnFeature |
|-------------------|
| EnterpriseNotices |
|    WeatherToPanel |


Q: List emailAddress how to replace value in a particular string I have the following method
/// <summary>
    /// Replaces SemiColons with commas because SMTP client does not accept semi colons
    /// </summary>
    /// <param name="emailAddresses"></param>
    public static List<string> ReplaceSemiColon(List<string> emailAddresses) // Note only one string in the list...
    {
        foreach (string email in emailAddresses)
        {
            email.Replace(";", ",");
        }

        //emailAddresses.Select(x => x.Replace(";", ","));  // Not working either

        return emailAddresses;
    }

However the email string is not replacing the ";" with the ",".   What am I missing?

A: I think you should try setting it back to itself email = email.Replace(";", ",");

A: String.Replace method returns new string. It doesn't change existing one.

Returns a new string in which all occurrences of a specified Unicode
  character or String in the current string are replaced with another
  specified Unicode character or String.

As Habib mentioned, using foreach with the current list gets a foreach iteration variable error. It is a read-only iteration. Create a new list and then add replaced values to it instead.
Also you can use for loop for modifying existing list which keyboardP explained on his answer.
List<string> newemailAddresses = new List<string>();
foreach (string email in emailAddresses)
{
     newemailAddresses.Add(email.Replace(";", ","));
}
return newemailAddresses;

Be aware since strings are immutable types, you can't change them. Even if you think you change them, you actually create new strings object.

A: As others have already mentioned that strings are immutable (string.Replace would return a new string, it will not modify the existing one) and you can't modify the list inside a foreach loop. You can either use a for loop to modify an existing list or use LINQ to create a new list and assign it back to existing one. Like:
emailAddresses = emailAddresses.Select(r => r.Replace(";", ",")).ToList();

Remember to include using System.Linq;

A: Strings are immutable so another string is returned. Try
for(int i = 0; i < emailAddress.Count; i++)
{
   emailAddress[i] = emailAddress[i].Replace(";", ",");
}

A foreach loop would not compile here because you're trying to change the iteration variable. You'd run into this issue.

A: You should use somthing like:
var tmpList = new List();
add each modified email address to the tmplist
and when you are done, return the TmpList.
In .NET strings are inmutable, that's why your code doesnt work.


Q: how can i avoid asking username and password for facebook in my UIWebView? in my app i need a facebook like button. when user will click that button it ll like a facebook group. i used a UIWebView and used iframe in that. now i have a local html document which is loaded when user click on the webView. but when i click on the webView it asks for facebook user name and password. i also have a publish button which uses facebook api. once its loged in it doesn't ask username and password again. but webView asks always. how can i get auto login in webView?

A: This may help you http://forum.developers.facebook.net/viewtopic.php?id=37430


Q: Rails / Dalli: expire fragment from another namespace I have two apps connecting to memcached servers on different namespaces, for example's sake we'll call them "admin" and "users".
Every now and then I want to expire some fragments in the "users" namespace from the admin application.
Note: I am not caching/expiring actions as per the other several questions/answers I found here. I want to expire keys such as "abcde". I cache all sorts of things, AR results, JSON, and so on.
Already tried things like:
Rails.cache.delete("abcd")
Rails.cache.delete("users/abcd")
Rails.cache.delete("/users/abcd")

Digests are off.
How do I do this?

A: If your rails cache is configured with a namespace, that namespace will be prepended to the cache key automatically. So, when you Rails.cache.write("FOO", "BAR") the key will actually be $NAMESPACE:FOO. Keys are just strings and can't be navigated like a file system or anything fancy (AFAIK).
I think your best option is instantiate a separate instance of a dalli client for your alternative namespace to delete the key.


Q: how to get aggs count/buctuks from Flux I'm trying the Elasticsearch aggregations in spring webflux.
I what to know how to get the buckets values (inside buckets count) from  Flux<AggregationContainer<?>> in Java API and total records in elasticsearch.
Request:
order/_search
{
  "size": 0,
          "aggs": {  "status":
 { "terms":
 { "field":"order_status" , "size": 100}}}}

Response:
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    .....
  },
  "aggregations" : {
    "status" : {

      "buckets" : [
        {
          "key" : "CREATED",
          "doc_count" : 34
        },
        .....
        {
          "key" : "CANCELLED",
          "doc_count" : 2
        },
        {
          "key" : "COMPLETED",
          "doc_count" : 1
        }
      ]
    }
  }
}

Java imp:
  @Autowired
    private ReactiveElasticsearchOperations operations;
Flux<AggregationContainer<?>> result = operations.aggregate(searchQuery, Count.class, "indexs");


Q: Blocking users UID using PAM So i have to block users by their UID, users that have uid >= 500 should not be able to login. This as to be done with the file common-auth with pam_sucess_if.so . i have tried:
auth        requisite     pam_succeed_if.so uid >= 500 quiet
with no sucess.
Does anyone know how to do this?
Thanks in advance

A: The man pam_succeed_if page has flags like quiet before conditions like uid >= 500.
auth requisite pam_succeed_if.so quiet uid >= 500

NOTE: I did not test this, I just read the man page.


Q: Passing data from one screen to another screen in iPhone using phone gap I have just started to look into the phone gap.I have created one basic form which taking the data of the employee.I have table view in another screen .I want to pass the employee details to the second screen .I was googling for this purpose.I have found that there are some ways to do this like:
  1.Server side post back

  2. Client side URL examination

  3.What's in a window.name = local cross-page session

  4.HTML5 local storage

  5. Cookies

But will my phone gap application be 100% native by using these ways? Is there any alternate way or tutorial to pass the data between the screens?

A: What you actually mean by "a screen"? If you're talking about a pop-up dialog box or page by jQuery Mobile you can probably serialize the form with jQuery and assign it to a JavaSCript variable.
But if you're changing your "screen" by changing UIView to a different url you can use either:

*

*File API to store serialized form in a file and load it on the 2nd "screen"

*Storage API to ... actually do the same

I'd go for number one, as it's easier to implement than using SQL and writing loads of additional code.
Search for:

*

*jQuery.serialize()

*PhoneGap File API


Q: How to validate forms when a user changes the name of an input element in firebug? I realize it's impossible to prevent someone from changing the names of input elements in firebug.
How should I approach this problem?  A user changes the name of the input element "firstname" to "month" and visa versa.
<form action="example.php" method="post" enctype="multipart/form-data">

                First name: <input type="text" name="firstname" />

                Last name: <input type="text" name="lastname" />

            Birth Month:
                <select name="month">
                    <option value="01">January</option>
                    <option value="02">February</option>
                    <option value="03">March</option>
                    <option value="04">April</option>
                    <option value="05">May</option>
                    <option value="06">June</option>
                    <option value="07">July</option>
                    <option value="08">August</option>
                    <option value="09">September</option>
                    <option value="10">October</option>
                    <option value="11">November</option>
                    <option value="12">December</option>
                </select>

            <input type="submit" name="Submit" value="Sign Up!" />

</form>

My best idea so far is:
<?php
$month= $_POST['month'];
if($month!= 01 || $month!= 02 ... $month!= 12)
    echo 'wrong month';
?>

However this won't be clean for the year of birth... Facebook does a great job of preventing this when you sign up but I wasn't able to figure out what they did.  A non-javascript solution would be much appreciated.
EDIT: Lawrence, what do you recommend for a location form?

A: Going through each month in a condition is unneeded, php has functions for that.
<?php
$firstname= (string)$_POST['firstname'];
$lastname = (string)$_POST['lastname'];
$month    = $_POST['month'];

if(in_array($month,range(01,12))===true){
    $cont = TRUE;
}else{
    $cont = FALSE;
}
//If set, not empty, not swapped for month & greater or equals to 6 chars
if(isset($firstname) && $firstname!="" && strlen($firstname) >=6 && in_array($month,range(01,12))===false){
    $cont = TRUE;
}
//If set, not empty, not swapped for month & greater or equals to 6 chars
if(isset($lastname) && $lastname!="" && strlen($lastname) >=6 && in_array($month,range(01,12))===false){
    $cont = TRUE;
}
?>


Q: Windows OpenFileDialog with more than one file type I want to open a Windows OpenFileDialog with two possible selections:
foo*bar.xml
*.xml

The file name wildcard is specified with the FileName property but it applies to every file selection specified with the Filter property.
With the Filter property, users can select more than one set of file types, but is there a way to specify different file names in one dialog?
Paul

A:
The file name wildcard is specified with the FileName property

That doesn't work, only the Filter property can be used to filter files.  Furthermore, a wildcard like foo*bar.xml does do what you hope it does, anything past the * is ignored.  A wildcard doesn't behave like a regular expression at all.  This goes way, way back to early operating systems that didn't have the horsepower to implement regex.  Definitely at CP/M, probably as far back as RSX.
Options are very limited, you can specify multiple wildcards by separating them with a ; semicolon.  Like "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*".  But that's as far as you can push it.


Q: WSO2 Enterprise Integrator (6.5) - how to Store and retrieve Registry data using dynamic registry path I have a sequence to utilise an API which issues time-constrained bearer tokens from an authorization endpoint based on client ID and Secret. The Bearer Token remains valid for 1 hour and so I'm storing the bearer token and its expiry time in the registry whenever I renew the token and on subsequent calls will use the stored token rather than request a new one - unless it's expired.
This is all working as expected - however - it is feasible that this Sequence could be called from processes that have different client IDs - so for scalability I would like to modify the process so the Token and expiry are held under a registry branch for each client_id.
I'm unable to find a way to dynamically create the registry entries to incorporate the client_id in the registry path.
I can Read from a dynamic path successfully as follows:
<property expression="get-property('registry', fn:concat('conf:/resource/MyApplication/',$ctx:client_id,'/TokenExpiry'))" name="RegBearerExpiryStr" scope="default" type="STRING"/>
but I cannot work out how to successfully Write a registry entry in a similar fashion.
I have tried the following with no success - I can see from the wire logs that everything in the key name is being interpreted literally :
 <property expression="json-eval($.access_token)" name="fn:concat('conf:/resource/MyApplication/',$ctx:client_id,'/TokenExpiry'))" scope="registry" type="STRING"/>
and
 <property expression="json-eval($.access_token)" name="conf:/resource/MyApplication/{$ctx:client_id}/TokenExpiry" scope="registry" type="STRING"/>
I'm running EI 6.4 and 6.5
Any brilliant ideas - there must surely be a way to create a dynamic path for writing as well as reading ?

A: I personally use jsonObject XML and use OM type for storing complex types as WSO2 has better xml type support.
<property expression="//jsonObject" name="token" scope="default" type="OM"/>
<property name="conf:/storage/SampleToken.xml" scope="registry" expression="$ctx:token" type="OM"/>

But, there is one "pitfall", as WSO2 are cacheing the registry entries for default 15seconds. So you will read old values for some time. If that is a problem i use workaround. I use script mediator for better handling that, and with checking if that resource exist or not. I tested it on EI 6.5
<script language="js"><![CDATA[
 var regUrl = mc.getProperty('regUrl');
 var registry = mc.getConfiguration().getRegistry();

 if(registry.isResourceExists(regUrl) == false) {
    registry.newResource(regUrl, false);
 }
 registry.updateResource(regUrl,mc.getProperty('token'));

 var regEntry = registry.getRegistryEntry(regUrl);
 regEntry.setCachableDuration(0);
 registry.updateRegistryEntry(regEntry);]]>
</script>

I also made some blog post, may be also useful::
Reading, modifying and writing data in WSO2 Enterprise Integrator registry on an example


Q: excel how to use index and match to match the data Morning,
My fault, let me converted to English.

My concern is that I do not know how to connect table_1's category with the table_2's column and then found the correct color

A: You need to use either the VLOOKUP or HLOOKUP feature when structuring your results table.  For instance in cell C3 (color for head/set1) you would type =HLOOKUP(a2,e2:h5,2,FALSE). It will look horizontally in the first row for whatever is in cell A2 (HEAD)  and return the value from the 2nd row (RED).  Of flip it around to use HLOOKUP.
https://support.office.com/en-us/article/hlookup-function-a3034eec-b719-4ba3-bb65-e1ad662ed95f

A: Please try this formula, to be entered in row 3 where columns A and B are "category" and "Sets" respectively.
=VLOOKUP(B3,E1:H4,MATCH(A3,E1:H1,0),FALSE)
E1:H4 represents your entire table2 incl captions. You can exclude the caption row - probably better. E1:H4 is the first row of that same range. There is presumed to be only one caption row which is needed, and must be 1 only. If you prefer a neater solution take the data column captions only and adjust the result. Then your formula might look like this.
=VLOOKUP(B2,E2:H4,MATCH(A2,F1:H1,0)+1,FALSE)


Q: Squarespace Code Block Alignment Issues We have custom coded animate flipping cards on our website. There is an issue with the alignment and sizing of them. The issue only occurs when there are multiple cards on the page (they are made using code blocks). You can see the issue on the link below.
Any help would be appreciated!
LINK TO SITE
JSFIDDLE (ONLY 1 CARD...ISSUE DOESN'T SHOW UP)
HTML:

Brian Perry

CEO

CSS:
.back {
    -webkit-transform: rotateY(180deg);
    -moz-transform: rotateY(180deg);
  -o-transform: rotateY(180deg);
    transform: rotateY(180deg);

    background: #bd2d2c;
}

.flip-container {
  -webkit-perspective: 1000;
  -moz-perspective: 1000;
  -o-perspective: 1000;
  perspective: 1000;

}

.flip-container:hover .flipper,
  .flip-container.hover .flipper {
        -webkit-transform: rotateY(180deg);
        -moz-transform: rotateY(180deg);
    -o-transform: rotateY(180deg);
        transform: rotateY(180deg);
    }

.flip-container, .front-brian, .front-tony, .front-blaine, .front-alex, .front-eric, .front-sue, .front-tamara, .front-kenyon, .front-dom, .front-lt, .front-lindsey, .front-chris, .front-ethan, .back {
  width:6000px;
  min-height:100%;
  max-width:100%;
  max-height: 10000px;
   height:0;
   padding-bottom: 70%;

}

.flipper {
    -webkit-transition: 0.6s;
    -webkit-transform-style: preserve-3d;

    -moz-transition: 0.6s;
    -moz-transform-style: preserve-3d;

  -o-transition: 0.6s;
    -o-transform-style: preserve-3d;

    transition: 0.6s;
    transform-style: preserve-3d;

    position: relative;
}

.front-brian, .front-tony, .front-blaine, .front-alex, .front-eric, .front-sue, .front-tamara, .front-kenyon, .front-dom, .front-lt, .front-lindsey, .front-chris, .front-ethan, .back {
    -webkit-backface-visibility: hidden;
    -moz-backface-visibility: hidden;
  -o-backface-visibility: hidden;
    backface-visibility: hidden;

    position: absolute;
    top: 0;
    left: 100;
}

.front-brian{
    background: url(http://static1.squarespace.com/static/573e762945bf219b6da541d1/t/57a5d191e3df28ea3c3f9bfb/1470484886737/Brian+Headshots-29.jpg);

    background-size: cover;
    background-repeat: no-repeat;
    background-position: 50% 50%;
}

.back-title {
    color: #fff;
    font-size: 2em;
    position: absolute;
    top: 14%;
    left: 0%;
    right: 0%;
    text-align: center;
}

.role {
    color: #fff;
    font-size: 1.5em;
    position: absolute;
    top: 30%;
    left: 0%;
    right: 0%;
    text-align: center;
}

A: This appears to be occurring because you have nested blocks. That is, each code-block ( .code-block ) is nested within the previous one, so each image is slightly more padded than the one before.
See the attached image.
Nested Squarespace Code Blocks - Dev. Tools Screenshot
I'm not sure how this problem was created. Did you copy and paste code containing sqs-block code-block sqs-block-code elements? It appears that you did, at least at first glance.
To fix this, you're going to need to remove all of the Squarespace-specific divs that wrap each of your flip-container divs. Within the code block, all you should have is a series of flip-container divs, one after another. Like this:

etc

etc

etc

etc


Q: PHP code is rendered as text I'm using Ubuntu 16.04 and I want to run php files.
I installed Php 7 on it using:
sudo mkdir -p /var/www/html
sudo chown -R $USER:$USER /var/www/html
sudo apt install php
sudo apt install apache2

I created a php file (e.g. test.php) in /var/www/html. I can access it in the browser (e.g. http://localhost/test.php). Instead of executing the <?php ... ?> code, it is displayed as plain text:
I tried to turn short_open_tag to On. So I edited the /etc/php/7.0/fpm/php.ini and enabled it.
Then I ran sudo service php7.0-fpm restart. This didn't make any change in the browser. The php code is still displayed as plain text.
How can I fix this?

A: You didn't install apache properly, doing an apt-get on apache2 does not install everything.
what @newman stated is correct you can follow that guide, or here is a digitalocean link that is usuable for production server (since you would do this on a droplet). Note this is full stack LAMP, which I would assume you would get to eventually when you want to dab with mysql
https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-14-04


Q: How convert a Photoshop made logo into CSS properly? I am trying to convert a logo made into Photoshop in CSS.
As i am no master of both, i've tried but greatly failed by using the Photoshop build in "copy css" function.
I've tried to redo the CSS via my limited knowledge, but failed miserably.

.Group_5 {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 1920px;
  height: 1080px;
  z-index: 47;
}
.Group_4 {
  position: absolute;
  left: -2px;
  top: -2px;
  width: 1924px;
  height: 1084px;
  z-index: 46;
}
.Ellipse_3 {
  border-width: 6.25px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  border-radius: 50%;
  position: absolute;
  left: 1119px;
  top: 486px;
  width: 168.5px;
  height: 174.5px;
  z-index: 45;
}
.Ellipse_2 {
  border-width: 6.25px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  border-radius: 50%;
  position: absolute;
  left: 1122px;
  top: 505px;
  width: 139.5px;
  height: 139.5px;
  z-index: 44;
}
.Ellipse_1_copy {
  border-width: 6.25px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  border-radius: 50%;
  position: absolute;
  left: 1109px;
  top: 512px;
  width: 139.5px;
  height: 139.5px;
  z-index: 43;
}
.Ellipse_1 {
  border-width: 6.25px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  border-radius: 50%;
  position: absolute;
  left: 1091px;
  top: 492px;
  width: 176.5px;
  height: 176.5px;
  z-index: 42;
}
.Shape_26 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1358px;
  top: 409px;
  width: 10px;
  height: 7px;
  z-index: 41;
}
.Shape_25 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1347px;
  top: 409px;
  width: 18px;
  height: 17px;
  z-index: 40;
}
.Shape_24 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1394px;
  top: 409px;
  width: 11px;
  height: 7px;
  z-index: 39;
}
.Shape_23 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1385px;
  top: 408px;
  width: 21px;
  height: 20px;
  z-index: 38;
}
.Shape_22 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1386px;
  top: 430px;
  width: 20px;
  height: 20px;
  z-index: 37;
}
.Group_2 {
  position: absolute;
  left: 2px;
  top: 2px;
  width: 1920px;
  height: 1080px;
  z-index: 36;
}
.Shape_16_copy_2 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1395px;
  top: 410px;
  width: 8px;
  height: 26px;
  z-index: 35;
}
.Shape_16_copy {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1384px;
  top: 419px;
  width: 8px;
  height: 25px;
  z-index: 34;
}
.Shape_16 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1346px;
  top: 419px;
  width: 8px;
  height: 25px;
  z-index: 33;
}
.Shape_15 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1346px;
  top: 439px;
  width: 46px;
  height: 8px;
  z-index: 32;
}
.Shape_19 {
  border-width: 4.167px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  position: absolute;
  left: 1357px;
  top: 407px;
  width: 37.666px;
  height: 0;
  z-index: 31;
}
.Shape_21_copy {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1344px;
  top: 407px;
  width: 19px;
  height: 18px;
  z-index: 30;
}
.Shape_21 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1383px;
  top: 407px;
  width: 20px;
  height: 18px;
  z-index: 29;
}
.Shape_20 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1395px;
  top: 409px;
  width: 8px;
  height: 7px;
  z-index: 28;
}
.Shape_18 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1346px;
  top: 417px;
  width: 46px;
  height: 8px;
  z-index: 27;
}
.Shape_17_copy {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1381px;
  top: 408px;
  width: 20px;
  height: 19px;
  z-index: 26;
}
.Shape_17 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1384px;
  top: 428px;
  width: 19px;
  height: 19px;
  z-index: 25;
}
.Group_1 {
  position: absolute;
  left: 2px;
  top: 2px;
  width: 1920px;
  height: 1080px;
  z-index: 23;
}
.Rectangle_1 {
  border-width: 4.167px;
  border-color: rgb(0, 0, 0);
  border-style: solid;
  position: absolute;
  left: 1325px;
  top: 472px;
  width: 48.666px;
  height: 19.666px;
  z-index: 22;
}
.Shape_10 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1132px;
  top: 656px;
  width: 11px;
  height: 8px;
  z-index: 21;
}
.Shape_9 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1394px;
  top: 423px;
  width: 41px;
  height: 242px;
  z-index: 20;
}
.Shape_8 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1132px;
  top: 451px;
  width: 271px;
  height: 213px;
  z-index: 19;
}
.Shape_11 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1132px;
  top: 450px;
  width: 17px;
  height: 8px;
  z-index: 18;
}
.Shape_7 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1132px;
  top: 416px;
  width: 64px;
  height: 41px;
  z-index: 17;
}
.Shape_14 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1427px;
  top: 417px;
  width: 8px;
  height: 215px;
  z-index: 16;
}
.Shape_13 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1393px;
  top: 415px;
  width: 44px;
  height: 44px;
  z-index: 15;
}
.Shape_12 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 1144px;
  top: 416px;
  width: 302px;
  height: 42px;
  z-index: 14;
}
.Group_3 {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 1920px;
  height: 1080px;
  z-index: 11;
}
.Shape_3 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 577px;
  top: 684px;
  width: 710px;
  height: 12px;
  z-index: 10;
}
.Shape_2 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 571px;
  top: 301px;
  width: 137px;
  height: 403px;
  z-index: 9;
}
.I {
  font-size: 283.333px;
  font-family: "Kozuka Gothic Pr6N";
  color: rgb(0, 0, 0);
  line-height: 1.2;
  text-align: center;
  -moz-transform: matrix( 1,0,0,0.76592618857706,0,0);
  -webkit-transform: matrix( 1,0,0,0.76592618857706,0,0);
  -ms-transform: matrix( 1,0,0,0.76592618857706,0,0);
  position: absolute;
  left: 1043.001px;
  top: 406px;
  z-index: 7;
}
.C_copy_2 {
  font-size: 283.333px;
  font-family: "Kozuka Gothic Pro";
  color: rgb(0, 0, 0);
  line-height: 1.2;
  text-align: center;
  -moz-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  -webkit-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  -ms-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  position: absolute;
  left: 869.507px;
  top: 406.5px;
  z-index: 6;
}
.C {
  font-size: 283.333px;
  font-family: "Kozuka Gothic Pro";
  color: rgb(0, 0, 0);
  line-height: 1.2;
  text-align: center;
  -moz-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  -webkit-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  -ms-transform: matrix( 1.04227845443354,0,0,0.87676868039824,0,0);
  position: absolute;
  left: 711.507px;
  top: 406.5px;
  z-index: 5;
}
.Shape_4 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 685px;
  top: 289px;
  width: 98px;
  height: 212px;
  z-index: 4;
}
.Shape_1 {
  background-color: rgb(1, 1, 1);
  position: absolute;
  left: 693px;
  top: 309px;
  width: 89px;
  height: 191px;
  z-index: 3;
}

I might be just missplacing something, or the given CSS result is not working properly, as anything i do and/or try results into a blank page.
I am not exactly sure how i could get this logo converted, as mentioned above i am no master in both.
The logo is made of circiles/lines and the 2"C" texts.
Some of the layers have masks on them for transparency (where they overlap)
It's not the best made, as it was supposed to have the same thickness overall, but i would like a way to get into CSS form.


Q: How to pass a different argument conditionally I want to be able to change an argument to a function when a condition is met.
Currently I am doing this which works, but I am repeating the first argument, is there a way to just change the second argument?
credential = './credentials.json'

if os.path.exists(credential):
  account = authenticate(client_config=secrets, credentials=credential)
else:
  account = authenticate(client_config=secrets, serialize=credential)

A: An elegant way is to use kwargs:
credential = './credentials.json'
key = "credentials" if os.path.exists(credentials) else "serialize"
auth_kwargs = {"client_config": secrets, key: credential}

account = authenticate(**auth_kwargs)

A: I think your way is fine too, but you can do this
credential = './credentials.json'
params = {'serialize': credential}
if os.path.exists(credentials):
  params['credentials'] = params.pop('serialize')

account = authenticate(client_config=secrets, **params)

A: You can pass an (unpacked) dictionary to a function:
credential = './credentials.json'
arguments = {'client_config': secrets, 'serialize': credential}  # default

if os.path.exists(credentials):
    arguments.pop('serialize')
    arguments['credentials'] = credential

account = authenticate(**arguments)

A: There is functools.partial for this:
from functools import partial

credential = './credentials.json'

auth = partial(authenticate, client_config=secrets)

if os.path.exists(credential):
  account = auth(credentials=credential)
else:
  account = auth(serialize=credential)


Q: Pickle multiple machine learning model I have multilayer model consist of two models, kmeans and random forest classifier; that work inside single function.
My question is how to pickle both and keep them work in sequence???
Thanks in advance


Q: Can I generate numbers in series using IntegerField in Django I have created a model where Integer field is among the field in my model, when each post is added I want to have number that will be generated in series in each post. Can I achieve by just using Integer field, Please help!!!
models.py
class Documents(models.Model):
    docs_name = models.CharField(max_length=200,verbose_name="Jina la Nyaraka")

    item_type = models.CharField(default="", max_length=100,verbose_name="Aina ya nyaraka" )

    police_station = models.CharField(max_length=255, verbose_name="Kituo cha polisi")

    phone_no = models.CharField(verbose_name="Namba yako ya simu", max_length=10, blank=False,
validators=[int_list_validator(sep=''),MinLengthValidator(10),])

    date = models.DateTimeField(default=timezone.now,verbose_name="Date")

    Description = models.TextField(blank=True, null=True,verbose_name="Maelezo zaidi")

    pay_no = models.IntegerField(default=0,verbose_name="Namba ya malipo")

    publish = models.BooleanField(default=False)

    image = models.ImageField(upload_to="Documents",blank=False, verbose_name="Picha ya nyaraka")

    """docstring for Documents"""
    def __str__(self):
        return self.docs_name

views.py
@login_required
def PostNew(request):
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('loststuffapp:IndexView')
    else:
        form = PostForm()
    return render(request, 'loststuffapp/form.html', {'form': form})

A: well as far i can get it, you need to make some kind of sequence for your IntegerField.
while it's not and id field, you can emmulate it by taking max value of that field among all objects:
max_val = YourModelClass.objects.all().aggregate(Max('that_field_in_question'))
# then just make new object, and assign max+1 to 'that_field_in_question'
new_obj = YourModelClass('that_field_in_question'=max_val + 1)
new_obj.save()


Q: Using UIRefreshControl in UIViewController with UITableView I wonder how i can use UIRefreshController for a UITableView inside a UIViewController.
I want to implement pull-to-refresh functionality to TableView but i don't have a TableViewController.
Is there a way to do this in xcode 6 (swift)

A: Of course you can do this. Initiate a RefreshControl and simply put it as subview of your tableview. You don't necessarily  need a UITableViewController for this.
EDIT:
Try something like this:
let control = UIRefreshControl()
control.addTarget(self, action: "action", forControlEvents: .ValueChanged)
tableView.addSubview(control)

A: Here's the Objective-C version that worked for me in case anyone needs it. I added it to viewDidLoad:
UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
[refresh addTarget: self action: @selector(didPullToRefresh:) forControlEvents: UIControlEventValueChanged];
[self.tableView addSubview: refresh];

Not a fan of UITableViewController...


Q: Flutter paint(): is this legit? Rendering Renderobject in different context I try to render the child of a listitem (somewhere up) to a different place (widget) in the tree;
In the approach below, BlendMask is the "target" widget that checks for and paints "source" widgets that got themself an GlobalKey which is stored in blendKeys.
This works somewhat. And I'm not quite sure if I might fight the framework, or just missing some points...
The problems are two:

*

*The minor one: This approach doesn't play nice with the debugger. It compiles and runs fine but every hot-reload (on save f.e.) throws an "can't findRenderObject() of inactive element". Maybe I miss some debug flag?

*the real problem, that brought me here questioning the idea en gros: As mentioned, the Source-Widget is somewhere in the subtree of the child of a Scrollable (from a ListView.build f.e.): How can I update the Òffset for the srcChild.paint() when the list is scrolled? - without accessing the lists scrolController?! I tried listening via WidgetsBindingObservers didChangeMetrics on the state of the Source widget, but as feared no update on scroll. Maybe a strategically set RepaintBounderyis all it needs? *hope* :D
Anyway, every tip much appreciated. Btw the is an extend of this question which itself extends this...
class BlendMask extends SingleChildRenderObjectWidget {
  [...]
  @override
  RenderObject createRenderObject(context) {
    return RenderBlendMask();
  }
}

class RenderBlendMask extends RenderProxyBox {
[...]
@override
void paint(PaintingContext context, offset) {    <-- the target where we want to render a widget
  [...]                                              from somewhere else in the tree!
  for (GlobalKey key in blendKeys) {
    if (key.currentContext != null) {
      RenderObject? srcChild                     <-- the source we want to render in this sibling widget!
       = key.currentContext!.findRenderObject();
      if (srcChild != null) {
        Matrix4 mOffset = srcChild.getTransformTo(null);
        context.pushTransform(true, offset, mOffset, (context, offset) {
          srcChild.paint(context, offset);
        });
      }
    }
  }
}
} //RenderBlendMask


Q: Difficulty screen scraping http://www.momondo.com using nokogiri I have some difficulty to extract the total price (css selector = '.total') from the flight result.
http://www.momondo.com/multicity/?Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false

I get the error "undefined method `text' for nil:NilClass nokogiri ".
My code
desc "Fetch product prices"
task :fetch_details => :environment do
  require 'nokogiri'
  require 'open-uri'
  include ERB::Util

  OneWayFlight.find_all_by_money(nil).each do |flight|
    url = "http://www.momondo.com/multicity/Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false"
    doc = Nokogiri::HTML(open(url))
    price = doc.at_css(".total").text[/[0-9\.]+/]
    flight.update_attribute(:price, price)
  end
end

A: The content you're attempting to scrape appears to be populated by JS after the page loads. To see for yourself, inspect the content of div#flight_results of the document you're currently parsing:
url = 'http://www.momondo.com/multicity/?Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false'

doc = Nokogiri::HTML(open(url))
doc.at_css('div#flight_results').to_html #=> '

'

Though it is outside of the scope of this question, you can generally reconstruct the JS requests used to populate the content you're after.


Q: C++ Function pointers vs Switch
*

*What is faster: Function pointers or switch?

The switch statement would have around 30 cases, consisting of enumarated unsigned ints from 0 to 30.
I could do the following:
class myType
{
    FunctionEnum func;
    string argv[123];
    int someOtherValue;
};
// In another file:
myType current;
// Iterate through a vector containing lots of myTypes
 // ... for ( i=0; i < myVecSize; i ++ )
    switch ( current.func )
    {
           case 1:
            //...
            break;
           // ........
           case 30:
             // blah
            break;
    }

And go trough the switch with func every time. The good thing about switch would also be that my code is more organized than with 30 functions.
Or I could do that (not so sure with that):
class myType
{
    myReturnType (*func)(int all, int of, int my, int args );
    string argv[123];
    int someOtherValue;
};

I'd have 30 different functions then, at the beginning a pointer to one of them is assigned to myType.

*

*What is probably faster: Switch statement or function pointer?

Calls per second: Around 10 million.
I can't just test it out - that would require me to rewrite the whole thing. Currently using switch.
I'm building an interpreter which I want to be faster than Python & Ruby - every clock cycle matters!

A: I think the difference is negligible in most cases - your case might be an exception. Why don't you put together a simple prototype app to explicitly measure the performance of each solution? My guess is that it would not take more than an hour of work...
However, think about clarity and maintainability of the code as well. IMHO it is obvious that the function pointer solution wins hands down in this respect.
Update: Note also that even if one solution is, let's say, twice as fast as the other as it is, it still may not necessarily justify rewriting your code. You should profile your app first of all to determine how much of the execution time is actually spent in those switches. If it is 50% of total time, there is a reason to optimize it. If it is a couple of percents only, optimizing it would be a waste of effort.

A: Péter Török has the right idea about trying both and timing them.  You may not like it, but unfortunately this is the reality of the situation.  The "premature optimization" chant happens for a reason.
I'm always in favour of using performance best-practices right from the start as long as it doesn't sacrifice clarity.  But in this kind of case it's not a clear win for either of the options you mentioned.  In most cases, this kind of minor change will have no measurable effect.  There will be a few major bottlenecks that completely govern the speed of the whole system.  On modern computers a few instructions here and there will be basically invisible because the system is blocked by memory cache misses or by pipeline stalls and those can be hard to predict.  For instance in your case, a single extra cache miss would likely decide which method would be slower.
The real-world solution is to evaluate the performance of the whole system with a profiler.  That will show you where your "hot spots" are in the code.  The usual next step is to make algorithmic changes to reduce the need for that many calls into the hot code either through better algorithms or through caching.  Only if a very tiny section of code is lighting up the profiler is it worth getting down to small micro-optimizations like this.  At that point, you have to try different things and test the effect on speed.  Without measuring the effect of the changes, you're just as likely to make it worse, even for an expert.
All that being said, I would guess that function calls in your case might be very slightly faster if they have very few parameters, especially if the body of each case would be large.  If the switch statement doesn't use a jump table, that likely be slower.  But it would probably vary a lot by compiler and machine architecture, so I wouldn't spend much time on it unless you have hard evidence later on that it is a bottleneck to your system.  Programming is as much about re factoring as it is about writing fresh code.

A: Switch statements are typically implemented with a jump table.  I think the assembly can go down to a single instruction, which would make it pretty fast.
The only way to be sure is to try it both ways.  If you can't modify your existing code, why not just make a test app and try it there?

A: Writing interpreters is fun, isn't it?  I can guess that the function pointer might be quicker, but when you're optimizing, guesses won't take you very far.
If you really want to suck every cycle out of that beast, it's going to take multiple passes, and guesses aren't going to tell you what to fix. Here's an example of what I mean.


Q: How to give strokes a specific width based on base64 i'm trying to build a stroked line, based on a svg file, cause of the color and the corner shapes that it has. Each stroke is 15px wide and has a gap between each line from also 15px. The problem is that when i try to include it via background-image it always makes the line longer than it actually should be.

.stroke-dotted {
  background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTVweCIgaGVpZ2h0PSI0cHgiIHZpZXdCb3g9IjAgMCAxNSA0IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPGcgaWQ9IldlYnNpdGUiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJEZXNrdG9wIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMTQyLjAwMDAwMCwgLTE5NDAuMDAwMDAwKSIgc3Ryb2tlPSIjMTZDREM3IiBzdHJva2Utd2lkdGg9IjMiPgogICAgICAgICAgICA8ZyBpZD0iU2VydmljZSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMC4wMDAwMDAsIDE0ODguMDAwMDAwKSI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iV2ViZGVzaWduIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg2MC4wMDAwMDAsIDQzOC4wMDAwMDApIj4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNODIsMTYgTDk3LDE2IiBpZD0ibGluZSI+PC9wYXRoPgogICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=);
  width: 100%;
  background-repeat: repeat-x;
}

Thats how it should look like:

And that's how it looks now:

Is there a way to give the lines a specific width of 15px and also an gap of 15px? I also tried to fix it with the background-size attribute, but it didn't worked out.

A: First things first: don't encode your SVG as a base64, it is much longer than the original code and its unnecessary as you can just add the code to the url. You might need to URL encode it for IE11 and earlier, but otherwise all browsers support it.
Now, to control your sizing in SVG tags, ommit the viewBox and simply give it a width and height of 100% and express all other values in percentage. Now you can control the size of the line by defining its pixel size, even though the points are defined in percentage:

div {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0%;
  top: 0%;
  background: url('data:image/svg+xml;charset=utf8,<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">\
    <line x1="0%" y1="50%" x2="100%" y2="50%" stroke="cyan" stroke-width="1px" stroke-dasharray="15px 15px" />\
  </svg>') no-repeat 50% 50% / cover;
}
body {
  /* A reference grid */
  background: url('data:image/svg+xml;charset=utf8,<svg width="15px" height="15px" xmlns="http://www.w3.org/2000/svg">\
    <rect x="0" y="0" width="100%" height="100%" stroke="#222" stroke-width="1px" fill="black" />\
  </svg>');
}

Once your SVG is correctly set up, it is as simple as defining the stroke-dasharray property with the pixel values:
<line x1="0%" y1="50%" x2="100%" y2="50%" stroke="black" stroke-width="1px" stroke-dasharray="15px 15px" />

Now you can use CSS to change your box, or even SVG to change the offsets within the SVG background.


Q: PHP Notice: Undefined index errors I have been creating some code in PHP and the logs of my server keep showing the following errors. The code are handlers for a game that I have been creating.  I have tried to fix them by researching and applying the ''fixes'' but it didn't go well.

Undefined index: a#jt in
/usr/share/nginx/Sweater/Sweater/GameHandler.php on line 160
Undefined index: a#jt in
/usr/share/nginx/Sweater/Sweater/GameHandler.php on line 161
Undefined index: a#jt in
/usr/share/nginx/Sweater/Sweater/GameHandler.php on line 167
Undefined index: a#lt in
/usr/share/nginx/Sweater/Sweater/GameHandler.php on line 227
Trying to get property of non-object in
/usr/share/nginx/Sweater/Sweater/GameHandler.php on line 302

This is the code for them:
function handleJoinTable(Array $arrData, Client $objClient) {
    $intPlayer = $arrData[4];
    $tableId = $arrData[2];
    $strUsername = $this->objDatabase->getUsername($intPlayer);
    $seatId = count($this->tablePopulationById[$tableId]) - 1; // Line 160
    if($this->gamesByTableId[$tableId] === null) { // Line 161
        $findFourGame = new FindFour();
        $this->gamesByTableId[$tableId] = $findFourGame;
    }
    $this->tablePopulationById[$tableId][$strUsername]; // Line 167
    $seatId += 1;
    $objClient->sendXt('jt', $objClient->getIntRoom(), $tableId, $seatId);
    $objClient->sendXt('ut', $objClient->getIntRoom(), $tableId, $seatId);
    $this->playersByTableId[$tableId][] = $intPlayer;
    $this->tableId = $tableId;
}

function handleLeaveTable(Array $arrData, Client $objClient) {
        $intPlayer = $arrData[2];
        $tableId = $arrData[3];
        $strUsername = $this->arrClientsByID[$intPlayer]; // Line 227
        unset($objClient->arrPlayer[$intPlayer]);
        $objClient->sendXt('lt', $objClient->getIntRoom(), $strUsername);
    }

function handleGetGame(Array $arrData, Client $objClient) {
    $intPlayer = $arrData[3];
    if($objClient->getExtRoom() == 802) {
        $puckData = $this->rinkPuck;
        $objClient->sendXt('gz', $objClient->getIntRoom(), $puckData);
    } elseif($intPlayer->tableId !== null) { // Line 302
        $tableId = $intPlayer->tableId;
        $playerUsernames = array_keys($this->tablePopulationById[$tableId]);
        @list($firstPlayer, $secondPlayer) = $playerUsernames;
        $boardString = $this->gamesByTableId[$tableId]->convertToString();
        $objClient->sendXt('gz', -1, $firstPlayer, $secondPlayer, $boardString);
    }
}

What's going on here?

A: $this->tablePopulationById[$tableId]
tablePopulationById is an array that DOES NOT contain a key of index $tableId.
$arrData[3]; DOES NOT contain an object of whatever class you were expecting!
In both cases, var_dump them to see what you DO have!
var_dump($this->tablePopulationById);
var_dump($arrData);


Q: Javascript: Testing form submit with sinon spy and chai Hi im trying to test a form submit using sinon spy and chai, however I am not sure if I am doing the right thing. Whenever i run the test, seconds comes back as undefined. Not sure why this is happening. I'm new to sinon, chai. Here is the code
This is the test file:
describe('CountdownForm', () => {
  it('should exist', () => {
    expect(CountdownForm).to.exist;
  });
  it('should call onSetCountdown if valid seconds entered', () => {
    const spy = sinon.spy();
    const countDownForm = shallow(<CountdownForm onSetCountdown={spy}/>)

    countDownForm.refs.seconds.value = '109';
    countDownForm.find('form').simulate('submit', { preventDefault(){} })

    expect(spy.called).to.be.true;
  });
});

This is the jsx file:
class CountdownForm extends Component {

  onSubmit = (e) => {
  e.preventDefault();
  const stringSeconds = this.refs.seconds.value;

  if (stringSeconds.match(/^[0-9]*$/)) {
    this.refs.seconds.value = '';
    this.props.onSetCountdown(parseInt(stringSeconds, 10));
    }
  }
  render() {
    return (
      <div>
        <form ref="form" onSubmit={this.onSubmit} className='countdown-form'>
          <input type="text" ref="seconds" placeholder="Enter time in seconds"/>
          <button className="button expanded">Start</button>
        </form>
      </div>
    );
  }
}


Q: ssh reverse port forwarding from local to remote2 by using remote1 I need port forwarding and also reverse port forwarding betwwen my localhost and remote2 pc using remote1 pc. My local pc can not connect directly remote2.
Design looks like:
local  ----------------> remote1 -----------------> remote2

5037  ---(ssh -L 5037:remote2:7385 user@remote1)--->  7385  //working

27183  <-----------( I can not achieve )------------ 27183  //need

I used ssh -L 5037:remote2:7385 -R remote2:27183:localhost:27183 user@remote1
But it forwards my local 27183 port to remote1's 27183 port.
How to use ssh tunnelling to forward my local 27183 port to remote2's 27183 port?


Q: ASP.NET removing DropDownList item inside repeater? I don't know if I am allowed to post such a specific issue here.
The scenario is that I have a Product that has a many to many relationship with Category.
Means one product may belong to multiple categories and a category may have multiple products. Now on the form I have provide a dropdown along with a button that says add another category and when I click on that button another dropdown should appear below that first dropdown. and the selected item of the previous dropdown must be remove from the dropdown items.
Below is my code of the dropdown's repeater and the two buttons mentioned.
    protected void btnAddAnotherCategory_Click(object sender, EventArgs e)
    {
        List<int> selectedIndices = new List<int>();
        foreach (RepeaterItem item in rptCategories.Items)
        {
            if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
            {
                DropDownList ddlCategory = (DropDownList)item.FindControl("ddlCategory");
                int selectedIndex = ddlCategory.SelectedIndex;
                selectedIndices.Add(selectedIndex);
            }
        }
        ViewState["objSelectedIndices"] = selectedIndices;
        rptCategories_DataSource("add", false);
    }

    protected void btnRemoveCategory_Click(object sender, EventArgs e)
    {
        List<int> selectedIndices = new List<int>();
        foreach (RepeaterItem item in rptCategories.Items)
        {
            if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
            {
                DropDownList ddlCategory = (DropDownList)item.FindControl("ddlCategory");
                int selectedIndex = ddlCategory.SelectedIndex;
                selectedIndices.Add(selectedIndex);
            }
        }
        ViewState["objSelectedIndices"] = selectedIndices;
        rptCategories_DataSource("remove", false);
    }

    protected void rptCategories_DataSource(string editCommand, bool pageLoad)
    {
        switch (editCommand)
        {
            case "add":
                if (ViewState["categoriesCount"] == null)
                {
                    List<Category> count = new List<Category>();
                    count.Add(new Category());
                    ViewState["categoriesCount"] = count;
                }
                if (!pageLoad)
                {
                    List<Category> count = (List<Category>)ViewState["categoriesCount"];
                    count.Add(new Category());
                    ViewState["categoriesCount"] = count;
                }
                List<Category> objCategories = (List<Category>)ViewState["categoriesCount"];
                objCategories = objCategories.Where(x => x.StatusID != 3).ToList();
                rptCategories.DataSource = objCategories;
                rptCategories.DataBind();
                break;
            case "remove":
                if (((List<Category>)ViewState["categoriesCount"]).Count > 1)
                {
                    List<Category> count = (List<Category>)ViewState["categoriesCount"];
                    count.Remove(count.Last());
                    count = count.Where(x => x.StatusID != 3).ToList();
                    ViewState["categoriesCount"] = count;
                    rptCategories.DataSource = count;
                    rptCategories.DataBind();
                }
                break;
        }
    }

    protected void rptCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        Category objCategory = (Category)e.Item.DataItem;

        DropDownList ddlCategory = (DropDownList)e.Item.FindControl("ddlCategory");
        ddlCategory.DataSource = new CategoryBLL().GetAllCategoriesWithStatus();
        ddlCategory.DataTextField = "Name";
        ddlCategory.DataValueField = "ID";
        ddlCategory.DataBind();

        if (objCategory.CategoryID != null)
            ddlCategory.SelectedValue = objCategory.CategoryID.ToString();

        if (ViewState["objSelectedIndices"] != null)
        {
            List<int> objSelectedIndices = (List<int>)ViewState["objSelectedIndices"];
            if (objSelectedIndices.Count > e.Item.ItemIndex)
                ddlCategory.SelectedIndex = objSelectedIndices.ElementAt(e.Item.ItemIndex);
        }

        if (e.Item.ItemIndex < ((List<Category>)rptCategories.DataSource).Count - 1)
        {
            ddlCategory.Enabled = false;
        }

        btnAddAnotherCategory.Visible = true;
        btnRemoveCategory.Visible = true;
        if (rptCategories.Items.Count < 1)
        {
            btnRemoveCategory.Visible = false;
        }
        if (rptCategories.Items.Count >= new CategoryBLL().GetAllCategoriesWithStatus().Count - 1)
        {
            btnAddAnotherCategory.Visible = false;
        }
    }

The StatusID mentioned in the code is to determine the deleted products as I am not ACTUALLY deleting the Product rather only setting its StatusID
Now the problem is that my code works fine with the above statements but as you can see it does not remove the selected items from the dropdown. The dropdown's are required to be populated from a single table everytime. The tricky part is removing the selecteditems in the previous repeateritems dropdownlist.
Any solution would be welcomed.


Q: Calling a variable into main function - Jython I'm an newbie playing around with JES and I'm testing how to call a variable in from another function to the main function. I'm using return which from what I understand should return variable num but it's still erroring :( Any guidance would be most appreciated.
def update():
  a = sqrt(10)
  b = 239
  getTotal(a,b)
  print num

def getTotal(a,b):
  num = a*b
  return num

A: Need somewhere for that value to return to.
Try this:
def update():
  a = sqrt(10)
  b = 239
  c = getTotal(a,b)
  print c

def getTotal(a,b):
  num = a*b
  return num


Q: ValueError invalid literal for int() with base 2: '' in Python I'm trying to get a string, jJ, as input and then converting each character to it's 6 bit binary form using the mapping given in a and concatenating them and returning it in mapFirst(string). That is, jJ becomes 100011001001.
In binaryToLetter(string) I'm taking the returned value and separating it into parts of 8 bits and converting it back to it's character form and concatenated. 100011001001 becomes 00001000 and 11001001, which are then converted and joined to give (backspace)É.
In my code, I'm getting the error :
Exception has occurred: ValueError
invalid literal for int() with base 2: ''

  File "C:\Users\Sembian\Desktop\exc files new\Ex_Files_Learning_Python\Exercise Files\task_cs\task1.py", line 11, in <genexpr>
    return ''.join( str( int( (binNew[newLen:newLen-i]),2 ) ).replace('0b','').zfill(8) for i in range(0, newLen, n) )

The code I used is :
from textwrap import wrap
a = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/']

def mapFirst(string):
   return ''.join(str(bin(ord(chr(a.index(c))))).replace('0b','').zfill(6) for c in string)

def binaryToLetter(binNew):
   newLen = len(str(binNew))
   n=8
   return ''.join( str( int( (binNew[newLen:newLen-i]),2 ) ).replace('0b','').zfill(8) for i in range(0, newLen, n) )

def main():
   k = 'jJ'
   print("the first binary value is: ",mapFirst(k))
   print("the final decoded value is: ", binaryToLetter(mapFirst(k)))

if __name__ == "__main__":
  main()

A: I managed to get something kinda working. For the first part:
def mapFirst(string):
   return ''.join(bin(a.index(c))[2:].zfill(6) for c in string)

I have removed a bunch of unnecessary clutter:

*

*ord(chr(x)) == x (assuming x:int < 256), because ord is an inverse of chr.

*str(bin(x)) == bin(x), because bin already returns a string.

*bin(x).replace('0b', '') == bin(x)[2:], because bin will always return a string starting with 0b, so you can use string (list) slicing.

For the second part:
def binaryToLetter(binNew):
   return ''.join(reversed([chr(int(binNew[max(0, i - 8):i], 2))
                            for i in range(len(binNew), 0, -8)]))

To break it down a little:

*

*I am using range(len(binNew), -1, -8) to generate decreasing a sequence from len(binNew) to 0 (inclusive) in steps of -8.

*I am then using the list slicing again to get the 8-bit long chunks from binNew, making sure that I don't overshoot the last one (that what the max() is for).

*I am turning these 8 char strings to a number with int(..., 2) and turning that number to chr.

*Because I am "chopping" away the 8 long substrings starting from the back, I need to reverse the order. But reversed doesn't accept generators, so I change the original generator into a list.


Q: How to call parent function in child button Suppose I have a component called ButtonComponent which will be used in various places in the application, so I make is as generic as possible, like so:
button.component.ts
import { Component, ViewEncapsulation, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ButtonComponent{

  @Input() group: FormGroup;
  @Input() type: string;
  @Input() description: string;
  @Input() class: string;
  @Input() callFunction: Function;
}

button.component.html

  <button type="{{ type }}" class="{{ class }}" (click)="callFunction()">{{ description }}</button>

Now my button is completely customizable (in theory). I am now going to import it to a login component which has a function called login(). I want my button instance to run this specific function when I click it:
login.component.ts
//imports

/**
* This component is rendered at the start of application, it provides the UI
* & functionality for the login page.
*/
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})

/**
* This class is used to build a login form along with initialization of validators
* as well as authenticate the user, and reroute upon success
*/
export class LoginComponent implements OnInit, AfterContentInit{

  @ViewChild('login', { read: ViewContainerRef }) login_button;

  /**
  * This property initializes the formGroup element.
  */
  userForm: FormGroup;

  /**
  * The constructor initializes Router, FormBuilder, OauthService, LoggerService, ToastrService
  * & TranslatePipe in the component.
  */
  constructor(//initializations
  ) { }

  /**
  * This is the hook called on the initialization of the component, it initializes
  * the form.
  */
  ngOnInit() {
    this.buildForm();
  }

  /**
   * This method initialized the the formGroup element. Its properties and the validators.
   *
   * @method buildForm
   * @return
   */
  buildForm() {
    // validations
  });
  }

   /**
   * This method returns the values of the form controls.
   *
   * @return
   */
  get form() { return this.userForm.controls; }

   /**
   * This method is triggered on success, it reroutes the user to main page.
   *
   * @return
   */
  onSuccess() {
    let result = this.translate.transform("pages[login_page][responses][success]");
    this.logger.info(result);
    this.toastr.success(result);
    this.router.navigate(['main']);
  }

   /**
   * This method is triggered when user clicks log-in, it calls the aunthenication method
   * from oauth service.
   *
   * @return
   */
  login() {
    this.oauth.authenticateUser(this.form.username.value, this.form.password.value, this.onSuccess.bind(this));
  }

  ngAfterContentInit() { //here I build my login button instance after init
    this.buildLoginButton();
  }

  /**
  * This function builds the login button, imports the ButtonComponent
  *
  */
  buildLoginButton(){
    let data = {
      type: "button",
      class: "btn btn-primary px-4",
      description: this.translate.transform("pages[login_page][login_form][buttons][login]"),
      function: "login",
      group: this.userForm
      }
    const inputFactory = this.resolver.resolveComponentFactory(ButtonComponent);
    const loginButton = this.login_button.createComponent(inputFactory);
    loginButton.instance.group = data.group;
    loginButton.instance.type = data.type;
    loginButton.instance.class = data.class;
    loginButton.instance.description = data.description;
    loginButton.instance.callFunction = function(){ //I call parent function using a static method
      LoginComponent.executeMethod(data.function);
    }
  }

  static executeMethod(someMethod){ //for my login button this should return this.login()
    eval("this."+someMethod+"()");
  }

}

To make the button instance visible I add the reference into my login template like this:

Now my button is visible, great! But now when i click the button:

ERROR TypeError: this.login is not a function
      at eval (eval at push../src/app/views/login/login.component.ts.LoginComponent.executeMethod
  (login.component.ts:225), :1:6)
      at Function.push../src/app/views/login/login.component.ts.LoginComponent.executeMethod
  (login.component.ts:225)
      at ButtonComponent.loginButton.instance.callFunction (login.component.ts:179)
      at Object.eval [as handleEvent] (ButtonComponent.html:2)
      at handleEvent (core.js:10251)
      at callWithDebugContext (core.js:11344)
      at Object.debugHandleEvent [as handleEvent] (core.js:11047)
      at dispatchEvent (core.js:7710)
      at core.js:8154
      at HTMLButtonElement. (platform-browser.js:988)

How do I make my button run the function in the parent component instead of looking for the function within itself? I don't want to change a lot in the ButtonComponent that would make it less generic as I have to make other buttons as well that would probably run other functions.
There was a solution that stated using EventEmitter for this, but I am unsure how this would work given how I am importing the button into the login component, both the ts and the html
Edit the complete login.component.html:

                <form [formGroup]="userForm" (submit)="login()">

{{ 'pages[login_page][login_form][labels][login]' | translate }}

{{ 'pages[login_page][login_form][labels][sign_in]' | translate }}

                </form>

{{ 'pages[login_page][sign_up_panel][labels][sign_up]' | translate }}

{{ 'pages[login_page][sign_up_panel][labels][new_account]' | translate }}

A: Add this code in button.component.ts
@Output() clickFunctionCalled = new EventEmitter<any>();
callFunction() {
    this.clickFunctionCalled.emit();
  }

No change in button.template.html
Add this code where you use app-button component in html
<app-button  (clickFunctionCalled)="callCustomClickFunction($event)"></app-button>

Add this in login.component.ts
callCustomClickFunction() {
   console.log("custom click called in login");
   this.login();
}

Basically, emit the click event from the child component. Catch the event in the parent component and call the desired function of the parent component.
You can also directly call the parent component's function like this
<app-button  (clickFunctionCalled)="login($event)"></app-button>

As you are using dynamic component creator for creating the button component, you need to do something like this, for binding output event
loginButton.instance.clickFunctionCalled.subscribe(data => {
    console.log(data);
});


Q: unable to compile play 2.8.15 using sbt 1.7.1 Due to log4j vulnerability, using sbt 1.7.1 version with play 2.8.15,but unable to compile the play code and getting errors.
Steps taken:

*

*Downloaded sbt code 1.7.1 from https://www.scala-sbt.org/download.html

*Installed the new Play binary eg PlayDev-2.8.15

*Removed .sbt .cache .ivy2 from  /home directory

*Ran sbt_stage.sh and see below error .

[PlayDev-2.8.15]$ ./sbt_stage.sh
/apps/Play/PlayDev-2.8.15/build.sbt:2: error: not found: value PlayJava
  .enablePlugins(PlayJava,LauncherJarPlugin)
                 ^
/apps/Play/PlayDev-2.8.15/build.sbt:2: error: not found: value LauncherJarPlugin
  .enablePlugins(PlayJava,LauncherJarPlugin)
                          ^
/apps/Play/PlayDev-2.8.15/build.sbt:3: error: not found: value PlayFilters
  .disablePlugins(PlayFilters)
                  ^
/apps/Play/PlayDev-2.8.15/build.sbt:9: error: not found: value guice
      guice,
      ^
/apps/Play/PlayDev-2.8.15/build.sbt:10: error: not found: value ws
  ws,
  ^
/apps/Play/PlayDev-2.8.15/build.sbt:11: error: not found: value ehcache
  ehcache,
  ^
/apps/Play/PlayDev-2.8.15/build.sbt:12: error: not found: value javaJpa
      javaJpa,
      ^
/apps/Play/PlayDev-2.8.15/build.sbt:14: error: not found: value javaWs
       javaWs % "test",
       ^
/apps/Play/PlayDev-2.8.15/build.sbt:24: error: not found: value routesGenerator
    routesGenerator := InjectedRoutesGenerator,
    ^
/apps/Play/PlayDev-2.8.15/build.sbt:24: error: not found: value InjectedRoutesGenerator
    routesGenerator := InjectedRoutesGenerator,
                       ^
/apps/Play/PlayDev-2.8.15/build.sbt:25: error: not found: value PlayKeys
    PlayKeys.externalizeResources := false,
    ^
/apps/Play/PlayDev-2.8.15/build.sbt:39: error: not found: value PlayKeys
    PlayKeys.externalizeResourcesExcludes += baseDirectory.value /
    ^
sbt.compiler.EvalException: Type error in expression
[warn] Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore? (default: r)
sbt script version: _to_be_replaced
[info] welcome to sbt 1.7.1 (Oracle Corporation Java 1.8.0_232)
[info] loading project definition from /apps/Play/PlayDev-2.8.15/project


Q: opencv MSER.detectRegions() vs findContours(): what's the difference? I am building a generic text parsing algorithm for images.
I was running:
MSER.detectRegions()

vs
findContours(...cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

on a binary image. The results where the same.
I know MSER can be done on gray-scale but I wanted to go safer.
I need to select one of them and the findContours() takes less then half the run time MSER does.
Am I missing something?
What would you pick?

A: As already pointed out, it does not make sense to compute MSER on a binary image. MSER basically thresholds an image (grayscale) multiple times using increasing (decreasing) thresholds and what you get is a so called component tree like this here. The connected components which change their size/shape at least over the different binarizations are the so-calles Maximally Stable Extremal Regions (e.g. the K in the schematic graphic). This is of course a very simplified explanation. Please ask Google for more details, you'll find enough.
As you can see, thresholding an already thresholded image does not make sense. So pass the grayscale image to the MSER algorithm instead. MSER is a common basis for state-of-the-art text detection approaches (see here and here).


Q: Interpreting coefficients in log-log model with dummy for elasticity I'm running an analysis of two products, X and Y, and I'm particularly interested in understanding the elasticities. However, I'm struggling to interpret the results.
I'm using a log-log model, and in the first run I set quantity of product X (oz_X) as the dependent variable and the price of X (pX) as the independent variable to obtain X's own-price elasticity. The result below shows an elasticity of -6.94.

Then I include a dummy variable (deal_X) in the model that indicates whether product X was on promotion (i.e. on discount) or not. I'm doing this because I'm interested in determining if regular and promotional prices have different elasticities, and to determine if these elasticities are statistically different from each other. Including this dummy variable into the model I get the below result.

Can someone help me with interpreting this result, specifically in the context of elasticities? Am I correct in interpreting the coefficient on the dummy variable as the demand for product X increasing by 140% when X is on promotion compared to when it's not? (That sounds like a lot...) Furthermore, the own-price elasticity of X has fallen (in absolute value) from -6.94 to -3.14. What exactly does this mean, and what business implications does this have?

A: In your first model, the interpretation is that a 1% decrease in price leads to an approximately 7% increase in sales. The coefficient is an elasticity, and since it is greater than 1, we consider demand elastic since the change in quantity is larger than price.
When you give out a promotional discount, the new elasticity is smaller: now a 1% decrease in price leads to 3% increase in sales. This has some sense: discounting takes you to a different region of the demand curve, where demand is less sensitive to price changes (more inelastic).
You can also go in the other direction and calculate the effect of a price increase, as it is symmetric. Just multiply by negative one. More detail here. This link gives better approximation when the log-log coefficient is larger. Here it is not too far off.
The discount promotion dummy is trickier. When it goes from from 0 to 1 (a sale), the approximate effect on sales is:
$$100 \cdot \left[ \exp(1.4010 - \frac{1}{2}\cdot 0.042^2)-1 \right] \approx +306 \%$$
In this case, the effect is not symmetric. When the dummy goes from 1 to 0 (sale ends), then
$$100 \cdot \left[ \exp(-1.4010 - \frac{1}{2} \cdot 0.042^2)-1 \right] \approx -75 \%$$
Getting rid of the discount does not give you the same effect.
The dummy variable formula can be found on David Giles' old blog.
All these interpretations assume that you don't have an endogeneity problem with your data that biases these elasticities substantially. For example, if the variation in these prices were random (say set in an experiment), that would suffice.


Q: Test return value from jest mocked event callback I have the following component in Button.tsx:
// Button.tsx
import * as React from 'react';
import { Button as ReactstrapButton } from 'reactstrap';

interface IHandlerParams<onClickArgsType> {
  onClickParams?: onClickArgsType
}

export interface IButtonProps<onClickArgsType = {}> {
  color?: string,
  onClick?: (event: React.MouseEvent<any>, args?: onClickArgsType) => any,
  handlersParams?: IHandlerParams<onClickArgsType>
}

interface IHandlers {
  onClick: React.MouseEventHandler<any>
}

export class Button<onClickArgsType> extends React.Component<IButtonProps<onClickArgsType>> {

  private handlers: IHandlers;

  constructor(props: IButtonProps<onClickArgsType>) {
    super(props);
    this.handlers = {
      onClick: (MouseEvent:React.MouseEvent<any>) => { if (this.props.onClick) {this.props.onClick( MouseEvent, this.props.handlersParams ? this.props.handlersParams.onClickParams : undefined) }}
    }
  }

  render() {
    return (
      <ReactstrapButton
        color={this.props.color}
        onClick={this.handlers.onClick}>
        {this.props.children}
      </ReactstrapButton>
    )
  }
}

NOTE: I am using that weird "handlers" object to manage the event's callback, so that I do not have an arrow function directly in the ReactstrapButton properties, avoiding creating a new object each time and thus preventing the component from being re-rendered.
And a corresponding test file in Button.unit.test.tsx:
// Button.unit.test.tsx
import { mount, shallow } from "enzyme";
import * as React from "react";

import { Button, IButtonProps } from "./Button";

interface IOnClickParamsTest {
  a: number,
  b: number
}

describe('App component', () => {
  it('renders without crashing', () => {
    shallow(
      <Button />
    );
  });

  it('test the onClick method', () => {
    const onClick = jest.fn((event: React.MouseEvent<IButtonProps<IOnClickParamsTest>>, params: IOnClickParamsTest) => params.a + params.b);
    const onClickParams: IOnClickParamsTest = { a: 4, b: 5 };

    const buttonComponent = mount(
      <Button<IOnClickParamsTest>
        onClick={onClick}
        handlersParams={{ onClickParams }}
      />
    );
    buttonComponent.simulate("click");

    expect(onClick).toBeCalled();
    expect(onClick.mock.calls[0][1]).toBe(onClickParams);// The second argument of the first call to the function was onClickParams
    // expect(onClick.mock.results[0].value).toBe(9);// The return value of the first call to the function was 9
  });

});

The test passes as expected, but fails in the last commented line with following error:
TypeError: Cannot read property '0' of undefined

The error is referencing to the onClick.mock.results property. I have debugged the onClick.mock property and results, of course, is not there. Nevertheless, as per this docs in Jest, there should exist a results property in there.
By the way, I am using :
"react": "^16.4.0",
"react-dom": "^16.4.0",

"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"jest": "^23.1.0",
"jest-enzyme": "^6.0.2",
"ts-jest": "^22.4.6"

Any thoughts? Thank you so much in advance!

A: The return value is available in Jest v23.  Apps bootstrapped using create-react-app with react-scripts-ts as of today (Aug 1, 2018) are using Jest v22.  create-react-app will be updated to use Jest v23 in the near future.
In the meantime, testing the return value is possible using Sinon fakes.
In this case the updated test looks like this:
// Button.unit.test.tsx
import { mount, shallow } from "enzyme";
import * as React from "react";
import * as sinon from 'sinon';

import { Button, IButtonProps } from "./Button";

interface IOnClickParamsTest {
  a: number,
  b: number
}

describe('App component', () => {
  it('renders without crashing', () => {
    shallow(
      <Button />
    );
  });

  it('test the onClick method', () => {
    const onClick = sinon.fake((event: React.MouseEvent<IButtonProps<IOnClickParamsTest>>, params: IOnClickParamsTest) => params.a + params.b);
    const onClickParams: IOnClickParamsTest = { a: 4, b: 5 };

    const buttonComponent = mount(
      <Button<IOnClickParamsTest>
        onClick={onClick}
        handlersParams={{ onClickParams }}
      />
    );
    buttonComponent.simulate("click");

    expect(onClick.calledOnce).toBe(true);
    expect(onClick.firstCall.args[1]).toBe(onClickParams);
    expect(onClick.returnValues[0]).toBe(9);
  });

});


Q: What does "m" mean in mpstat? I check the manual of mpstat it states:

The mpstat command writes to standard output activities  for  each  available
     processor,  processor 0 being the first one.  Global average activities among
     all processors are also reported.  The mpstat command can be used both on SMP
     and  UP  machines,  but in the latter, only global average activities will be
     printed. If no activity has been selected, then the default report is the CPU
     utilization report.

However, I didn't get the idea what does m mean in mpstat?  is it multiple?

A: It's unclear exactly what the M in mpstat means. NOTE: mpstat is part of the sysstat package and so is part of a family of *stat tools:
$ rpm -ql sysstat | grep /bin/
/usr/bin/cifsiostat
/usr/bin/iostat
/usr/bin/mpstat
/usr/bin/nfsiostat-sysstat
/usr/bin/pidstat
/usr/bin/sadf
/usr/bin/sar
/usr/bin/tapestat

It's likely the case that the M stands for one of the following:

*

*multi-processor

*multiple-processors

*microprocessor

*machine

*monitor

Given the top of the mpstat.c source code describes it as this:

*

*mpstat: per-processor statistics

I'd be inclined to go with the multiple. This seems to be consistent with the source code if you glance through it, given it goes out of its way to deal with both single (UP) and multiple CPUs (SMP).
Example comments from code:

*

*Structures used to save CPU and NUMA nodes CPU stats

*Compute CPU "all" as sum of all individual CPU (on SMP machines and look for offline CPU.

*Read total number of interrupts received among all CPU.

*What is the highest processor number on this machine?

NOTE: One thing I find curious with this tool, is that if the M is meant to represent multi*, this word never actually appears in the source code, mpstat.c.
References

*

*Wikipedia - mpstat

*sysstat utilities

A: According to Linux Magazine it looks like "multi-processor". I'm sure "multiple processor" would work, too.

A: mpstat is from the first multi processor enhancements from SunOS-4.x.
There is no hint to multi processor in the source code nor in the man page, so there it could only be seen as an obvious explanation.


Q: Spectral density for the operator $A u = - u''$? How to prove that the spectral density for the operator $A u = - u''$ on the whole real line is
$$ e(x,y;\lambda) = \frac{\chi(\lambda) \, cos\lambda^{1/2} (x-y)}{2\pi \lambda^{1/2}} $$
where $\chi $ is the Heaviside function.
Thank you in advance

A: Let $s=\sqrt{\lambda}$ in the following, with $ds = \frac{1}{2\sqrt{\lambda}}d\lambda$,
$$
      \int_{0}^{\infty}\left(\int_{-\infty}^{\infty}f(y)\frac{\cos\sqrt{\lambda}(x-y)}{2\pi\sqrt{\lambda}}dy\right)d\lambda \\
  = \frac{1}{\pi}\int_{0}^{\infty}\left(\int_{-\infty}^{\infty}f(y)\cos s(x-y)dy\right)ds \\
  = \frac{1}{\pi}\int_{0}^{\infty}\int_{-\infty}^{\infty}f(y)\cos(sy)dy\cos(sx)ds
   + \frac{1}{\pi}\int_{0}^{\infty}\int_{-\infty}^{\infty}f(y)\sin(sy)dy\sin(sx)ds \\
  = \frac{2}{\pi}\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}f(y)\cos(sy)dy\cos(sx)ds+\frac{2}{\pi}\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}f(y)\sin(sy)dy\sin(sx)ds
$$
You can also write the original expression in terms of the exponential form.


Q: How does an HTTPProxySocket work? Background
I'm trying to figure out what's going on in a proxy server implementation I found online here but am quite lost. I was able to run the proxy successfully, but I am unable to understand what is happening under the hood. I'll explain what exactly I'm confused about in just a moment.
What I have done so far
I was able to start the proxy server described in this class and redirected my HTTP traffic there. I am able to successfully load pages in my browser through the proxy.
Where I am confused
The socket that is opened when a connection is received by the proxy server is of type HTTPProxySocket. Within this socket, data is passed to the remote server, and when data is read back, an HTTPStreamScanner (line 127) is used to scan the response data.
But I'm able to see both HTTP and HTTPS header data, which is really confusing to me.
Question

*

*It seems like HTTP Connect is being used. After a little digging, it seems like CONNECT is used to initialize a tunnel. Really, I'm over my head with this. How does a tunnel relate to a socket, and why would I want to create a tunnel in the first place?

*At what layer of the network model does this operate? Or does that question not even make sense?

A: Regardless of how encrypted the HTTPS connection might be, at minimum the proxy needs to know:

*

*the server's address (usually the IP address, but many browsers send the full hostname – in case the proxy might have different DNS settings),

*the TCP port to connect to (generally 443 for HTTPS).

According to your comments, that's the only information you are seeing, so this is normal. The browser won't be sending HTTP-specific parameters (original request method, path, query string, HTTP headers) until it establishes the TLS connection to the server, through your proxy.

Really, I'm over my head with this. How does a tunnel relate to a socket, and why would I want to create a tunnel in the first place? [...] At what layer of the network model does this operate? Or does that question not even make sense?

(This is a general description, not a NEKit-oriented description.)
In networks, a tunnel is something that pretends to be at a lower layer than it really is, and is able to carry same-layer or even lower-layer protocols inside itself.
For example, regular HTTP is an application-layer protocol, but HTTP CONNECT allows it to carry other application-layer protocols inside – to the web browser it behaves like a transport protocol, in the sense that you can build connect()/send()/recv() functions around it.
As another example, most VPNs are a type of tunnel that carries IP inside UDP, i.e. L3 over L4. (Maybe even L3-over-L7 if you include the encryption/compression/authentication stuff that the VPN does.)
(TLS itself is quite similar. If you're looking from the transport layer's point of view, TLS is an application layer protocol, but if you look from the application's perspective, TLS could very well be the upper-half of transport layer.)
So why would you want to create a tunnel? To break the layering, that's literally it. Your original question was, "why does the proxy seem to break HTTPS encryption". That's exactly why HTTP CONNECT is used – browsers use it to carry a lower-layer protocol (TLS) inside a higher-layer protocol (HTTP) in order to preserve the encryption.


Q: Why does standard error not involve population size? $$SE = \frac{SD}{\sqrt{N}}$$

*

*If N is the entire population, I would expect SE to be zero.

*If N is equal to population size - 1, I would expect SE to be lower than if N is a small fraction of the population size, yet SE is the same.

So why isn't population size part of SE?
While a mathematical explanation is great, I'd really like to get a gut feel intuition of the reason.

A: This formula assumes that the sample is a very small proportion of the population.
If there is a finite population and the sample is a substantial part of it, you can use the finite population correction:
$\text{FPC} = \sqrt{\frac{N-n}{N}}$
where $n$ is the sample size and $N$ is the population size.  If $N = n$ then this will become 0, as you suspected. Ordinarily, though, it makes very little difference.