Setting imageview to horizontal scroll view

Question: Hi I have an url which gives me 2 image links. I have to download the image and set the image. I'm using horizontal scroll view and have reached till getting the image url and downloading the image using async task. can some one let me know how to set image to horizontal scroll view.
public void fetchImageUrl(){
    String url="http://apps.aspelec.com/cms/api/UploadImageAndChangeComplaintStatus?companyid=1&callrecordid=13";
    StringRequest request=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            System.out.println(response);
            getJsonUrl(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("ErrorListner=",error.getMessage());
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(request);

}
public void getJsonUrl(String response){
    try {
        JSONArray jArray = new JSONArray(response);
        ArrayList<String> imgurl=new ArrayList<>();
        for(int i=0;i<1;i++){
          String dummyurl=jArray.getJSONObject(i).getString("ImagePath");
            System.out.println("dummy url=="+dummyurl);
            imgurl.add(dummyurl);
            setView(imgurl);
        }
    }catch (JSONException e){

    }
}
public void setView(ArrayList<String> imgUrl){
    for(int j=0;j<imgUrl.size();j++){
        vi=(LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v=vi.inflate(R.layout.custome_serverdownloadedimageview,null,false);
        img=(ImageView)v.findViewById(R.id.customserverdownlodedimg);
        new DownloadImage(img).execute(imgUrl.get(j));
        //Picasso.with(this).load(imgUrl.get(j)).resize(100,100).into(img);
    }
}

activity_main.xml
    <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/supervisor_complaint_details_cardview"
    android:fillViewport="true"
    android:foregroundGravity="left"
    android:paddingBottom="25dp"
    android:paddingLeft="25dp"
    android:paddingRight="25dp"
    android:paddingTop="25dp"
    tools:context="com.six30labs.cms.activity.VerifyDetailSupervisor">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <RelativeLayout
        android:id="@+id/layoutComplaintNameSupervisor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/verifyComplaintLabelSupervisor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:text="@string/complaint_name"
            android:textColor="@color/colorPrimary"
            android:textSize="17sp"
            android:typeface="serif" />

        <TextView
            android:id="@+id/verifyComplaintFieldSupervisor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/verifyComplaintLabelSupervisor"
            android:layout_marginTop="5dp"
            android:gravity="left"
            android:maxLines="5"
            android:minLines="2"
            android:textColor="@color/black"
            android:textSize="16sp"
            android:textStyle="normal"
            android:typeface="serif" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_below="@+id/verifyComplaintFieldSupervisor"
            android:layout_marginTop="10dp"
            android:background="#000000" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/layoutTicketNumberSupervisor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/layoutComplaintNameSupervisor">

        <TextView
            android:id="@+id/verifyLabelTicketNoSupervisor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:gravity="left"
            android:text="@string/ticket_number"
            android:textColor="@color/colorPrimary"
            android:textSize="17sp"
            android:typeface="serif" />

        <TextView
            android:id="@+id/verifyTicketNumberFieldSupervisor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/verifyLabelTicketNoSupervisor"
            android:layout_marginTop="10dp"
            android:gravity="left"
            android:textColor="@color/black"
            android:textSize="16sp"
            android:textStyle="normal"
            android:typeface="serif" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_below="@+id/verifyTicketNumberFieldSupervisor"
            android:layout_marginTop="10dp"
            android:background="#000000" />

    </RelativeLayout>

        <LinearLayout

            android:id="@+id/layoutAssignedAndDueDateSupervisor"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="1"
            android:layout_below="@+id/layoutTicketNumberSupervisor">

            <RelativeLayout
                android:id="@+id/layoutAssignedDateSupervisor"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.5">

                <TextView
                    android:id="@+id/verifylabelAssignedDateSupervisor"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="15dp"
                    android:gravity="left"
                    android:text="@string/assigned_date"
                    android:textColor="@color/colorPrimary"
                    android:textSize="17sp"
                    android:typeface="serif" />

                <TextView
                    android:id="@+id/VerifyAssignedDateFieldSupervisor"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/verifylabelAssignedDateSupervisor"
                    android:layout_marginTop="10dp"
                    android:gravity="left"
                    android:textColor="@color/black"
                    android:textSize="13sp"
                    android:textStyle="normal"
                    android:typeface="serif" />
                </RelativeLayout>

            <RelativeLayout
                android:id="@+id/layoutDueDateSupervisor"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.5">

                <TextView
                    android:id="@+id/verifylabelDueDateSupervisor"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="15dp"
                    android:layout_centerHorizontal="true"
                    android:text="@string/due_date"
                    android:textColor="@color/colorPrimary"
                    android:textSize="17sp"
                    android:typeface="serif" />

                <TextView
                    android:id="@+id/VerifyDueDateFieldSupervisor"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_below="@+id/verifylabelDueDateSupervisor"
                    android:layout_marginTop="10dp"
                    android:gravity="left"
                    android:textColor="@color/black"
                    android:textSize="13sp"
                    android:textStyle="normal"
                    android:typeface="serif" />
            </RelativeLayout>
        </LinearLayout>

        <View
            android:id="@+id/divider"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_below="@+id/layoutAssignedAndDueDateSupervisor"
            android:layout_marginTop="10dp"
            android:background="#000000" />

        <LinearLayout
            android:id="@+id/layoutCompletedDateAndPrioritySupervisor"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="1"
            android:layout_below="@+id/divider">

            <RelativeLayout
                android:id="@+id/layoutCompletedDateSupervisor"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.5">

                <TextView
                    android:id="@+id/verifylabelCompletedDateSupervisor"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="15dp"
                    android:text="@string/completed_date"
                    android:textColor="@color/colorPrimary"
                    android:textSize="17sp"
                    android:typeface="serif" />

                <TextView
                    android:id="@+id/VerifyCompletedDateFieldSupervisor"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/verifylabelCompletedDateSupervisor"
                    android:layout_marginTop="10dp"
                    android:gravity="left"
                    android:textColor="@color/black"
                    android:textSize="13sp"
                    android:textStyle="normal"
                    android:typeface="serif" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.5">

                <ImageView
                    android:id="@+id/verifyPriorityImage"
                    android:layout_width="wrap_content"
                    android:layout_height="50dp"
                    android:layout_centerVertical="true"
                    android:layout_centerHorizontal="true"
                    android:src="@mipmap/calendar"/>
            </RelativeLayout>
        </LinearLayout>

        <View
            android:id="@+id/divider1"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_below="@+id/layoutCompletedDateAndPrioritySupervisor"
            android:layout_marginTop="10dp"
            android:background="#000000" />

        <RelativeLayout
            android:id="@+id/layoutVerifyServerImageLabel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/divider1">

            <TextView
                android:id="@+id/serverImageLabel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/view_Image"
                android:layout_marginTop="15dp"
                android:textColor="@color/colorPrimary"
                android:textSize="17sp"
                android:typeface="serif"/>

        </RelativeLayout>

        <HorizontalScrollView
            android:id="@+id/layoutVerifyServerImage"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:orientation="horizontal"
            android:layout_below="@+id/layoutVerifyServerImageLabel">

            <LinearLayout
                android:id="@+id/serverDownloadedImageView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"/>

        </HorizontalScrollView>
    </RelativeLayout>
</ScrollView>

Custom Imageview
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/customserverdownlodedimg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"/>
</LinearLayout>

Comment: Please see I have other things to display on xml file, In the end I will be displaying the images..
My Horizontal scroll view is at the bottom of the xml file..
Comment: you can add a horizontal RecyclerView in place of ScrollView which will not just work perfect but also would be much user friendly
Comment: Thanks for the suggestion... I will try to use that I was just reading about it now.
Answer: You can do something like this
 horizontalScrollView = (HorizontalScrollView)findViewById(R.id.horizontal_grid);
        int[] images = new int[]{R.drawable.image1, R.drawable.image2, ....R.drawable.image10};
        LinearLayout sv = (LinearLayout) findViewById (R.id.horizontal_container);
        for (int i=0 ; i<images.length; i++){
            ImageView iv = new ImageView (this);
            LinearLayout.LayoutParams imageViewLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,  ViewGroup.LayoutParams.MATCH_PARENT);
            iv.setPadding(4,0,0,0);
            iv.setImageResource(images[i]);
            iv.setLayoutParams(imageViewLayoutParams);
            sv.addView(iv);
        }

And your xml should look something like this
    <HorizontalScrollView
        android:id="@+id/horizontal_grid"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="40">
        <LinearLayout
            android:id="@+id/horizontal_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal" >
        </LinearLayout>

    </HorizontalScrollView>

Answer: public void setView(ArrayList<String> imgUrl){

serverDownloadedImageView = (LinearLayout)findViewById(R.id.serverDownloadedImageView);
serverDownloadedImageView.removeAllViews();
    for(int j=0;j<imgUrl.size();j++){

     ImageView img = new ImageView(this);

        new DownloadImage(img).execute(imgUrl.get(j));
        //Picasso.with(this).load(imgUrl.get(j)).resize(100,100).into(img);
    serverDownloadedImageView.addView(img,j)

    }
}


Load Jquery on buttonclick asp.net

Question: Hi i am trying to load the following jquery on buttonclick in the code behind, however nothing seems to be happening;
    StringBuilder sb = new StringBuilder();
    sb.Append("$(document).ready(function () {");
    sb.Append("$.gritter.add({");
    sb.Append("title: 'This is a regular notice!',");
    sb.Append("text: 'This will fade out after a certain amount of time. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.',");
    sb.Append("image: 'http://a0.twimg.com/profile_images/59268975/jquery_avatar_bigger.png',");
    sb.Append("sticky: false,");
    sb.Append("time: ''");
    sb.Append("});");
    sb.Append("});");

    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(), sb.ToString(), true);

Can anyone see what i am doing wrong?
Comment: Are you getting script errors in your browser? What does this look like if you do a view-source?
Comment: No i am not getting any errors, nothing appears on source code either.
Answer: Without knowing the context (UpdatePanel? Postback? Why do this from the server at all?) it's hard to say.
You should probably be using RegisterStartupScript instead of RegisterClientScriptBlock, if this happens to be in an UpdatePanel. Otherwise it will never be executed.
Also I can't think of a good reason why this needs to be created from the server in the first place. Put your code in a function that loads with the page, and call the function from a client event (e.g. onclick or better, register an event handler using jQuery) rather than trying to create the entire function and run it after a postback, e.g.
(editied based on comments) -- just set your functions up for either condition. If the only thing different is the title, you don't need two functions, e.g.

In c#:
bool success; // your update should set a bool somewhere based on whether it
              // succeeded
Page.ClientScript.RegisterStartupScript("addNotice(" + success.ToString() + ");");
             // will render "addNotice(true)" or "addNotice(false)"

A better way to do this would be with ajax instead of posting back, but that would be a different kettle of fish and this should work with your current architecture.
Comment: The reason it needs to be added server side, is the image that appears is dynamic, also depending on success or failure i want to load a different jquery, does that make sense?
Comment: I don't know anything about the gritter plugin, but none of what you've said tells me that it needs to be done on the server. There's no issue with loading an image from client script, or acting conditionally. I would need to see some more context to better respond to that, however..
Comment: I am checking in the database is allowed to insert data, if they are i allow them to insert the data, and display a jquery notification. If they are not allowed i display a different version of the notification. i hope i am making sense

Load Jquery on buttonclick asp.net


javafx mediaview white flash on transition

Question: Folks...
I'm using the following code to transition between two videos.
public void loadMedia(Media media)
{
    MediaPlayer newPlayer = new MediaPlayer(media);
    newPlayer.setAutoPlay(true);
    mediaView.setMediaPlayer(newPlayer);
    player = newPlayer;
}

When I call loadMedia with the new video, the mediaplayer flashes white briefly. I'm guessing this has to do with the status taking time. But I need these transitions to go smoothly with no flash.
What to do?
Thanks,
GeePaw
Answer: As so often, I answered my own question shortly after. The trick is to wait for the status to be ready before you change the view's player:
public void loadMedia(Media media)
{
    MediaPlayer newPlayer = new MediaPlayer(media);
    newPlayer.setAutoPlay(true);
    newPlayer.setOnReady(()->videoReady(newPlayer));
}

private void videoReady(MediaPlayer newPlayer)
{
    mediaView.setMediaPlayer(newPlayer);
    player = newPlayer;
}

Comment: Your answer almost saved my day. Im having trouble to adapt to my needs, at the end of the video, i must find the next one and play it, it works.. i have the same problem as yours, a white flick between the files, i tryed to adapt your solution, but got nothing... any chance you elaborate more?

as far as i got with your answer i still have the same white flick.
(code at -> https://pastebin.com/0jej1rrF) the carregaVideos(),update the 'this.url' string, to the next file to be played.

thanks for your time!


Is it mandatory to apply every minor Core upgrade step by step?

Question: I have a site in drupal 6.26 and I need actualize it.
I have two options:
6.26 to 6.27 to 6.28
or
6.26 to 6.28 directly
What is the best method? Thanks
Answer: You can go from 6.26 directly to 6.28.
The most critical part, is the database update, because tables and fields can get modified, added or removed. The upgrade process in Drupal takes care of executing every single database update step.


Alternative Tyre Allocation: what happens if it rains?

Question: The 2023 Hungarian Grand Prix will be using the new Alternative Tyre Allocation rule for Qualifying.
What happens if it rains during Qualifying? All I have heard is they must use hards for q1, mediums for q2 and soft for q3.
Comment: Could you provide a source for where you heard this?
Comment: they are using the "alternative tire allocation " this weekend. It was supposed to be used at Imola ,but that was cancelled.Formula 1 to answer your ?
Comment: Hi @keva454 - I have edited your question to make it clearer to the question I think you're asking - If you feel that my changes are incorrect - feel free to [edit](https://sports.stackexchange.com/posts/29022/edit) the question again
Answer: If the session is declared "wet" by the race stewards, then the teams will have a free tyre choice.
From Mercedes' explainer on the new rules:

Drivers have four sets of the intermediate tyre, and three sets of wets, to use per weekend. If a session is declared wet, they then have a free tyre choice. This could be from those inters or wets, but also across the slick tyre range if track conditions permit. That means we may not see the mandated compound running in qualifying.


How to change static Variables in Java

Question: How do I change the data exchange to not use statics. My Prof told me I should avoid it, but I dont know how to improve here. For example I brought the class Controls. Any Ideas? I really don't know what to do and need help. Thank You!!
package game2048;

public class GameBody {
    public static final ColorDescription COLORS = new ColorDescription();
    public static final Window WINDOW = new Window("2048");
    public static final Controls CONTROLS = new Controls();
    public static final Board BOARD = new Board(4);

}
public class Controls implements KeyListener {

    @Override
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
    public void keyPressed(KeyEvent e) {

        int keyCode = e.getKeyCode();

        switch (keyCode) {
            case KeyEvent.VK_UP:
                GameBody.BOARD.moveUp();
                break;
            case KeyEvent.VK_DOWN:
                GameBody.BOARD.moveDown();
                break;
            case KeyEvent.VK_LEFT:
                GameBody.BOARD.moveLeft();
                break;
            case KeyEvent.VK_RIGHT:
                GameBody.BOARD.moveRight();
                break;
            case KeyEvent.VK_ESCAPE:
                GameBody.WINDOW.dispose();
                break;
            default:
                break;
        }

        GameBody.BOARD.isGameOver();
        GameBody.WINDOW.repaint();

    }

    public void bind() {
        GameBody.WINDOW.addKeyListener(this);
    }

    public void unbind() {
        GameBody.WINDOW.removeKeyListener(this);
    }

}

Comment: 1) Remove the `static` keyword. 2) Declare an instance of `GameBody` instead of using the class directly.
Answer: At first, remove all static keywords.
Then, in you main(), create an instance of your Gameboy using:
GameBody gamebody = new Gamebody();

And be aware of keyPressed. It might be a better idea to use keyReleased.
Answer: Something like this:
package game2048;

public class GameBody {
    public final ColorDescription COLORS = new ColorDescription();
    public final Window WINDOW = new Window("2048");
    public final Controls CONTROLS = new Controls();
    public final Board BOARD = new Board(4);

}
public class Controls implements KeyListener {
    private GameBody gamebody = GameBody();

    @Override
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
    public void keyPressed(KeyEvent e) {

        int keyCode = e.getKeyCode();

        switch (keyCode) {
            case KeyEvent.VK_UP:
                gamebody.BOARD.moveUp();
                break;
            case KeyEvent.VK_DOWN:
                gamebody.BOARD.moveDown();
                break;
            case KeyEvent.VK_LEFT:
                gamebody.BOARD.moveLeft();
                break;
            case KeyEvent.VK_RIGHT:
                gamebody.BOARD.moveRight();
                break;
            case KeyEvent.VK_ESCAPE:
                gamebody.WINDOW.dispose();
                break;
            default:
                break;
        }

        gamebody.BOARD.isGameOver();
        gamebody.WINDOW.repaint();

    }

    public void bind() {
        gamebody.WINDOW.addKeyListener(this);
    }

    public void unbind() {
        gamebody.WINDOW.removeKeyListener(this);
    }

}

How to change static Variables in Java


Mongo Aggregate Nested Array, Lookup

Question: I am creating a web application using MongoDB and Go, which includes role based access control. I am storing the information regarding this in 2 collections, permissions and roles.
This is how these two collections look like.
Permissions
{
    "operation": "create",
    "resource": "project"
}
{
    "operation": "read",
    "resource": "project"
}
{
    "operation": "update",
    "resource": "project"
}
{
    "operation": "delete",
    "resource": "project"
}
{
    "operation": "create",
    "resource": "user"
}

resource is something on which an operation is performed. So if there is some operation which cannot be performed on some resource, then, I needn't store it. For example user can only be created hence only create user need to be stored.
Currently there are only 4 operations(create, read, update, delete) in the scope of the application, but could increase, like upload could come into picture.
Roles
{
    "role": "admin",
    "display_name": "Administrator",
    "permissions": [
      {
        "operation": "create",
        "resource": "project"
      },
      {
        "operation": "read",
        "resource": "project"
      },
      {
        "operation": "update",
        "resource": "project"
      },
      {
        "operation": "delete",
        "resource": "project"
      }
    ]
}

Roles contain role, the name of role to be displayed on UI and the set of permissions that role has.
I need to send this information to UI using a REST API in a specific format, which would describe whether a specific role can perform an operation on a resource or not using the checked flag and whether a specific operation on a resource is editable or not by using the flag isEditable.
For example the permissions collection doesn't contain an operation delete on resource user, so it should not be editable, hence flag is set to false. Similarly user can be created, hence it is set to true.
 {
    display_name: "System Administrator",
    role: "admin",
    permissions: [
      {
        resource: "user",
        privilages: {
          create: { checked: false, isEditable: true },
          delete: { checked: false, isEditable: false },
          update: { checked: false, isEditable: false },
          read: { checked: false, isEditable: false }
        }
      },
      {
        resource: "project",
        privilages: {
          create: { checked: true, isEditable: true },
          delete: { checked: true, isEditable: true },
          update: { checked: true, isEditable: true },
          read: { checked: true, isEditable: true }
        }
      }
   ]
}

Is it possible to perform this using mongo aggregations? Or do I need to make modifications in my schema, If yes, then what modifications should I make.
Comment: Why don't you just store the desired document into a single collection ? Also, what have you tried ?
Answer: I was able to solve the problem in 3 steps:

Include all the permissions for every role and add a flag called checked. This increased data redundancy but that wasn't a big issue.
Do a group by on resource field in roles collection.
Populate the missing privileges for every resource with isEditable set to false on server side.

I had to traverse the data on server side, but this was the most efficient way I could think of.

Mongo Aggregate Nested Array, Lookup


The Login block has vanished

Question: I haven't changed it in /admin/structure/blocks and it is still there.
All that I can think that I installed a few modules to try them out and then disabled them and maybe that caused it.
In any case, my users can't log in and I am in big trouble.
How to go about debugging the problem?  Thanks.

Update: I am not logged in (I see "Log in or register to post comments"). Even when I load /user/logout the login block is not there (not in the HTML)
The "recent log messages" shows nothing out of the way.
Comment: First check that other blocks are displaying in that region. Maybe you have edited the template file and removed the block region
Comment: Also, check that you're not logged in.  If you are, the block won't show!
Comment: check you ```dblog``` for errors. debug the html to see if anything is hiding it.
Comment: @tecjam +1  I didn't edit the template. The block is the first in its sidebar and the others display
Comment: @Chapabu +1 I tried several browsers also private browsing mode & a different PC. Still the same problem
Comment: @karthik +1 No sign of it in the HTML, so apparently not generated. I am off now to check the dblog. Thanks
Answer: The modules you were experimenting with and then disabled, did you go through the uninstall process?
Also, flush you caches.
I hope that helps.
Comment: +1 and the answer. Whatever was wrong, that fixed it (probably flushing the cache, I would guess).  Thanks for saving my life

The Login block has vanished


Multer Memory Storage to @google-cloud/storage doesn't complete

Question: I have an Express route that connects to my google-storage bucket and uploads an image. I've tried to stick close to Googles code samples, but go from multer buffer straight to the bucket.
The process appears to complete without returning en err. However, the file appears in the bucket with 0B size. So it seems the meta data arrives but the image buffer does not...??
Can anyone see what I'm doing wrong?
If possible, I'd like to get this to work without the aid of additional NPM help packages like multer-cloud-storage and all the other variants.

const Multer = require("multer");
const multer = Multer({
    storage: Multer.MemoryStorage,
    fileSize: 5 * 1024 * 1024
  });
const {Storage} = require('@google-cloud/storage');
const storage = new Storage({
    projectId: 'project-name',
    keyFile: '../config/project-name.json'
    });

const bucket = storage.bucket('bucket-name');

app.post('/upload', multer.single('file'), function (req, res) {

    const blob = bucket.file(req.file.originalname);
    const blobStream = blob.createWriteStream({
        metadata: {
            contentType: req.file.mimetype
        },
        resumable: false
    });
    blobStream.on('error', err => {
        next(err);
        console.log(err);
        return;
    });
    blobStream.on('finish', () => {
        blob.makePublic().then(() => {
            res.status(200).send(`Success!`);
        })
    })
    blobStream.end();
})

Comment: I don't see anywhere in your code that actually writes to the blobStream.
Comment: I *thought* blob.createWriteStream() inherits the req.file.buffer object, no? The way it's described here suggests it piped in. https://blog.datawheel.us/uploading-to-google-cloud-storage-from-node-js-bcdee76f83bc
Comment: There's no inheriting anything.  You have to be explicit about what to do with a node stream.
Comment: Thanks @DougStevenson. I'm clearly out of my depth. How does one pipe the multer memorystore buffer into createWriteStream() ?
Answer: Node's native stream did not work for me. So, streamifier it is.
An Express route that pipes an uploaded image from Multer MemoryStorage to a GCS bucket, bypassing the persisting to disk.
Given this is Googles recommended pattern, I was disappointed at the incompleteness of their code examples and the weak answers here on SO.
    // npm streamifier
    const streamifier = require('streamifier');
    // npm multer
    const Multer = require("multer");
    const multer = Multer({
        storage: Multer.MemoryStorage,
        fileSize: 5 * 1024 * 1024
      });
    // Google Cloud Storage GCS
    const {Storage} = require('@google-cloud/storage');
    const storage = new Storage({
        projectId: 'my-project',
        keyFile: 'my-project.json'
        });
    const bucket = storage.bucket('my-bucket');

    // Express Route Hendler
    app.post('/upload', multer.single('file'), function (req, res) {
        // grab original file name out of multer obj
        const blob = bucket.file(req.file.originalname);
        // create the GCS stream handler
        const blobStream = blob.createWriteStream()
        // Yuck...
        return new Promise((resolve, reject) => {
                streamifier.createReadStream(req.file.buffer)
                    .on('error', (err) => {
                        return reject(err);
                    })
                    .pipe(blobStream)
                    .on('finish', (resp) => {
                       res.send('done')
                    });
            })
    }); //end route

Answer: You're defining and opening the stream, but not writing anything to it.
If you don'tn want the small overhead of multer-cloud-storage, I'd suggest to look at src/index.ts file. The _handleFile function handles all the writing tasks. The magic happens on
file.stream.pipe(blobStream)
  .on('error', (err) => cb(err))
  .on('finish', (file) => {
    const name = blob.metadata.name;
    const filename = name.substr(name.lastIndexOf('/')+1);
    cb(null, {
        bucket: blob.metadata.bucket,
        destination: this.blobFile.destination,
        filename,
        path: `${this.blobFile.destination}${filename}`,
        contentType: blob.metadata.contentType,
        size: blob.metadata.size,
        uri: `gs://${blob.metadata.bucket}/${this.blobFile.destination}${filename}`,
        linkUrl: `https://storage.cloud.google.com/${blob.metadata.bucket}/${this.blobFile.destination}${filename}`,
        selfLink: blob.metadata.selfLink,
                        })
});

Answer: I was using a similar approach to upload to GCS without third party lib. But, after a wile, a noticed a huge amount of memory usage by node that wasn't garbage collected. Sending 20mb file with Multer.MemoryStorage was resulting in +20MB allocated to my node process and so on.
To fix this, I've made my own Multer storage engine (based on 3rd party packages), to pipe files received direct to GSC stream.
The final code is:
import { Request } from "express";
import { v4 as uuid } from "uuid";
import { Bucket, Storage } from "@google-cloud/storage";
import multer from "multer";

export default class MulterGoogleCloudStorage implements multer.StorageEngine {
  private gcsBucket: Bucket;

  private gcsStorage: Storage;

  private blobFile = {
    filename: ""
  };

  private setBlobFile(req: Request, file: Express.Multer.File) {
    const ext = file.mimetype.split("/")[1].split(";")[0];
    const filename = `${uuid()}_${file.originalname || `.${ext}`}`;

    this.blobFile.filename = filename
      .replace(/^\.+/g, "")
      .replace(/^\/+/g, "")
      .replace(/\r|\n| /g, "_");

    return true;
  }

  constructor() {
    this.gcsStorage = new Storage({
      projectId: process.env.GCLOUD_PROJECT!,
      keyFilename: process.env.GCLOUD_KEYFILE!
    });

    this.gcsBucket = this.gcsStorage.bucket(process.env.GCLOUD_BUCKET!);
  }

  _handleFile = (
    req: Request,
    file: Express.Multer.File,
    cb: (error: Error | null, info?: Partial<Express.Multer.File>) => void
  ): void => {
    if (this.setBlobFile(req, file)) {
      const blobName = this.blobFile.filename;
      const blob = this.gcsBucket.file(blobName);

      const blobStream = blob.createWriteStream();
      file.stream
        .pipe(blobStream)
        .on("error", err => cb(err))
        .on("finish", () => {
          const { name } = blob.metadata;
          cb(null, {
            filename: name,
            size: blob.metadata.size
          });
        });
    }
  };

  _removeFile = (req: Request, file: Express.Multer.File): void => {
    if (this.setBlobFile(req, file)) {
      const blobName = this.blobFile.filename;
      const blob = this.gcsBucket.file(blobName);
      blob.delete();
    }
  };
}

export function storageEngine(): MulterGoogleCloudStorage {
  return new MulterGoogleCloudStorage();
}

Usage:
import multer from "multer";
import MulterGoogleCloudStorage from "../helpers/MulterGoogleCloudStorage";

const upload = multer({
  storage: new MulterGoogleCloudStorage()
});

app.post("/upload", upload.array("medias"), mycontroller.store);

...


How to create a array of arraylist in android

Question:     ArrayList<String> parsedPODAY_ID=new ArrayList<>();
    ArrayList<String> parsedPODAY_P_IMG=new ArrayList<>();
    ArrayList<String> parsedPODAY_NAME=new ArrayList<>();
    ArrayList<String> parsedPODAY_PRICE=new ArrayList<>();
    ArrayList<String> parsedPODAY_OFFPRICE=new ArrayList<>();

I have created arraylist.But how can i create a arraylist or array of these arraylist.
Thanks in advance!!
Comment: You might want to consider a different data structure to perform the task. There are Object arrays, Object[]. But this gets complicated with generics.
Comment: Try having a reference of type at ArrayList arrayOfArrays
Comment: Use `LinkedHashMap>`. **Don't** use `ArrayList>`, it is considered bad programming practice and is too complicated.
Answer: Simply use
  ArrayList<ArrayList<String>> parent = new ArrayList<>();

add like
parent.add(parsedPODAY_OFFPRICE);

Comment: @MohitGaur Welcome happy coding :)
Answer: Try following
ArrayList<ArrayList<String>> mainArrayList = new ArrayList<ArrayList<String>>();

ArrayList<String> subOneArray = new ArrayList<String>();
subOneArray.Add("first");
subOneArray.Add("second");

ArrayList<String> subTwoArray = new ArrayList<String>();
subTwoArray.Add("first");

mainArrayList.Add(subOneArray);
mainArrayList.Add(subTwoArray);

above code will bit complicated when change made, another way is
 // create map to store
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        // create list one and store values
        List<String> valSetOne = new ArrayList<String>();
        valSetOne.add("Apple");
        valSetOne.add("Aeroplane");
        // create list two and store values
        List<String> valSetTwo = new ArrayList<String>();
        valSetTwo.add("Bat");
        valSetTwo.add("Banana");
        // create list three and store values
        List<String> valSetThree = new ArrayList<String>();
        valSetThree.add("Cat");
        valSetThree.add("Car");
        // put values into map
        map.put("A", valSetOne);
        map.put("B", valSetTwo);
        map.put("C", valSetThree);
        // iterate and display values
        System.out.println("Fetching Keys and corresponding [Multiple] Values n");
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<String> values = entry.getValue();
            System.out.println("Key = " + key);
            System.out.println("Values = " + values + "n");
        }


Temporal Convolution Network for stage classification confusion

Question: Using the TCN architecture provided in the repository here, in pytorch, I am trying to do multiclass classification this dataset.
I have the following architecture: (will be abstracting some parts, that are the same as in the docs)
This is the temporal block:
class TemporalBlock(nn.Module):
def __init__(self, n_inputs, n_outputs, kernel_size, stride, dilation, padding, dropout=0.2):
    super(TemporalBlock, self).__init__()
    self.conv1 = weight_norm(nn.Conv1d(n_inputs, n_outputs, kernel_size,
                                       stride=stride, padding=padding, dilation=dilation))
    self.chomp1 = Chomp1d(padding)
    self.relu1 = nn.ReLU()
    self.dropout1 = nn.Dropout(dropout)

    # changed n_outputs to n_inputs, first param
    self.conv2 = weight_norm(nn.Conv1d(n_outputs, n_outputs, kernel_size,
                                       stride=stride, padding=padding, dilation=dilation))
    self.chomp2 = Chomp1d(padding)
    self.relu2 = nn.ReLU()
    self.dropout2 = nn.Dropout(dropout)

    self.net = nn.Sequential(self.conv1, self.chomp1, self.relu1, self.dropout1,
                             self.conv2, self.chomp2, self.relu2, self.dropout2)
    self.downsample = nn.Conv1d(n_inputs, n_outputs, 1) if n_inputs != n_outputs else None
    self.relu = nn.ReLU()
    self.init_weights()

And this is the network:
class TemporalConvNet(nn.Module):
def __init__(self, num_inputs, num_channels, kernel_size=200, dropout=0.2):
    super(TemporalConvNet, self).__init__()
    layers = []
    num_levels = len(num_channels)
    for i in range(num_levels):
        dilation_size = 2 ** i
        in_channels = num_inputs if i == 0 else num_channels[i-1]
        out_channels = num_channels[i]
        layers += [TemporalBlock(in_channels, out_channels, kernel_size, stride=1, dilation=dilation_size,
                                 padding=(kernel_size-1) * dilation_size, dropout=dropout)]
    self.network = nn.Sequential(*layers)

This is the final module that I use using the aforementioned network:
class TCN(nn.Module):
def __init__(self, input_size, output_size, num_channels, kernel_size, dropout):
    super(TCN, self).__init__()
    self.tcn = TemporalConvNet(input_size, num_channels, kernel_size, dropout=dropout)
    self.linear = nn.Linear(num_channels[-1], output_size)
    self.sig = nn.Sigmoid()

def forward(self, x):
    output = self.tcn(x)
    output = self.linear(output[:, :, -1])
    return self.sig(output).double()

And I initialize the model as follows:
    model = TCN(input_size, output_size, num_channels=[6]*30, kernel_size=125, dropout=0.25)

However, I have doubts regarding the TCN class, and whether I should use sigmoid as I have done in the output. This is how I train it:
size = 10
    total_loss_s = 0
    train_acc_s = 0
    count = 0
    perm = np.random.permutation(train_x.shape[0])
    criterion = torch.nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), betas=(0.9, 0.999), lr=1e-3, weight_decay=0)
    for i in np.arange(0, train_x.shape[0], size):
        x, y = train_x[perm[i:i + size]], train_y[perm[i:i + size]]
        torch.cuda.empty_cache()
        optimizer.zero_grad()
        output = model(x)
        train_loss = criterion(output, torch.max(y, 1)[1])
        train_acc = multi_acc(output, torch.max(y, 1)[1])
        train_loss.backward()
        optimizer.step()
        total_loss_s += train_loss.item()
        train_acc_s += train_acc
        count += output.size(0)
        if i > 0 and i % 100 == 0:
            cur_loss = total_loss_s / count
            total_loss_s = 0.0
            count = 0

Is there something that I have done wrong in the architecture or training step that someone else can see better? Any help is appreciated!!
And the accuracy I get is low compared to when I only use CNN.
Answer: Its not advisable to use a sigmoid as activation function for your multiclass-classification scenario. If you would have only two classes sigmoid would be fine since the output space of sigmoid is $\text{sigmoid}(x) \in (0,1)$ and therefore a valid probability. Now you can use this probability as the probability for the positive class and $1 - \text{sigmoid}(x)$ as the probability for the negative class. This is however not possible if you have more than 2 classes, i.e. your not in a binary-classification setting anymore.
For this case you should use the softmax function as activation for your output layer. It scales all of your 4 outputs to valid probabilities. This is important since the loss of your network will be calculated using cross-entropy, which can only work correct if the sum of your output probabilities are valid, i.e. they sum up to $1$. This is ensured by the softmax function.


Additional PlanningEntity in CloudBalancing - bounded-space situation

Question: I successfully amended the nice CloudBalancing example to include the fact that I may only have a limited number of computers open at any given time (thanx optaplanner team - easy to do). I believe this is referred to as a bounded-space problem. It works dandy.
The processes come in groupwise, say 20 processes in a given order per group. I would like to amend the example to have optaplanner also change the order of these groups (not the processes within one group). I have therefore added a class ProcessGroup in the domain with a member List<Process>, the instances of ProcessGroup being stored in a List<ProcessGroup>. The desired optimisation would shuffle the members of this List, causing the instances of ProcessGroup to be placed at different indices of the List List<ProcessGroup>. The index of ProcessGroup should be ProcessGroup.index.
The documentation states that "if in doubt, the planning entity is the many side of the many-to-one relationsship." This would mean that ProcessGroup is the planning entity, the member index being a planning variable, getting assigned to (hopefully) different integers. After every new assignment of indices, I would have to resort the list List<ProcessGroup in ascending order of ProcessGroup.index. This seems very odd and cumbersome. Any better ideas?
Thank you in advance!
Philip.
Comment: Would you mind including an napkin UML drawing of your class diagram in the question? In reading text that second paragraph is hard to grok.
Comment: @Geoffrey: I have put the intended UML class drawing in https://imageshack.com/i/ex3lg4p5j.  Basically, all I want to do is to amend the sequence of processes as they are stored in a list 'processList = List'- just not by process, but by groups of processes.
Comment: Thanks. Please explain the purpose of the ProcessGroup constraint more tangibly in the question (see my guessing answer below).
Comment: I have now explained the constraint more clearly (I hope).
Answer: The current design has a few disadvantages:

It requires 2 (genuine) entity classes (each with 1 planning variable): probably increases search space (= longer to solve, more difficult to find a good or even feasible solution) + it increases configuration complexity. Don't use multiple genuine entity classes if you can avoid it reasonably.
That Integer variable of GroupProcess need to be all different and somehow sequential. That smelled like a chained planning variable (see docs about chained variables and Vehicle Routing example), in which case the entire problem could be represented as a simple VRP with just 1 variable, but does that really apply here?

Train of thought: there's something off in this model:

ProcessGroup has in Integer variable: What does that Integer represent? Shouldn't that Integer variable be on Process instead? Are you ordering Processes or ProcessGroups? If it should be on Process instead, then both Process's variables can be replaced by a chained variable (like VRP) which will be far more efficient.
ProcessGroup has a list of Processes, but that a problem property: which means it doesn't change during planning. I suspect that's correct for your use case, but do assert it.

If none of the reasoning above applies (which would surprise me) than the original model might be valid nonetheless :)
Comment: Yes, the current design certainly has these disadvantages. The problem does indeed smell like chain spirit... It is a great idea to substitute this awkward 'Integer index' solution with a chained variable approach, I hadn't thought of that. The only disadvantage of the chained approach is that I would have to chose an anchor (like 'Domicile'), which is a bit quirky.  I will try implementing the problem as one genuine entity class 'Process' and one normal class 'ProcessGroup', the former having the PlanningVariable 'Computer', the latter having a chained variable a la 'previousStandstill'. Thx


Zero inflated correlation

Question: What is the best way to correlate zero-inflated count variables with a small sample size (n=~50 and N=99)?
Comment: You may need to provide more information. What do you mean by correlate? What are n and N?
Comment: This question only makes sense if the males and females are couples.  If not (and it seems unlikely with delinquency counts), perhaps "correlate" is the wrong term and the user really wanted to know about how to model a count variable as response and a factor (sex) as an explanatory variable.
Comment: How did you solve this problem? I have the same issue, but with ceiling values inflation.
Comment: By correlate, I mean a measure of association - something like pearson's r. N and n were typos; I just meant I have two sample sizes. So, for one variable, I have 50 males and 50 females and I want to correlate their scores together. For another variable, I have 99 males and 99 females and I want to correlate their scores. My variables are measures of delinquency counts, which are relatively rare events. Thanks so much for your response!!
Answer: There are many nonparametric measures of relation. There is even a whole book on the subject *Nonparametric Measures of Association*by Gibbons, which is one of the "green books" series from Sage, although I have not read this book.  Agresti, in Categorical Data Analysis, has excellent coverage of these.
For count data with a lot of 0's, you could use one of the ordinal measures.
Answer: If there are not too many non-zero values, why not simply present the cross-table? Or graphically, the two bar charts?
@Peter -- the description of the book Nonparametric Measures of Association on Amazon mentions that it is for ordinal data, and you too mention using ordinal methods for count data. But are they really sufficiently similar?
Comment: Certainly count data are ordinal. They are also interval. However, when a lot of the entries are 0, then the interval level measures don't seem to be ideal. You more or less acknowledge this, implicitly, by suggesting a cross table.

Zero inflated correlation


Angular2 Renderer: Svg rect is rendered but not showing in page

Question: I want to create a bar chart using SVG with rect as the bar.
The related code as follows:
barchart-one.html
   <svg #svgone width="400" height="250" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 250">
    <g #abcd></g>
</svg>

barchart-one.ts
 import { Component, Renderer2, ViewChild, ElementRef } from '@angular/core';

    @Component({
    selector: 'barchart-one',
    templateUrl: 'barchart-one.html'
    })
    export class BarchartOneComponent {
    @ViewChild('abcd')
    private abcd: ElementRef;
    constructor(private renderer: Renderer2) {}

    ngAfterViewInit() {
        for (var i = 1; i < 8; i++) {
            let height = Math.floor(Math.random() * (140 - 110)) + 110;
            const rect = this.renderer.createElement('rect');
            this.renderer.setAttribute(rect, 'height', height);
            this.renderer.setAttribute(rect, 'rx', '6');
            this.renderer.setAttribute(rect, 'ry', '6');
            this.renderer.setAttribute(rect, 'width', '12');
            this.renderer.setAttribute(rect, 'x', (i*50)+20);
            this.renderer.setAttribute(rect, 'y', (220-height));
            this.renderer.appendChild(this.abcd.nativeElement, rect);
            console.log(rect);
        };
    }
    }

Result of svg render:
<g>

<rect height="126" rx="6" ry="6" width="12" x="70" y="94"></rect>
<rect height="122" rx="6" ry="6" width="12" x="120" y="98"></rect>
<rect height="124" rx="6" ry="6" width="12" x="170" y="96"></rect>
<rect height="116" rx="6" ry="6" width="12" x="220" y="104"></rect>
<rect height="139" rx="6" ry="6" width="12" x="270" y="81"></rect>
<rect height="123" rx="6" ry="6" width="12" x="320" y="97"></rect>
<rect height="137" rx="6" ry="6" width="12" x="370" y="83"></rect>
</g>

The expected result is not showing in page even though the code for rect is correctly rendered.
Answer: You cannot create SVG elements with createElement, you must use createElementNS and pass the SVG namespace i.e. http://www.w3.org/2000/svg as the first parameter.
this.renderer.createElementNS('http://www.w3.org/2000/svg', 'rect');

Comment: Can you provide some example.
Answer: This is old question, but, maybe someone will find it useful in the future. There is an Angular module called ngx-svg, which allows to create easily multiple SVG elements and plot them on the site. Also lot of different interactions with these elements are available.
Your html code would look like this -
<svg-container containerId="barChart" height="500">
  <svg-rect height="126" width="12" color="#000" x="70" y="94"></svg-rect>
  <svg-rect height="122" width="12" color="#000" x="120" y="98"></svg-rect>
  <svg-rect height="124" width="12" color="#000" x="170" y="96"></svg-rect>
  <svg-rect height="116" width="12" color="#000" x="220" y="104"></svg-rect>
  <svg-rect height="139" width="12" color="#000" x="270" y="81"></svg-rect>
  <svg-rect height="123" width="12" color="#000" x="320" y="97"></svg-rect>
  <svg-rect height="137" width="12" color="#000" x="370" y="83"></svg-rect>
</svg-container>

The above code, would automatically create and plot your desired chart.


Calculate most common value, amount of times it occurs and without using reoccurring values

Question: This is basically a statistics script for website visitors. I have a very simple table like this:
website_ref  |  ip_address  |  city  |  page_viewed
abc              12.13.14     London     index.php
abc              12.13.14     London     contact.php
abc              12.13.14     London     about.php
abc              10.16.19     Paris      index.php
abc              33.33.33     Paris      about.php
abc              44.42.32     London     index.php
abc              09.09.09     Paris      images.php

There's more information at play here but not relevant for this question. What I am trying to do is calculate the most common city for the website ref by visitors. Now looking at the table above you may think London, as does my current script. But it is incorrect for my requirements as the IP addresses are the same for London, in fact, the top city should be Paris at it is the most common value with different IP Addresses. I hope you understand what I am trying to accomplish. I would also prefer that the statement could count the results too, so it would show as:
Most common: Paris (3/5)

5 being the total distinct IP Address visitors (which I can already figure out). Here is what I am using at the moment:
$getCITY = mysqli_fetch_assoc(mysqli_query($conn, "SELECT city, COUNT(city) as count FROM all_website_stats WHERE website_ref = '$website_ref' GROUP BY city ORDER BY COUNT(city) DESC LIMIT 1"));

$getCITY = $getCITY['city'];

$getCOUNT = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(distinct ip_address) as count FROM all_website_stats WHERE website_ref = '$website_ref' AND `city` = '$getCITY'"));
$getCOUNT = $getCOUNT['count'];

I hope somebody can help me out here.
Answer: I would run this query:
select city, count(distinct ip_address) as ips,
(
    SELECT count(distinct ip_address)
    from all_website_stats where website_ref = 'abc'
) as total
from all_website_stats
where website_ref = 'abc'
group by city
order by ips desc
limit 1

To get the following result:
city   | ips | total
Paris  | 3   |  5

Live demo
Comment: Worked perfect and I'm glad it was all 3 in one single code, makes things much easier to handle. The live demo was a lot of help as well. Thanks for the help.
Comment: @Snappysites **


What is the equivalent of MySQL @currant := @currank + 1 in MS SQL?

Question: This is the main MySQL script I try to convert this following script into MS SQL script. I don't know the equivalent.
SELECT
        (SELECT
                COALESCE(transaction_price, 0)
            FROM
                (SELECT
                    COALESCE(transaction_price, 0) AS TRANSACTION_PRICE, COALESCE(actual_size, 0) AS ACTUAL_SIZE, @currank = @currank + 1 AS rank
                FROM
                    dw_property_detail p, (SELECT @currank:=0) r
                WHERE
                    land_id = 2 AND transaction_price IS NOT NULL AND flat_type = 'Studio'
                ORDER BY transaction_price DESC) x
            WHERE
                x.rank = 1) AS TRAN_S,
        (SELECT
                COALESCE(per_ft_s, 0)
            FROM
                (SELECT
                    COALESCE(transaction_price / actual_size, 0) AS PER_FT_S, @currank:=@currank + 1 AS rank
                FROM
                    dw_property_detail p, (SELECT @currank:=0) r
                WHERE
                    land_id = 2 AND transaction_price IS NOT NULL AND flat_type = 'Studio'
                ORDER BY COALESCE(transaction_price / actual_size, 0) DESC) x
            WHERE
                x.rank = 1) AS PER_FT_S

What is the equivalent of @currank := @currank + 1 and SELECT @currank := 0?
Comment: What is this query supposed to do? Can you share some sample data and the result the query produces?
Comment: Ok I will update the MySQL query. Please see.
Answer: ROW_NUMBER  (window/analytic function - feature that currently is not supported by MySQL)
https://msdn.microsoft.com/en-us/library/ms186734.aspx
Add it to the SELECT clause as an additional column.
You won't need now the query's ORDER BY, for that purpose (but do keep it if you want ordered results)
row_number() over (order by transaction_price desc)

SELECT      COALESCE(transaction_price, 0)                          AS TRANSACTION_PRICE
           ,COALESCE(actual_size, 0)                                AS ACTUAL_SIZE
           ,row_number () over (order by transaction_price DESC)    AS rank

FROM        dw_property_detail p

WHERE       land_id     = 2
        AND flat_type   = 'Studio'
        AND transaction_price IS NOT NULL

ORDER BY    transaction_price DESC

Comment: Can you do me sample I get lost. I don't understand. :P
Comment: Check the examples at the bottom of the added link
Comment: can you simplify my script?
Comment: oops, it only return 2 column TRAN_S and PER_FT_S but yours is return 3 column transaction_price, actual_price, and rank
Comment: It is just the sub-query part, not the whole query
Comment: I don't understand. Honestly, I am a newly in TSQL. Can you update the whole?


Maven repository server for caching

Question: I'm trying to understand some concepts about maven. This is the my scenario:
Almost every time I deploy a project, i.e Cloudstack I type:
mvn install

I got some failures like unable to connect to some repositories or that some tests just failed. I don't understand why some tests can fail if the code has been recently downloaded.
My idea is to create a local server repository so maven won't connect to remote servers but to a server that is in the same network with the packages that the application needs.
Is possible to do that? or does these problems are produced by other cause?
Comment: Can you post some of the errors you get?
Answer: See Maven, Introduction to Repositories:

There are strictly only two types of repositories: local and remote. The local repository refers to a copy on your own installation that is a cache of the remote downloads, and also contains the temporary build artifacts that you have not yet released.
Remote repositories refer to any other type of repository, [...]. These repositories might be a truly remote repository set up by a third party to provide their artifacts for downloading [...]. Other "remote" repositories may be internal repositories set up on a file or HTTP server within your company, used to share private artifacts between development teams and for releases.

mvn install does not deploy your project's artifact (at least not in the sense of Maven's deploy, see Introduction to the Build Lifecycle). It does:

install the package into the local repository, for use as a dependency in other projects locally

whereas mvn deploy is:

done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects

"unable to connect to some repositories" and "some tests just failed" are two different kind of errors. It's impossible to tell more without any relevant part(s) of the output of the build where these occurred.

Maven repository server for caching


Vídeo perde tamanho dentro de div com uso de resolution slider

Question: Estou utilizando Revolution Slider e ao fazer a transição de vídeos pelo o Carousel, o vídeo perde o tamanho predefinido ao qual determinei para a minha página de exibição, ou seja, determino o width:auto e height:768px, mas ao realizar a transição, esses vídeos perdem a altura 768 e ficam ajustados pelo width e 'height' automático da resolução do meu monitor. Já tentei ajustar com CSS, JS e HTML, mas nada funcionou.
Alguém tem alguma solução?

<link rel="stylesheet" type="text/css" href="rs-plugin/css/settings.css" media="screen" />

                <div class="tp-caption tp-fade fadein fullscreenvideo"
                         data-x="0"
                         data-y="0"
                         data-speed="50"
                         data-start="500"
                         data-easing="Power4.easeOut"
                         data-endspeed="1500"
                         data-endeasing="Power4.easeIn"
                         data-autoplay="true"
                         data-nextslideatend="true"
                         data-forceCover="1"
                         data-dottedoverlay="twoxtwo"
                         data-aspectratio="16:9"
                         data-forcerewind="on"
                         style="z-index: 5">

                        <video class="video-js vjs-default-skin"
                               preload="none"
                               poster="videos/cybersecurity.jpg"
                               width="100%"
                               height="100%"
                               data-setup="{}">
                               <source src="videos/cybersecurity.webm" type="video/webm" />
                        </video>

                <div class="tp-caption tp-fade fadein fullscreenvideo"
                         data-x="0"
                         data-y="0"
                         data-speed="50"
                         data-start="500"
                         data-easing="Power4.easeOut"
                         data-endspeed="1500"
                         data-endeasing="Power4.easeIn"
                         data-autoplay="true"
                         data-nextslideatend="true"
                         data-forceCover="1"
                         data-dottedoverlay="twoxtwo"
                         data-aspectratio="16:9"
                         data-forcerewind="on"
                         style="z-index: 5">

                        <video class="video-js vjs-default-skin"
                               preload="none"
                               poster="videos/servers.jpg"
                               width="100%"
                               height="100%"
                               data-setup="{}">
                               <source src="videos/servers.webm" type="video/webm" />
                        </video>

                    <div class="tp-caption tp-fade fadein fullscreenvideo"
                         data-x="0"
                         data-y="0"
                         data-speed="50"
                         data-start="500"
                         data-easing="Power4.easeOut"
                         data-endspeed="1500"
                         data-endeasing="Power4.easeIn"
                         data-autoplay="true"
                         data-nextslideatend="true"
                         data-forceCover="1"
                         data-dottedoverlay="twoxtwo"
                         data-aspectratio="16:9"
                         data-forcerewind="on"
                         style="z-index: 5">

                        <video class="video-js vjs-default-skin"
                               preload="none"
                               poster="videos/process_imagem.jpg"
                               width="100%"
                               height="100%"
                               data-setup="{}">
                            <source src="videos/process_low.webm" type="video/webm" />
                        </video>

                    <div class="tp-caption tp-fade fadein fullscreenvideo"
                         data-x="0"
                         data-y="0"
                         data-speed="50"
                         data-start="500"
                         data-responsive_offset="on"
                         data-easing="Power4.easeOut"
                         data-endspeed="1500"
                         data-endeasing="Power4.easeIn"
                         data-autoplay="true"
                         data-nextslideatend="true"
                         data-forceCover="1"
                         data-dottedoverlay="twoxtwo"
                         data-aspectratio="16:9"
                         data-forcerewind="on"
                         style="z-index: 5">

                        <video class="video-js vjs-default-skin"
                               preload="none"
                               poster="videos/cloud_computing.jpg"
                               width="100%"
                               height="100%"
                               data-setup="{}">
                            <source src="videos/cloud_computing1.webm" type="video/webm" />
                        </video>

                <div class="tp-caption tp-fade fadein fullscreenvideo"
                         data-x="0"
                         data-y="0"
                         data-speed="50"
                         data-start="500"
                         data-easing="Power4.easeOut"
                         data-endspeed="1500"
                         data-endeasing="Power4.easeIn"
                         data-autoplay="true"
                         data-nextslideatend="true"
                         data-forceCover="1"
                         data-dottedoverlay="twoxtwo"
                         data-aspectratio="16:9"
                         data-forcerewind="on"
                         style="z-index: 5">

                        <video class="video-js vjs-default-skin"
                               preload="none"
                               poster="videos/ambiente_imagem.jpg"
                               width="100%"
                               height="100%"
                               data-setup="{}">
                               <source src="videos/ambiente_low.webm" type="video/webm" />
                        </video>

segue abaixo duas telas do comportamento apresentado

vocês conseguem perceber a diferença de imagens ao olhar para as flechas do carousel (em vermelho)
css utilizado nos
.bannercontainer {
    width:100%;
    position:relative;
    padding:0;
}
.banner{
    width:100%;
    height: 768px;
    position:relative;
    padding:0;
}
Comment: Tem como criar um [mcve]?
Comment: Essa informação não me parece ajudar em nada. Tem como você [edit] a pergunta e adicionar o código que gera esse comportamento? Principalmente que seja verificável, isto é, que nós possamos executar em nossas máquinas ou emuladores e verificar o problema em ação.
Comment: Foco no conteúdo dos comentários: [edit] é um link. Use-o.
Answer: Problema solucionado, na biblioteca própria (jquery.themepunch.revolution.js - jQuery Plugin for Revolution Slider ) existe o default dos valores de height e width:
(function(jQuery,undefined){

    ////////////////////////////////////////
    // THE REVOLUTION PLUGIN STARTS HERE //
    ///////////////////////////////////////

    jQuery.fn.extend({

        // OUR PLUGIN HERE :)
        revolution: function(options) {

                ////////////////////////////////
                // SET DEFAULT VALUES OF ITEM //
                ////////////////////////////////
                defaults = {
                    delay:9000,
                    startheight:768, /* default = 500 */
                    startwidth: vimeoready_auto,  /* default = 960 */
                    fullScreenAlignForce:"off",
                    autoHeight:"off",
                    hideTimerBar:"off",
                    hideThumbs:200,
                    hideNavDelayOnMobile:1500,


SVG não ajusta o tamanho

Question: Não tenho muita experiência com SVG, e acho bem confuso a forma de trabalhar com essas imagens, eu preciso deixar essa imagem com o tamanho de 35x35 px.
Exportei o código no illustrator de uma imagem SVG de 512x512px, quero trabalhar com ela de forma responsiva, mas não consigo manipular o tamanho dela por CSS de jeito nenhum.
    <svg width="35" height="35" viewbox="0 0 35 35">

        <path d="M256,0C114.609,0,0,114.609,0,256s114.609,256,256,256s256-114.609,256-256S397.391,0,256,0z M256,472
c-119.297,0-216-96.703-216-216S136.703,40,256,40s216,96.703,216,216S375.297,472,256,472z M325.906,306.188c-16-2.734-37.906-18.25-37.906-24.984v-17.016c0-6.344,8.594-18.219,12.25-29.156
c0.344-1.031,2.547,0.156,4.688-2.453c4.031-4.969,4.625-12.516,5.547-15.953c1.469-5.406-5.094-5.625-5.094-5.625
s4.891-28.375,0.547-46.297c-5.875-24.406-37.5-36.703-49.875-36.703c-12.391,0-43.969,12.297-49.875,36.703
c-4.344,17.922,0.656,46.297,0.656,46.297s-6.328,0.219-4.875,5.625c0.938,3.438,1.969,10.984,6.031,15.953
c2.125,2.609,3.406,1.422,3.75,2.453c3.656,10.938,12.25,22.812,12.25,29.156v17.016c0,6.734-21.922,22.25-37.922,24.984
c-20.547,3.5-30.703,17.703-25.891,53.125c2.406,17.688,49.094,25.297,95.344,24.641c46.25,0.656,93.641-6.953,96.047-24.641
C356.406,323.891,346.469,309.688,325.906,306.188z"/>

    </svg>

Comment: Para a maioria dos casos, precisa setar o parâmetro "preserveAspectRatio". Consulte esse tópico: http://pt.stackoverflow.com/questions/75877/tornar-svg-responsivo
Comment: preserveAspectRatio não tem efeito sem viewBox... e, mais uma vez, líquido não é responsivo...  Outro ponto, "preserveAspectRatio", mesmo sem especificar, possui o valor padrão "xMidYMid meet". Por isso, a "falsa" impressão de que não necessita.
Answer: Primeiro, remova a largura (width) e altura (height) do elemento SVG.
Depois disso determine uma viewBox relativo a imagem no seu caso viewbox="0 0 512 512".
Com isso basta para assegurar que ele possua o tamanho máximo de onde se encontrar, basta definir no CSS o width como máximo (ou 100%). Assim, a imagem vai adquirir o tamanho máximo de onde você adicionar.
Como no seu caso você quer aplicar um tamanho específico (35px), basta definir a altura e largura com essa medida ou qualquer outra que você queira.
Após isso seu código ficará da seguinte forma:

svg {
  width: 35px;
  height: 35px;
}
<svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512">
  <path d="M256,0C114.609,0,0,114.609,0,256s114.609,256,256,256s256-114.609,256-256S397.391,0,256,0z M256,472
c-119.297,0-216-96.703-216-216S136.703,40,256,40s216,96.703,216,216S375.297,472,256,472z M325.906,306.188c-16-2.734-37.906-18.25-37.906-24.984v-17.016c0-6.344,8.594-18.219,12.25-29.156
c0.344-1.031,2.547,0.156,4.688-2.453c4.031-4.969,4.625-12.516,5.547-15.953c1.469-5.406-5.094-5.625-5.094-5.625
s4.891-28.375,0.547-46.297c-5.875-24.406-37.5-36.703-49.875-36.703c-12.391,0-43.969,12.297-49.875,36.703
c-4.344,17.922,0.656,46.297,0.656,46.297s-6.328,0.219-4.875,5.625c0.938,3.438,1.969,10.984,6.031,15.953
c2.125,2.609,3.406,1.422,3.75,2.453c3.656,10.938,12.25,22.812,12.25,29.156v17.016c0,6.734-21.922,22.25-37.922,24.984
c-20.547,3.5-30.703,17.703-25.891,53.125c2.406,17.688,49.094,25.297,95.344,24.641c46.25,0.656,93.641-6.953,96.047-24.641
C356.406,323.891,346.469,309.688,325.906,306.188z" />
</svg>
Comment: essa técnica não é responsiva, é "fluida" ou "líquida"..
Comment: na pergunta diz "quero trabalhar com ela de forma responsiva"... entendeu?
Comment: Isso não quer dizer "responsivo".. Apenas entenda que responsivo é diferente de líquido/fluido...
Comment: obrigado @natan resolveu meu problema :D
Comment: Pessoal, isso resolve meu problema, não foi exatamente uma técnica responsiva mas resolveu minha questão, muito obrigado a todos vocês pela ajuda.

SVG não ajusta o tamanho


Django: Shut off console output of http response messages

Question: So we made an app with django and it prints all these http response messages on the console everytime it gets a request.
[Date String] 'GET /urlpath/..blah blah ' 200 216
[Date String] 'DELETE /anotherurl/..blah blah ' 200 205
...
..

We have disabled all logger outputs. Set Debug=False. Tried 'python manage.py runserver --verbosity 0'.  Even tried changing sys.stdout to a NullDevice() class.  Yet, we can't seem to turn off these response messages which are slowing the server to a crawl. All other messages get turned off, except these.  Any suggestions?
I realize that the django internal webserver is meant only for development and not for production, but we would like to get a fair amount of speed just with the developmental version itself (without having to go into the intricacies of deploying django behind Apache/lighttpd).
Comment: "... we would like to get a fair amount of speed just with the developmental version itself ..." BWAHAHA.
Comment: I'd like to switch these console outputs off, too, at least the ones with HTTP Result code 200.
Comment: I know printing can be slow but unless you are doing thousands of request per page I really don't think you will benefit from turning these off. And if you are doing thousands of request it will be slow even on proper web server.
Comment: There are good reason to filter out certain messages during developement, especially while debugging, to have requests checking if a page has been updated, constantly bombing your debug session, is pretty much unsuable.
Answer: You can let console logging turned on, but with this small patch You can suppress the noisy lines like
GET /urlpath/..blah blah ' 200 216
...

completely, which all have HTTP result code = 200.
In Your Site-packages or VirtualEnv (if You're using it) directory, go to folder structure django / core / servers / basehttp.py
then goto
Class WSGIRequestHandler,
function def log_message(self, format, *args)
After
# Don't bother logging requests for admin images or the favicon.
if (self.path.startswith(self.admin_media_prefix)
        or self.path == '/favicon.ico'):
    return

Insert
# START ----- Don't show page requests which have run successfully
if args[1] == '200':
    return
# END ----- Don't show page requests which have run successfully

This is a dirty work-around for Python 2.7.3, Django 1.4.3, I am interested in a clean customization, also :-)
Comment: This worked just fine for me. I always hesitate to modify library code, but in this case it seems fully justified. I found I was also interested in preventing `304` responses from being displayed as well; instead of `if args[1] == '200':` I used `if args[1] in ['200', '304',]:`. This answer should be accepted.
Answer: The built-in development server was not designed for performance, instead use gunicorn. You can add it as an app to your Django project and it will make a command run_gunicorn available to you, as an alternative to runserver. It's a fair bit faster and more responsive than the built-in development server. If you want you can also set gunicorn's logging level with --log-level. It's also fairly simple to deploy, and suitable for production.
Comment: It's a bit more complex than that, as gunicorn does not start automatically when making a change to your project's .py files, so you have to set up restarting manually.
Answer: All you need just to Add in Django logging settings:
    'loggers': {
        # django's default logger
        'django.server': {
            'handlers': ['django.server'],
            'level': 'INFO',
            'propagate': False,
        },
    }

you can override Django's default loggers: https://github.com/django/django/blob/32265361279b3316f5bce8efa71f2049409461e3/django/utils/log.py#L18
How Django's default built-in loggers works: https://docs.djangoproject.com/en/1.10/topics/logging/#id3
using custom CallbackFilter filter: https://docs.djangoproject.com/en/1.10/topics/logging/#django.utils.log.CallbackFilter
Comment: This is good information, but I don't understand how to "override Django's default loggers"
Comment: I can't seem to detect these response messages inside a CallbackFilter. When I set a breakpoint inside the callback function, I hit it on every console message except these. If this can really be accomplished with CallbackFilter, a working example would be super helpful.


Selecionar todo o texto textbox

Question: Tenho o seguinte código:
Private Sub nct_focus(sender As Object, e As EventArgs) Handles nCT.GotFocus, nCT.Click
    sender.SelectAll()
End Sub

o que acontece é o seguinte, ele funciona bem, porém tenho uns 40 textboxes no meu form, já dei uma olhada e gostaria de chamar essa função em todos os textboxes do meu form...
alguma forma de fazer isso sem ter que repetir o código toda a vez que incluir um novo textbox?
Answer: Basta adicionar os elementos que terão os eventos tratados (handled) pelo método separando por vírgulas:
Private Sub nct_focus(sender As Object, e As EventArgs) Handles text1.GotFocus, text2.GotFocus, text2.GotFocus.... etc....
    sender.SelectAll()
End Sub

Agora se quiser que automaticamente todos os TextBoxes do seu form tenham o evento associados ao seu método, você pode pesquisar todos os elementos dentro do seu form, na collection Controls, verificar se não do tipo TextBox e associar o evento.
Pode fazer isso ao carregar o form, algo assim:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
   ' Para cada controle, verificar o tipo e associar ao evento
    For Each ctrl As Control In Me.Controls

        If TypeOf ctrl Is TextBox Then
            Dim textBox As TextBox = CType(ctrl, TextBox)
            AddHandler textBox.GotFocus, AddressOf nct_focus
        End If
    Next
End Sub

Comment: Legal, isso me faz lembrar muitas coisas, faz tempo q não trabalho com forms.. boa sorte :)
Comment: do primeiro modo eu já sabia que dava pra fazer, queria algo aproximado com a segunda forma, porem já havia testado dessa forma que você passou, infelizmente não funcionou
Comment: o que não funcionou? ele não associou os eventos, ou associou e não fez o que esperava?
Comment: não associou os eventos, acho que a saída vai ser fazer como na primeira forma
Comment: entendi.... só para confirmar, se converter o sender não funciona? nessa linha `sender.SelectAll()` sender é um Object, não precisa converter para `TextBox`?
Comment: Consegui fazer funcionar, era um erro de análise meu, havia um tabcontrol dentro do meu form, o que fazia com que o evento não fosse adicionado, pois não existia nenhum textbox diretamente no form, mas sim no tabcontrol.

Selecionar todo o texto textbox


Open user's Microsoft Word Application php

Question: I'm building a php application for intranet only use. I'm accessing network drives and listing the files.
Since chrome and FF do not have built-in functions to open Windows Explorer (I know there are extensions available). I was hoping to have php code recognize the file is a word application file (.doc, .docx, etc...) and then launch the user's Microsoft Word Application to open the file.
I've looked into PHPWord, but the documentation is terrible.
Is there a way (other than having each user download an extension) to be able to open a MS Word file using PHP?
Comment: Not using php as requested but: http://stackoverflow.com/questions/2800081/how-to-run-an-external-program-e-g-notepad-using-hyperlink gives a solution.
Comment: It helps - but it will only download the file and not open it. Thank you for the suggestion though.
Answer: PHPWord development is continued in github. Please checkout the latest version of the develop branch.
Answer: It looks like you're just wanting to stream a ms word doc to the browser and have the browser open the document in MS word.  That can be accomplished by setting the content type headers properly and then outputting the contents of the file.
This:
https://www.devside.net/wamp-server/forcing-a-pdf-or-doc-to-open-in-browser-rather-than-downloading
might help
Also, depending on browser and how it is streamed out, you might have an option in the browser to either Open the file, or save the file.  If you set the user's browsers to "open the file" then you are set.


Usar um component dentro de um Shell Console no CakePHP

Question: Alguém sabe me dizer como usar um component que criei no cakephp dentro de um script de console do cake?
Já tentei usar App::import mas não consegui.
Por exemplo em um controller normal eu consigo usar meu component da seguinte maneira:
public $components = array('MeuComponent');

Mas no Shell isso não funciona =/
Alguém sabe me dizer como usar MeuComponent dentro de um Shell do CakePHP?
Answer: Acabei achando a solução aqui
Antes da sua class Shell adicione
App::uses('ComponentCollection', 'Controller');
App::uses('MeuComponentComponent', 'Controller/Component');

class WorkerShell extends AppShell {
    public function main(){
       $Collection = new ComponentCollection();
       $obj = new MeuComponentComponent($Collection);
    }
}

Pronto, já pode usar seu component dentro dos scripts Shell.


A problem on a.s. convergence

Question: I'm preparing for an exam and I came across this problem from old exams. I'm really clueless on how to solve it.
Consider a sequence of random variables $\{X_n\}_{n=1} ^\infty$ defined on the probability space $([0,1],B[0,1],\lambda)$ where $\lambda$ is Lebesgue measure. Define $X_n(\omega) =  1_{[1/2-(2n)^{-1}, 1/2+(2n)^{-1} ]}(\omega)$ for all $\omega \in [0,1]$. Prove that $X_n \xrightarrow{a.s.}0$ as $n \rightarrow \infty$.
Comment: @Cam: Just an aside: Note that Borel-Cantelli does not yield anything useful in this particular case, though a very minor modification to the function would.
Comment: Borel-Cantelli lemma?
Answer: It is not hard to show that for every $\omega \neq \frac12$, $\exists N$ $\colon$ $X_n(\omega)=0$ for all $n \geq N$. Is it clear for you ? Then the conclusion is straightforward.
Comment: @act00 Yes. Convergence for every $\omega \in [0,1/2) \cup (1/2,1]$ implies almost sure convergence because the Borelian set $[0,1/2) \cup (1/2,1]$ has full probability. Proving the convergence for $\omega \neq \frac12$ is not so straightforward but this is an elementary analysis exercise.
Comment: (+1) The convergence proof is elementary: for $\omega\ne 1/2$, let $N$ be any integer greater than $1/|1-2\omega|$. The existence of such an $N$ is guaranteed by the [Archimedean property](http://en.wikipedia.org/wiki/Archimedean_property) of real numbers. An easy algebraic calculation establishes that $X_n(\omega)=0$ for $n\ge N$.
Comment: Thanks! Can we say: $X_n(\omega) \rightarrow 0$ for all $\omega \in [0,1/2) \cup (1/2,1]$ and $\lambda( [0,1/2) \cup (1/2,1]) = 1$. Hence $X_n \xrightarrow{a.s.}0$ as $n \rightarrow \infty$ ?

A problem on a.s. convergence


Calling Main Method from Main Method

Question: This is my first question in this forum.
Hope to have a good experience!
My question is related to Java. In C/C++, sometimes we need to call main() function while being in main() function itself. Can the same thing be done in Java also?
If yes, suggest me some way to do it and also to terminate the program from the second main() call.
i.e.
public static void main(String args[]){
     main();//The question is about this part and also how to get out from this call directly to termination
}

One more thing. I am new to JAVA, so please be as descriptive as you can be.
Thanks for your support in Advance!
Comment: While it's possible, it's probably not necessary. What are you trying to achieve with a recursive call to main()?
Comment: I'm not sure why you would ever want to do this in _any_ language.
Comment: Sounds to me like a bad idea.
Answer: Well it can be done, but you really shouldn't do this ever (in C or C++ either).
All you have to do is call main with an array of Strings.  You could pass in the array as it was initially passed in, or you could generate your own array.
To exit from the recursive call to main, you would call System.exit() passing in some error code.
Again, I want to emphasize that you should probably never ever do this in any programming language. You claim that you sometimes need to do this in C/C++ but that is not true. You really shouldn't do it.
Comment: Thank You @Daniel.
But I'd really like to know why it is not suggested.
Comment: @Neferseti Well first of all, calling main is illegal in C++. The main problem with calling `main` recursively is that it goes against people's expectations. `main` is the entry point to the program, and nothing more. Nobody reading your code would expect `main` to be called any time besides the entry to your code. In any case, the use for recursion is to do a different task from what you are currently doing. If you're just trying to restart your program, that's not a good use for recursion. Just use a loop. Check out [this answer](http://stackoverflow.com/a/7811155/864027) for more details.

Calling Main Method from Main Method


Como mudar conteudo de um select a partir de outro select

Question: Como consigo colocar um botão relacionado com o outro?
Exemplo:
Distrito
<select name="PAIS" size="1" width="180" class="COMBODISTCSS" id="COMBOFAB" tabindex="1">
 <option value="Indiferente">Indiferente</option>
 <option value="Portugal">PORTUGAL</option>
<option value="Brasil">BRASIL</option>
<option value="Espanha">ESPANHA</option>
</select>

e depois tenho outra opção que é os Concelhos.
Concelho
<select name="CIDADE" size="1" width="195" class="COMBOCONCCSS" id="COMBOFAB" tabindex="1">
 <option value="Indiferente">Indiferente</option>
     <option value="Lisboa">Lisboa</option>
     <option value="Porto">Porto</option>
     <option value="Madrid">Madrid</option>
     <option value="Barcelona">Barcelona</option>
     <option value="Brasilia">Brasilia</option>
     <option value="São Paulo">São Paulo</option>

Escolho ESPANHA na primeira opção PAIS e quero que apareça apenas Nas cidades BARCELONA, MADRID, etc.
Comment: Sera necessária o uso do javascript/jQuery
Comment: Com jQuery você consegue fazer isso.
Comment: e como se chama essa função em javascript?
Comment: Você precisaria de um arquivo json com todas os países e com cidades. e depois quando você seleciona-se o país você pegaria o selecionado e fazia a busca dentro do json para trazer as cidades referente ao país, mas acredito que seria grande demais para ser respondido aqui.. mas vou ver o que consigo pra você... aguarde...
Comment: E você já tem o código todo na página ou vai buscar via Ajax?
Comment: Tenho tudo na mesma página.
Comment: Ok. Poste o código que tem e a resposta fica bem fácil.
Comment: Tenho assim. os dois botões de opção.
Answer: A sua pergunta é incompleta. Posso ajudar mais a explicar o que é preciso numa pergunta, ou próximas perguntas, para ser clara para quem quer ajudar. No Meta há de certeza uma pergunta referência mas não a encontro agora.
Ainda assim, fica aqui uma sugestão. Neste código em baixo mudei o seu ID duplicado para o segundo select. ID's têm de ser únicos, e já agora dá jeito ter um ID nesse select.
Adicionei um campo data-pais="" nas suas options. Assim, se todas estiverem no mesmo select dá para as mostrar/esconder.
<option data-pais="Portugal" value="Lisboa">Lisboa</option>
<option data-pais="Portugal" value="Porto">Porto</option>
<option data-pais="Espanha" value="Madrid">Madrid</option>

Acrescentei também CSS, aqui pode optar por retirar este código completamente se quiser que todas as opções estejam disponíveis.
#COMBOCID option{
    display: none;
}

jQuery
$('select[name="PAIS"]').on('change', function(){
    var pais = this.value;
    $('select[name="CIDADE"] option').each(function(){
        var $this = $(this);
        if($this.data('pais') == pais) $this.show();
        else $this.hide();
    });
});

Exemplo: http://jsfiddle.net/XH42p/
Comment: @user3253195, aqui fica uma nova versão: __http://jsfiddle.net/XH42p/__
Answer: Acho que daria pra você usar esse script
<select name="odin" id="odin" onchange="turnTo(this)">
        <option value="Vaca">Vaca</option>
        <option value="Boi">Boi</option>
        <option value="Ovelha">Ovelha</option>
    </select>
    <select name="thor" id="thor">
        <option value=""></option>
        <option value=""></option>
        <option value=""></option>
    </select>


Too many open files error when training in loop

Question: I have a pretty simple setup like this:
while True:
   model.fit(mySeqGen(xx), ..., use_multiprocessing=True, workers=8)
   <stuff>
   model.save_weights(fname)
   gc.collect()

Which runs for a long time, but if left overnight I will find it generating OSError: [Errno 24] Too many open files every loop iteration. The full stack trace is on another machine, but it has multiple references to multiprocessing.
This is surely not related to actual files, but byproducts of threads being created under the hood and not cleaned up properly. Is there a simple way I can make this loop stable over the long run and clean up after itself each pass?
Comment: Could you post the body of the `mySeqGen` function? It's may be happening in there if your generator is streaming data from your file system.
Comment: I can post something soon to give an idea, but it's actually a simulator and does not go to disk in any way.
Comment: I assume you are using keras. Which keras version are you using? Are you sure this is not actually related to too many files being opened and not being properly closed by keras itself? AFAIK `gc.collect()` does not guarantee closing of files.

What is `fname` in your code, which filetype are you saving to?
Comment: Could it be related to sockets? https://stackoverflow.com/questions/39537731/errno-24-too-many-open-files-but-i-am-not-opening-files
Comment: @rvd Yes, I think it is sockets related to the threads.  But how can I force them to close?  Or is this a bug in Tensorflow?  I'm using Tensorflow's keras within TF version 2.5.  No files are ever opened, unless you count the save, but the error stack is all about "../python3.8/multiprocessing/pool.py".  Fname is just the name where I have TF save the weights, "myModelWeights" or something.
Comment: @Mastiff I asked after the filename to see if it is an HDF file object or a '.hdf' string to see if there is a bug in the TF saving code here
https://github.com/keras-team/keras/blob/d8fcb9d4d4dad45080ecfdd575483653028f8eda/keras/saving/hdf5_format.py#L136.
Comment: It could be a bug in tensorflow, are you able to test it for tensorflow 2.8? Otherwise, it's your generator `mySeqGen`.

Similar issues can be found here https://github.com/tensorflow/tensorflow/issues/43738 and https://github.com/tensorflow/federated/issues/833.
Comment: Could it be that your `fname` is the same in every loop (i.e. you want to overwrite the weights file), but you do not set `model.save_weights(fname, overwrite=True)`? Are the weights actually saved before you encounter the error?
Comment: And one last shot: can you use `tf.Data` to wrap your generator? That might help TF to handle the sockets correctly. Check out `tf.data.Dataset.from_generator` here https://www.tensorflow.org/guide/data.
Comment: Thanks for all the leads.  The filename is pretty simple, of the form "myweights_12_3", so I'd be surprised if that was an issue.  And at least looking on the OS, the weights files are updated regularly.  And, the fact that the error trace indicates "multiprocessor" all over the place, makes me think it's not a normal file, but a thread/socket thing.
Comment: It must be the generator. What exactly are you doing there? Are you storing something in a list? [Related question](https://stackoverflow.com/questions/33694149/multiprocessing-oserror-errno-24-too-many-open-files-how-to-clean-up-jobs)
Comment: Why must it be the generator?
Comment: Correction: I have a hunch that it is the generator. Somewhere, file descriptors are not GC'd. I saw three options: A&B an internal bug in TF (possible, but not very likely) of two flavours: A) weight saving not closing the files, B) the multiprocessing not being GC'd due to an internal bug, and C) your generator doing something that prevents the GC to properly collect file descriptors that are generated, similar to [this situation](https://stackoverflow.com/questions/33694149/multiprocessing-oserror-errno-24-too-many-open-files-how-to-clean-up-jobs). That's all I have.
Comment: The generator is a simulator.  You can imagine it just sending back random ins/outs of the correct size and that would be a close enough model.  There is zero disk access and no internal multiprocessing.  I was hoping someone just knew about this problem, but it looks like my options will be to either live with it or create a toy example from scratch that has the issue so people have something to play with.
Answer: It may be a system limitation.
Enter the following command:
$ ulimit -n

one thousand and twenty-four
The result is 1024, which means that the system is limited to 1024 files open at the same time.
Modification method:

Reduce the number of threads to meet this limit (just method).

Increase this limit.

a. Ulimit - N 2048 (this method is temporarily modified and is currently valid. Restore the original setting after exiting)
b. Modify the following files
sudo vim /etc/security/limits. conf

soft nofile 2048

hard nofile 2048

Restart after saving.
*unlimited
Data segment length: ulimit - D unlimited
Maximum memory size: ulimit - M unlimited
Stack size: ulimit - s unlimited
Comment: This just delays the symptom, not solve the problem.
Answer: You can monitor the number of threads, connections and files opened by the process:
import psutil

p = psutil.Process()
while True:
   model.fit(mySeqGen(xx), ..., use_multiprocessing=True, workers=8)
   <stuff>
   model.save_weights(fname)
   gc.collect()
   print(f'files={len(p.open_files())} conn={len(p.connections(kind='tcp'))} threads={p.num_threads()}')

and at least you would know what problem to solve.


Como fazer MySql retornar utf-8?

Question: Quando requisito informações do meu banco que contenham caracteres especiais recebo "�" porém no phpmyadmin em agrupamento está "UTF-8" e meu site também tem o meta de UTF-8 o que posso fazer para retornar o correto?
Comment: Utilize `urf8_encode($string)` ou `urf8_decode($string)`
Comment: Muito obrigado, eu desconhecia dessa função
Comment: @MarceloBoni Adiciona como pergunta para que eu marque a resposta pf
Answer: Uma sugestão é converter tudo que entra no banco de dados em entidades html, como segue o código php:
$email = addslashes(htmlentities($_POST['email'], ENT_QUOTES,'UTF-8'));

Dessa forma, todos os caracteres especiais são convertidos, e na hora de exibi-los, o próprio navegador o interpretará.
Será convertido segundo a tabela disponível em http://erikasarti.net/html/acentuacao-caracteres-especiais/
á = á (&aacute)
ã = ã (&atilde)
e assim por diante

UPDATE
Outra sugestão que seria mais apropriada é criar um banco de dados na codificação UTF-8. Você poderá criar o banco MySQL já em UTF-8:
CREATE DATABASE `banco` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

Poderá criar uma tabela em UTF-8
CREATE TABLE document (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    campo VARCHAR(50),
) CHARACTER SET utf8 COLLATE utf8_general_ci;

Lembre-se de definir o charset UTF-8 em suas páginas HTML

  <meta charset="UTF-8">

E de utilizar o header UTF-8 nos arquivos PHP
<?php header("Content-type: text/html; charset=utf-8"); ?>

Se ainda não for possível cadastrar acentos no banco de dados você poderá utilizar no PHP
// Para mysqli
 mysqli_set_charset($con,"utf8");

// Para PDO
 $dsn = "mysql:host=localhost;dbname=world;charset=utf8";
 $opcoes = array(
     PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'
 );
 $pdo = new PDO($dsn, $usuario, $senha, $opcoes);

Outra coisa que talvez possa ajudar é adicionando a seu .htaccess
AddDefaultCharset utf-8

Lembre-se, "nenhum UTF-8 é de mais".
Answer: Não sei se é o ideal, mas você pode fazer uma consulta dessa forma também
$sql = "SELECT * FROM tbl_produto WHERE nome_produto = :nome_produto collate utf8_unicode_ci ";

Answer: Se estiver a usar PDO acrescente esta linha:
$pdo -> exec("SET CHARACTER SET utf8");

Answer: Se estiver usando mysqli, use a função mysqli_set_charset($connection,"utf8"). Essa função define o conjunto de caracteres default para enviar e receber dados para o Banco de Dados.
Se estiver usando PDO e PHP acima da versão 5.3.6 pode especificar o conjunto de caracteres no DSN.
$dsn = sprintf("mysql:host=%s;dbname=%s;charset=utf8", $host, $dbname);
                $connection = new \PDO($dsn, $user, $password);

Ou (Para versões do PHP anterior a 5.3.6)
$dsn = sprintf("mysql:host=%s;dbname=%s", $this->host, $this->dbname);
                    $connection = new \PDO($dsn, $this->user, $this->password);
$connection->exec('SET names = utf-8');

Como fazer MySql retornar utf-8?


R: process data frame subgroups and merge results together

Question: I need to process three data frames containing the same subgroups (name). So far I've been using this approach:
results = data.frame(name = factor("dummy"), col1 = 1, col = 2)
for( name in df1$name ) {
  new.results = process(name, df1[df1$name == name, ], df2[df2$name == name,], df3[df3$name == name, ]
  results = rbind(results, new.results)
}

return(results)

The problem with this code is that the process() function must return the same layout than the 'results' data frame. If I change the contents returned by process() I also have to change the outer function. Also the first row in the results data frame must be removed.
Is there an easier way to do this?
Comment: where does function `process()` come from and what is it doing?
Comment: What I am asking is how to stitch data frames together without knowing the data frame format in 'new.results'. process() always returns the same data frame format. Is there a way to avoid the very first line in the code?
Comment: Sorry - maybe I'm a being a bit dense, but can you explain further what stitching data frames together means? Is it safe to assume that `process()` is some internal function you've written up yourself? If so, do you need to apply `process()` by each level in the column `name`? Or is there more to it?
Answer: Check out the plyr package. For example:
data_out = ddply(
    .data = data_in
    , .variables = .(name)
    , .fun = process
)

Comment: The title of this question almost read like the short description of plyr :)