问:
Substance look and feel
Im having trouble with adding substance look and feel, this is my first time trying it, i want to add the graphite glass one but it doesn't work heres my code:

```<code> package loader;

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.logging.Logger;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JWindow;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.pushingpixels.substance.api.SubstanceLookAndFeel;
import org.pushingpixels.substance.api.skin.GraphiteGlassSkin;
import org.pushingpixels.substance.api.skin.GraphiteSkin;
import org.pushingpixels.substance.api.skin.SubstanceGraphiteGlassLookAndFeel;
import org.pushingpixels.substance.api.skin.SubstanceGraphiteLookAndFeel;
import org.pushingpixels.substance.api.skin.SubstanceRavenLookAndFeel;
import org.pushingpixels.substance.api.skin.TwilightSkin;

public class Loader extends JWindow implements ActionListener {
    private static URLClassLoader classLoader;
    private static int downloaded; // number of bytes downloaded
    // to
    // splash
    // image
    private final static String FRAME_IMAGE = "http://i.imgur.com/UW5ZfQ5.jpg"; // icon
                                                                                // for
                                                                                // the
                                                                                // frame
    private final static String JAR_URL = "http://chefJones.com/play/client.jar"; // link
    // to
    // jar
    final static Loader loader = new Loader();
    private final static Logger logger = Logger.getLogger(Loader.class
            .getName());
    private static String MAIN_CLASS = "RunClient"; // put your jars main class
    // here
    private static JProgressBar progressBar;
    /**
     *
     */
    private static final long serialVersionUID = -1162207878136245145L;
    private static int size; // size of download in bytes
    private static JDialog splash;
    private final static String SPLASH_IMAGE = "http://i.imgur.com/wPH1YJb.png"; // link

    private static float getProgress() {
        return ((float) downloaded / size) * 100;
    }

    private static void grabJAR() throws ClassNotFoundException,
            InstantiationException, IllegalAccessException, IOException,
            UnsupportedLookAndFeelException {
        final URL url = new URL(Loader.JAR_URL);
        final InputStream is = url.openStream();
        final byte[] b = new byte[2048];
        int length;
        final HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();

        // Specify what portion of file to download.
        connection.setRequestProperty("Range", "bytes=" + downloaded + "-");

        // Connect to server.
        connection.connect();

        // Make sure response code is in the 200 range.
        if ((connection.getResponseCode() / 100) != 2) {
            logger.info("Unable to find file");
            return;
        }

        // set content length.
        size = connection.getContentLength();
        while ((length = is.read(b)) != -1) {
            downloaded += length;
            progressBar.setValue((int) getProgress()); // set progress bar
        }
        is.close();
        classLoader = new URLClassLoader(new URL[] { (url) });
        final Applet client = (Applet) classLoader.loadClass(MAIN_CLASS)
                .newInstance();
        client.init();
        client.start();
        loader.loadClient(client);
        setFrameTheme();

    }

    protected static void hideSplashScreen() {
        splash.setVisible(false);
        splash.dispose();
    }

    public static void main(final String... args)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException, IOException,
            UnsupportedLookAndFeelException {
         try {
                JFrame.setDefaultLookAndFeelDecorated(true);

                SubstanceLookAndFeel.setSkin(new GraphiteSkin());
                SubstanceLookAndFeel.setSkin("org.pushingpixels.substance.api.skin.GraphiteSkin");
                UIManager.setLookAndFeel(new SubstanceGraphiteLookAndFeel());
                UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.SubstanceGraphiteLookAndFeel");

            } catch (Exception e) {
                e.printStackTrace();
            }

        try {
            showSplashScreen();
        } catch (final MalformedURLException e) {
            logger.severe("Encounter error: " + e.getClass());
            logger.severe("Error message: " + e.getMessage());
            logger.severe("Error cause: " + e.getCause());
        }
        final SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {

            @Override
            protected Void doInBackground() throws Exception {
                grabJAR();
                return null;
            }

            @Override
            protected void done() {

                hideSplashScreen();
            }

        };
        worker.execute();

    }

    private static void setFrameTheme() throws ClassNotFoundException,
            InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException

    {
        try {
            UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.GraphiteGlassLookAndFeel");
        } catch (final Exception e) {
            UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.GraphiteGlassLookAndFeel");

        }
    }

    protected static void showSplashScreen() throws MalformedURLException {
        splash = new JDialog((Frame) null);
        splash.setModal(false);
        splash.setAlwaysOnTop(true);
        splash.setUndecorated(true);
        final JLabel background = new JLabel(new ImageIcon(
                new URL(SPLASH_IMAGE)));
        background.setOpaque(true);
        background.setLayout(new BorderLayout());
        splash.getContentPane().add(background);
        final JLabel text = new JLabel("Loading, please wait...");
        text.setFont(new Font("Segoe UI Light", Font.BOLD | Font.PLAIN, 15));
        text.setHorizontalAlignment(SwingConstants.CENTER);
        text.setForeground(Color.WHITE);
        text.setBorder(BorderFactory.createEmptyBorder(100, 50, 100, 50));
        background.add(text);
        progressBar = new JProgressBar();
        background.add(progressBar, BorderLayout.SOUTH);
        splash.pack();
        splash.setLocationRelativeTo(null);
        splash.setVisible(true);
    }

    private JButton Button1;

    private JButton Button2;

    private JButton Button3;
    private JButton Button6;

    private JFrame clientFrame;

    private final JPanel clientPanel = new JPanel();
    private LayoutManager Layout;

    public JPanel totalPanel;

    @Override
    public void actionPerformed(final ActionEvent actionevent) {
        final String s = actionevent.getActionCommand();

        if (s.equals("Vote")) {
            LoaderUtils.openURL("http://chefJones.com/vote/");
        } else if (s.equals("Hiscores")) {
            LoaderUtils.openURL("http://chefJones.com/hiscores");
        } else if (s.equals("Forum")) {
            LoaderUtils.openURL("http://chefJones.com/forums");
        } else

        if (s.equals("Store")) {
            LoaderUtils.openURL("http://chefJones.com/store");
        } else if (s.equals("Screenshot")) {
            LoaderUtils.takeScreenShot();
        }
    }

    private void loadClient(final Applet client) throws ClassNotFoundException,
            InstantiationException, IllegalAccessException, IOException,
            UnsupportedLookAndFeelException {
        clientFrame = new JFrame("Loader");
        clientFrame
                .setIconImage(new ImageIcon(new URL(FRAME_IMAGE)).getImage());
        clientFrame.getContentPane().setLayout(new BorderLayout());
        clientPanel.setLayout(new BorderLayout());
        clientPanel.add(client);
        clientPanel.setPreferredSize(new Dimension(765, 503));
        clientFrame.getContentPane().add(clientPanel, "Center");
        clientFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        clientFrame.pack();
        clientFrame.setVisible(true);
        setVisible(false);
        final JMenuBar jmenubar = new JMenuBar();
        clientFrame.setJMenuBar(jmenubar);
        Layout = new FlowLayout();
        JFrame.setDefaultLookAndFeelDecorated(true);
        /*JDialog.setDefaultLookAndFeelDecorated(true);
        Button1 = new JButton("Screenshot");
        Button2 = new JButton("Vote");
        Button3 = new JButton("Forum");
        Button6 = new JButton("Upgrades");
        jmenubar.setLayout(Layout);
        jmenubar.add(Button2);
        jmenubar.add(Button3);
        jmenubar.add(Button6);
        jmenubar.add(Button1);
        Button2.addActionListener(this);
        Button3.addActionListener(this);
        Button6.addActionListener(this);
        Button1.addActionListener(this);
        Button2.setBackground(Color.BLACK);
        Button2.setForeground(Color.ORANGE);
        Button2.setText("Forum");
        Button3.setBackground(Color.BLACK);
        Button3.setForeground(Color.ORANGE);
        Button3.setText("Vote");
        Button6.setBackground(Color.BLACK);
        Button6.setForeground(Color.ORANGE);
        Button6.setText("Upgrades");
        Button1.setBackground(Color.BLACK);
        Button1.setForeground(Color.ORANGE);
        Button1.setText("Screenshot");*/
        setFrameTheme();
    }

}
</code>```

and error i get:

```<code>java.lang.IllegalStateException: This method must be called on the Event Dispatch Thread
    at org.pushingpixels.substance.api.SubstanceLookAndFeel.setSkin(SubstanceLookAndFeel.java:1970)
    at org.pushingpixels.substance.api.SubstanceLookAndFeel.setSkin(SubstanceLookAndFeel.java:2086)
    at loader.Loader.main(Loader.java:126)
</code>```

Please show me what to change or add.

Thank you.

答:
I use Eclipse and when I make a JFrame it generates some code for an event dispatch thread.

Try using this in the main method:

```<code>    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {

                GraphiteGlassSkin darkSkin = new GraphiteGlassSkin();
                SubstanceLookAndFeel.setSkin(darkSkin);
                UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.SubstanceGraphiteGlassLookAndFeel");

                Frame frame = new Frame();
                frame.setVisible(true);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    });
</code>```

I believe this does the same as Andrew's code except creating and invoking the runnable in the same line.

I'm using Substance 7.1.01.

Title: Substance look and feel

Body:
Im having trouble with adding substance look and feel, this is my first time trying it, i want to add the graphite glass one but it doesn't work heres my code:

 package loader;

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.logging.Logger;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JWindow;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.pushingpixels.substance.api.SubstanceLookAndFeel;
import org.pushingpixels.substance.api.skin.GraphiteGlassSkin;
import org.pushingpixels.substance.api.skin.GraphiteSkin;
import org.pushingpixels.substance.api.skin.SubstanceGraphiteGlassLookAndFeel;
import org.pushingpixels.substance.api.skin.SubstanceGraphiteLookAndFeel;
import org.pushingpixels.substance.api.skin.SubstanceRavenLookAndFeel;
import org.pushingpixels.substance.api.skin.TwilightSkin;

public class Loader extends JWindow implements ActionListener {
    private static URLClassLoader classLoader;
    private static int downloaded; // number of bytes downloaded
    // to
    // splash
    // image
    private final static String FRAME_IMAGE = "http://i.imgur.com/UW5ZfQ5.jpg"; // icon
                                                                                // for
                                                                                // the
                                                                                // frame
    private final static String JAR_URL = "http://chefJones.com/play/client.jar"; // link
    // to
    // jar
    final static Loader loader = new Loader();
    private final static Logger logger = Logger.getLogger(Loader.class
            .getName());
    private static String MAIN_CLASS = "RunClient"; // put your jars main class
    // here
    private static JProgressBar progressBar;
    /**
     *
     */
    private static final long serialVersionUID = -1162207878136245145L;
    private static int size; // size of download in bytes
    private static JDialog splash;
    private final static String SPLASH_IMAGE = "http://i.imgur.com/wPH1YJb.png"; // link

    private static float getProgress() {
        return ((float) downloaded / size) * 100;
    }

    private static void grabJAR() throws ClassNotFoundException,
            InstantiationException, IllegalAccessException, IOException,
            UnsupportedLookAndFeelException {
        final URL url = new URL(Loader.JAR_URL);
        final InputStream is = url.openStream();
        final byte[] b = new byte[2048];
        int length;
        final HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();

        // Specify what portion of file to download.
        connection.setRequestProperty("Range", "bytes=" + downloaded + "-");

        // Connect to server.
        connection.connect();

        // Make sure response code is in the 200 range.
        if ((connection.getResponseCode() / 100) != 2) {
            logger.info("Unable to find file");
            return;
        }

        // set content length.
        size = connection.getContentLength();
        while ((length = is.read(b)) != -1) {
            downloaded += length;
            progressBar.setValue((int) getProgress()); // set progress bar
        }
        is.close();
        classLoader = new URLClassLoader(new URL[] { (url) });
        final Applet client = (Applet) classLoader.loadClass(MAIN_CLASS)
                .newInstance();
        client.init();
        client.start();
        loader.loadClient(client);
        setFrameTheme();

    }

    protected static void hideSplashScreen() {
        splash.setVisible(false);
        splash.dispose();
    }

    public static void main(final String... args)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException, IOException,
            UnsupportedLookAndFeelException {
         try {
                JFrame.setDefaultLookAndFeelDecorated(true);

                SubstanceLookAndFeel.setSkin(new GraphiteSkin());
                SubstanceLookAndFeel.setSkin("org.pushingpixels.substance.api.skin.GraphiteSkin");
                UIManager.setLookAndFeel(new SubstanceGraphiteLookAndFeel());
                UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.SubstanceGraphiteLookAndFeel");

            } catch (Exception e) {
                e.printStackTrace();
            }

        try {
            showSplashScreen();
        } catch (final MalformedURLException e) {
            logger.severe("Encounter error: " + e.getClass());
            logger.severe("Error message: " + e.getMessage());
            logger.severe("Error cause: " + e.getCause());
        }
        final SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {

            @Override
            protected Void doInBackground() throws Exception {
                grabJAR();
                return null;
            }

            @Override
            protected void done() {

                hideSplashScreen();
            }

        };
        worker.execute();

    }

    private static void setFrameTheme() throws ClassNotFoundException,
            InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException

    {
        try {
            UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.GraphiteGlassLookAndFeel");
        } catch (final Exception e) {
            UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.GraphiteGlassLookAndFeel");

        }
    }

    protected static void showSplashScreen() throws MalformedURLException {
        splash = new JDialog((Frame) null);
        splash.setModal(false);
        splash.setAlwaysOnTop(true);
        splash.setUndecorated(true);
        final JLabel background = new JLabel(new ImageIcon(
                new URL(SPLASH_IMAGE)));
        background.setOpaque(true);
        background.setLayout(new BorderLayout());
        splash.getContentPane().add(background);
        final JLabel text = new JLabel("Loading, please wait...");
        text.setFont(new Font("Segoe UI Light", Font.BOLD | Font.PLAIN, 15));
        text.setHorizontalAlignment(SwingConstants.CENTER);
        text.setForeground(Color.WHITE);
        text.setBorder(BorderFactory.createEmptyBorder(100, 50, 100, 50));
        background.add(text);
        progressBar = new JProgressBar();
        background.add(progressBar, BorderLayout.SOUTH);
        splash.pack();
        splash.setLocationRelativeTo(null);
        splash.setVisible(true);
    }

    private JButton Button1;

    private JButton Button2;

    private JButton Button3;
    private JButton Button6;

    private JFrame clientFrame;

    private final JPanel clientPanel = new JPanel();
    private LayoutManager Layout;

    public JPanel totalPanel;

    @Override
    public void actionPerformed(final ActionEvent actionevent) {
        final String s = actionevent.getActionCommand();

        if (s.equals("Vote")) {
            LoaderUtils.openURL("http://chefJones.com/vote/");
        } else if (s.equals("Hiscores")) {
            LoaderUtils.openURL("http://chefJones.com/hiscores");
        } else if (s.equals("Forum")) {
            LoaderUtils.openURL("http://chefJones.com/forums");
        } else

        if (s.equals("Store")) {
            LoaderUtils.openURL("http://chefJones.com/store");
        } else if (s.equals("Screenshot")) {
            LoaderUtils.takeScreenShot();
        }
    }

    private void loadClient(final Applet client) throws ClassNotFoundException,
            InstantiationException, IllegalAccessException, IOException,
            UnsupportedLookAndFeelException {
        clientFrame = new JFrame("Loader");
        clientFrame
                .setIconImage(new ImageIcon(new URL(FRAME_IMAGE)).getImage());
        clientFrame.getContentPane().setLayout(new BorderLayout());
        clientPanel.setLayout(new BorderLayout());
        clientPanel.add(client);
        clientPanel.setPreferredSize(new Dimension(765, 503));
        clientFrame.getContentPane().add(clientPanel, "Center");
        clientFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        clientFrame.pack();
        clientFrame.setVisible(true);
        setVisible(false);
        final JMenuBar jmenubar = new JMenuBar();
        clientFrame.setJMenuBar(jmenubar);
        Layout = new FlowLayout();
        JFrame.setDefaultLookAndFeelDecorated(true);
        /*JDialog.setDefaultLookAndFeelDecorated(true);
        Button1 = new JButton("Screenshot");
        Button2 = new JButton("Vote");
        Button3 = new JButton("Forum");
        Button6 = new JButton("Upgrades");
        jmenubar.setLayout(Layout);
        jmenubar.add(Button2);
        jmenubar.add(Button3);
        jmenubar.add(Button6);
        jmenubar.add(Button1);
        Button2.addActionListener(this);
        Button3.addActionListener(this);
        Button6.addActionListener(this);
        Button1.addActionListener(this);
        Button2.setBackground(Color.BLACK);
        Button2.setForeground(Color.ORANGE);
        Button2.setText("Forum");
        Button3.setBackground(Color.BLACK);
        Button3.setForeground(Color.ORANGE);
        Button3.setText("Vote");
        Button6.setBackground(Color.BLACK);
        Button6.setForeground(Color.ORANGE);
        Button6.setText("Upgrades");
        Button1.setBackground(Color.BLACK);
        Button1.setForeground(Color.ORANGE);
        Button1.setText("Screenshot");*/
        setFrameTheme();
    }

}

and error i get:

java.lang.IllegalStateException: This method must be called on the Event Dispatch Thread
    at org.pushingpixels.substance.api.SubstanceLookAndFeel.setSkin(SubstanceLookAndFeel.java:1970)
    at org.pushingpixels.substance.api.SubstanceLookAndFeel.setSkin(SubstanceLookAndFeel.java:2086)
    at loader.Loader.main(Loader.java:126)

Please show me what to change or add.

Thank you.

Body:
I use Eclipse and when I make a JFrame it generates some code for an event dispatch thread.

Try using this in the main method:

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {

                GraphiteGlassSkin darkSkin = new GraphiteGlassSkin();
                SubstanceLookAndFeel.setSkin(darkSkin);
                UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.SubstanceGraphiteGlassLookAndFeel");

                Frame frame = new Frame();
                frame.setVisible(true);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    });

I believe this does the same as Andrew's code except creating and invoking the runnable in the same line.

I'm using Substance 7.1.01.


来源: stackexchange

问:
Empty RecyclerView from JSON Data
thanks for all the help so far. This is a bit odd question from me. I am making a network request to fetch data from server and updating the UI with the json strings. I have done the json parsing correctly and printed the result in my log cat like this:

```<code>11-17 22:57:02.143 25111-25111/com.billionusers.tingting D/MyReviewsFragment: FAN Lib My Reviews Response is:   {"success":true,"reviews":[{"_id":"5a0ef724b004b53e48eafaf6","updatedAt":"2017-11-17T14:50:12.700Z","createdAt":"2017-11-17T14:50:12.700Z","for":"5a0d90b8f690f625df370bb6","by":"5a0aa8f7aecfbc47838fb89b","body":"Lorem Ipsum","__v":0}]}
</code>```

I have used a model class to save the reviews and created the adapter from recyclerview procedure. My model class contains the name, image, time and body of the review data from server.

Here is my adapter code:

```<code>public class ReviewsAdapter extends RecyclerView.Adapter<MyReviewsHolder> {

private final Context context;
private List<Reviews> itemsList;

public ReviewsAdapter(Context context, List<Reviews> itemsList) {
    this.context = context;
    this.itemsList = itemsList;
}

@Override
public MyReviewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_reviews_item_layout, parent, false);
    return new MyReviewsHolder(view);
}

@Override
public void onBindViewHolder(MyReviewsHolder viewholder, int position) {
    Reviews reviews = itemsList.get(position);
    Picasso.with(context)
            .load(reviews.getReviewerImg())
            .into(viewholder.reviewerProfileImg);
    viewholder.reviewerNameTV.setText(reviews.getReviewerName());
    viewholder.reviewTimeTV.setText(reviews.getReviewTime());
    viewholder.reviewBodyTV.setText(reviews.getReviewBody());
}

@Override
public int getItemCount() {
    if (itemsList == null) {
        return 0;
    }
    return itemsList.size();
}
}
</code>```

In my fragment, I have initialized the views and fields like:

```<code>private TextView dummy;
private RecyclerView my_reviews_recyclerView;

private List<Reviews> itemsList = new ArrayList<>();
private ReviewsAdapter adapter;

private boolean success;

public MyReviewsFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_my_reviews, container, false);

    dummy = view.findViewById(R.id.dummy);

    my_reviews_recyclerView = view.findViewById(R.id.my_reviews_recyclerView);
    my_reviews_recyclerView.setHasFixedSize(true);
    my_reviews_recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    fetchMyReviews();

    return view;
}
</code>```

Code for making the network request. I have also done json parsing here and tried updating the UI with data but recyclerview shows empty state.

Here's the network and UI code:

```<code>AndroidNetworking.get(Constants.GET_MY_REVIEWS_ENDPOINT)
            .addHeaders("x-access-token", token)
            .setTag("Get My Reviews")
            .setPriority(Priority.HIGH)
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "FAN Lib My Reviews Response is: \t" + response.toString());

                    try {
                        JSONObject object = response.getJSONObject("");
                        success = (boolean) object.get("success");

                        JSONArray reviewsArray = object.getJSONArray("reviews");
                        for (int i = 0; i < reviewsArray.length(); i++){
                            JSONObject body = reviewsArray.getJSONObject(i);
                            String revId = body.getString("_id");
                            String revTime = body.getString("createdAt");
                            String revFor = body.getString("for");
                            String revBy = body.getString("by");
                            String revMsgBody = body.getString("body");

                            // TODO: 11/17/2017  Get Reviewer Details

                            //Reviews reviews = new Reviews("", "Demo User", revMsgBody, revTime);
                            Reviews reviews = new Reviews();
                            reviews.setReviewerName("Abhiram Labhani");
                            reviews.setReviewerImg("");
                            reviews.setReviewBody(revMsgBody);
                            reviews.setReviewTime(revTime);
                            itemsList.add(reviews);

                            adapter = new ReviewsAdapter(getActivity(), itemsList);
                            my_reviews_recyclerView.setAdapter(adapter);

                            if (adapter.getItemCount() > 0){
                                dummy.setVisibility(View.GONE);
                                Log.d(TAG, "Adapter size is:\t" + adapter.getItemCount());
                            } else {
                                dummy.setVisibility(View.VISIBLE);
                                Log.d(TAG, "Adapter size is:\t" + adapter.getItemCount());
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(ANError anError) {

                }
            });
</code>```

Could someone point out what I'm missing as I don't know where the problem is. Thanks.

答:
try to troubleshoot first,

check if the json you fetching is not null

from there, you can now check if the json you are fetching is the problem or the adapter.

ContentLicense: CC BY-SA 3.0

Title: Empty RecyclerView from JSON Data

Body:
thanks for all the help so far. This is a bit odd question from me. I am making a network request to fetch data from server and updating the UI with the json strings. I have done the json parsing correctly and printed the result in my log cat like this:

11-17 22:57:02.143 25111-25111/com.billionusers.tingting D/MyReviewsFragment: FAN Lib My Reviews Response is:   {"success":true,"reviews":[{"_id":"5a0ef724b004b53e48eafaf6","updatedAt":"2017-11-17T14:50:12.700Z","createdAt":"2017-11-17T14:50:12.700Z","for":"5a0d90b8f690f625df370bb6","by":"5a0aa8f7aecfbc47838fb89b","body":"Lorem Ipsum","__v":0}]}

I have used a model class to save the reviews and created the adapter from recyclerview procedure. My model class contains the name, image, time and body of the review data from server.

Here is my adapter code:

public class ReviewsAdapter extends RecyclerView.Adapter<MyReviewsHolder> {

private final Context context;
private List<Reviews> itemsList;

public ReviewsAdapter(Context context, List<Reviews> itemsList) {
    this.context = context;
    this.itemsList = itemsList;
}

@Override
public MyReviewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_reviews_item_layout, parent, false);
    return new MyReviewsHolder(view);
}

@Override
public void onBindViewHolder(MyReviewsHolder viewholder, int position) {
    Reviews reviews = itemsList.get(position);
    Picasso.with(context)
            .load(reviews.getReviewerImg())
            .into(viewholder.reviewerProfileImg);
    viewholder.reviewerNameTV.setText(reviews.getReviewerName());
    viewholder.reviewTimeTV.setText(reviews.getReviewTime());
    viewholder.reviewBodyTV.setText(reviews.getReviewBody());
}

@Override
public int getItemCount() {
    if (itemsList == null) {
        return 0;
    }
    return itemsList.size();
}
}

In my fragment, I have initialized the views and fields like:

private TextView dummy;
private RecyclerView my_reviews_recyclerView;

private List<Reviews> itemsList = new ArrayList<>();
private ReviewsAdapter adapter;

private boolean success;

public MyReviewsFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_my_reviews, container, false);

    dummy = view.findViewById(R.id.dummy);

    my_reviews_recyclerView = view.findViewById(R.id.my_reviews_recyclerView);
    my_reviews_recyclerView.setHasFixedSize(true);
    my_reviews_recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    fetchMyReviews();

    return view;
}

Code for making the network request. I have also done json parsing here and tried updating the UI with data but recyclerview shows empty state.

Here's the network and UI code:

AndroidNetworking.get(Constants.GET_MY_REVIEWS_ENDPOINT)
            .addHeaders("x-access-token", token)
            .setTag("Get My Reviews")
            .setPriority(Priority.HIGH)
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "FAN Lib My Reviews Response is: \t" + response.toString());

                    try {
                        JSONObject object = response.getJSONObject("");
                        success = (boolean) object.get("success");

                        JSONArray reviewsArray = object.getJSONArray("reviews");
                        for (int i = 0; i < reviewsArray.length(); i++){
                            JSONObject body = reviewsArray.getJSONObject(i);
                            String revId = body.getString("_id");
                            String revTime = body.getString("createdAt");
                            String revFor = body.getString("for");
                            String revBy = body.getString("by");
                            String revMsgBody = body.getString("body");

                            // TODO: 11/17/2017  Get Reviewer Details

                            //Reviews reviews = new Reviews("", "Demo User", revMsgBody, revTime);
                            Reviews reviews = new Reviews();
                            reviews.setReviewerName("Abhiram Labhani");
                            reviews.setReviewerImg("");
                            reviews.setReviewBody(revMsgBody);
                            reviews.setReviewTime(revTime);
                            itemsList.add(reviews);

                            adapter = new ReviewsAdapter(getActivity(), itemsList);
                            my_reviews_recyclerView.setAdapter(adapter);

                            if (adapter.getItemCount() > 0){
                                dummy.setVisibility(View.GONE);
                                Log.d(TAG, "Adapter size is:\t" + adapter.getItemCount());
                            } else {
                                dummy.setVisibility(View.VISIBLE);
                                Log.d(TAG, "Adapter size is:\t" + adapter.getItemCount());
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(ANError anError) {

                }
            });

Could someone point out what I'm missing as I don't know where the problem is. Thanks.


问:
Is there any work around for Sikuli IDE image replacement?
I am using Sikulix for UI testing, the problem is that when ever there are changes in UI I need to replace all the images which got changed using the IDE and I need to again describe the actions ( accuracy, click position) which is becoming a sort of overhead in my case. Is there any work around by which I can simply replace the new UI images in the project folder with the same old name ( It wont work directly as the new coordinates might be different + the new image should be of same resolution that of older one)

PS: I have completely understood that sikuli works at pixel level, but still curious to find out if any one has found a work around.

答:
This may or may not work for you depending on your project development:

In my case, the changes that occur at times reduces the image similarity from say 0.9 defined to ~0.7. Now, rather than going ahead to replace the image with a totally new image where i would have to manipulate the offsets as well now, I capture the same region image at 0.7 similarity and replace it. You can easily create a script for this and even integrate it into your project. Use find to figure out the matching region and capture to take the screenshot of the area. The image caught using this way will now again match at 100% for you also, you have rid yourself from the headache of adjusting the targetoffset. Hope this helps.


问:
How can one avoid DatabaseObjectNotClosedException
How one we avoid this exception??</p>

```
01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): Releasing statement in a finalizer.    Please ensure that you explicitly call close() on your cursor: SELECT * FROM test

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteCompiledSql.(SQLiteCompiledSql.java:62)

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:80)

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:46)
```

答:
I think this error appears because you didn’t close your database. Always close your sqlitehelper class

EDITED:

You have to implement like this in your class which is extending SQLiteOpenHelper class:

```<code>@Override
public synchronized void close() {
    if(db != null){
        db.close();
    super.close();
    }
}
</code>```

Body:
How one we avoid this exception??

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): Releasing statement in a finalizer.    Please ensure that you explicitly call close() on your cursor: SELECT * FROM test

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteCompiledSql.(SQLiteCompiledSql.java:62)

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:80)

01-19 17:16:16.024: WARN/SQLiteCompiledSql(477):     at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:46)

Body:
I think this error appears because you didn’t close your database. Always close your sqlitehelper class

EDITED:

You have to implement like this in your class which is extending SQLiteOpenHelper class:

@Override
public synchronized void close() {
    if(db != null){
        db.close();
    super.close();
    }
}


问:
Azure Functions: Force HTTPS
Is there a way with Azure Functions to force connections to be over HTTPS?

I'm not seeing it in the App Settings, and I don't see any reference to web.config for Azure Functions.

答:
Update November 2017

In the Azure portal, go to your function app.

Platform features > Custom Domains > toggle HTTPS Only to 'On'.

Anyone using HTTP will receive a 301 Moved Permanently and be redirected to the HTTPS endpoint. You do not need to actually add a new hostname/domain to toggle this feature. This appears to work with both consumption and app service plans.

Title: Azure Functions: Force HTTPS


问:
Send bytes multiple times within one HTTP connection. Java 8, Spring Boot, Tomcat
My business case:

The user sends me an HTTP request. Example: http://ip:port/api/videostream

I handle this request.

I connect to another application over a TCP connection.

Application start sending me data (bytes) by this TCP connection.

I receive this data(bytes).

I send this data (bytes) to the user.

I need to send the data while the user watches this video stream. But how can I transfer data (bytes) to a user multiple times within a single Http request?

答: Try just to open output stream in ServletRequest and write into this stream while there is data in TCP input stream.</p>


问:
Accessing data within a JSON object using javascript
I have the following JSON object returned and I want to access all the "title" values. I have been able to get a new object of all the "pages," but not the "titles." I have tried everything except the correct thing! The "similar" questions on here are straight forward array access questions. This seems to involve nested arrays. Please help! Thanks.

```<code>{
    "batchcomplete": "",
    "continue": {
        "gsroffset": 15,
        "continue": "gsroffset||"
    },
    "query": {
        "pages": {
            "22989": {
                "pageid": 22989,
                "ns": 0,
                "title": "Paris",
                "index": 1
            },
            "59134": {
                "pageid": 59134,
                "ns": 0,
                "title": "Paris Commune",
                "index": 13
            },
            "61371": {
                "pageid": 61371,
                "ns": 0,
                "title": "Paris (disambiguation)",
                "index": 2
            },
            "64129": {
                "pageid": 64129,
                "ns": 0,
                "title": "Catacombs of Paris",
                "index": 11
            },
            "76286": {
                "pageid": 76286,
                "ns": 0,
                "title": "Disneyland Paris",
                "index": 15
            },
            "89106": {
                "pageid": 89106,
                "ns": 0,
                "title": "Paris–Brest–Paris",
                "index": 8
            },
            "357488": {
                "pageid": 357488,
                "ns": 0,
                "title": "Paris Saint-Germain F.C.",
                "index": 10
            },
            "868936": {
                "pageid": 868936,
                "ns": 0,
                "title": "Paris Gun",
                "index": 14
            },
            "2397134": {
                "pageid": 2397134,
                "ns": 0,
                "title": "Paris (Paris Hilton album)",
                "index": 6
            },
            "7618874": {
                "pageid": 7618874,
                "ns": 0,
                "title": "Paris syndrome",
                "index": 9
            },
            "11217925": {
                "pageid": 11217925,
                "ns": 0,
                "title": "Paris Hilton",
                "index": 7
            },
            "23528038": {
                "pageid": 23528038,
                "ns": 0,
                "title": "Paris Jackson (actress)",
                "index": 5
            },
            "30242372": {
                "pageid": 30242372,
                "ns": 0,
                "title": "Paris Agreement",
                "index": 4
            },
            "45259235": {
                "pageid": 45259235,
                "ns": 0,
                "title": "Paris Laxmi",
                "index": 12
            },
            "55340805": {
                "pageid": 55340805,
                "ns": 0,
                "title": "Paris Paris",
                "index": 3
            }
        }
    }
}
</code>```

It wants me to add more details, but I don't know what else I can add.

答:
If you want to use lodash/underscore, something like this would work:

```<code>const dataPages = data["query"]["pages"];
let titles = [];
_.each(dataPages, (dataPage) => titles.push(dataPage["title"]))
</code>```

This should get you a titles array!

Body:
I have the following JSON object returned and I want to access all the "title" values. I have been able to get a new object of all the "pages," but not the "titles." I have tried everything except the correct thing! The "similar" questions on here are straight forward array access questions. This seems to involve nested arrays. Please help! Thanks.

{
    "batchcomplete": "",
    "continue": {
        "gsroffset": 15,
        "continue": "gsroffset||"
    },
    "query": {
        "pages": {
            "22989": {
                "pageid": 22989,
                "ns": 0,
                "title": "Paris",
                "index": 1
            },
            "59134": {
                "pageid": 59134,
                "ns": 0,
                "title": "Paris Commune",
                "index": 13
            },
            "61371": {
                "pageid": 61371,
                "ns": 0,
                "title": "Paris (disambiguation)",
                "index": 2
            },
            "64129": {
                "pageid": 64129,
                "ns": 0,
                "title": "Catacombs of Paris",
                "index": 11
            },
            "76286": {
                "pageid": 76286,
                "ns": 0,
                "title": "Disneyland Paris",
                "index": 15
            },
            "89106": {
                "pageid": 89106,
                "ns": 0,
                "title": "Paris–Brest–Paris",
                "index": 8
            },
            "357488": {
                "pageid": 357488,
                "ns": 0,
                "title": "Paris Saint-Germain F.C.",
                "index": 10
            },
            "868936": {
                "pageid": 868936,
                "ns": 0,
                "title": "Paris Gun",
                "index": 14
            },
            "2397134": {
                "pageid": 2397134,
                "ns": 0,
                "title": "Paris (Paris Hilton album)",
                "index": 6
            },
            "7618874": {
                "pageid": 7618874,
                "ns": 0,
                "title": "Paris syndrome",
                "index": 9
            },
            "11217925": {
                "pageid": 11217925,
                "ns": 0,
                "title": "Paris Hilton",
                "index": 7
            },
            "23528038": {
                "pageid": 23528038,
                "ns": 0,
                "title": "Paris Jackson (actress)",
                "index": 5
            },
            "30242372": {
                "pageid": 30242372,
                "ns": 0,
                "title": "Paris Agreement",
                "index": 4
            },
            "45259235": {
                "pageid": 45259235,
                "ns": 0,
                "title": "Paris Laxmi",
                "index": 12
            },
            "55340805": {
                "pageid": 55340805,
                "ns": 0,
                "title": "Paris Paris",
                "index": 3
            }
        }
    }
}

It wants me to add more details, but I don't know what else I can add.

Body:
If you want to use lodash/underscore, something like this would work:

const dataPages = data["query"]["pages"];
let titles = [];
_.each(dataPages, (dataPage) => titles.push(dataPage["title"]))

This should get you a titles array!


问:
Computing Values for Groups of Data Excel
I have a big Excel file with listed participants and dates. I want to calculate, for each date, how many days it is from the first (start) date for each participant. Each start date is different, and each participant has a different number of entries. I know what formula I need to do the calculation, but I'm stumped on how I can recursively calculate for each participant without doing it manually! Example for what I have and want:

```<code>Participant Date    Days from Start
ca002   01/01/1983  0
ca002   10/05/1984  495
ca002   01/01/1986  1096
ca002   01/01/1986  1096
ca002   29/12/1999  6206
ca002   21/03/2001  6654
ca002   31/12/2004  8035
ca004   01/01/1967  0
ca004   01/01/1972  1826
ca004   01/01/1989  8036
ca004   01/01/2006  14245
ca004   01/01/2006  14245
</code>```

Any help greatly appreciated.

答:
Assuming your data is in the A and B columns, the first row is a header row, and your dates for each participant are in chronological order, you can type this formula into cell C2 and drag down as far as necessary:

```<code>= B2-INDEX(B$2:B2,MATCH(A2,A$2:A2,0))
</code>```

Body:
I have a big Excel file with listed participants and dates. I want to calculate, for each date, how many days it is from the first (start) date for each participant. Each start date is different, and each participant has a different number of entries. I know what formula I need to do the calculation, but I'm stumped on how I can recursively calculate for each participant without doing it manually! Example for what I have and want:

Participant Date    Days from Start
ca002   01/01/1983  0
ca002   10/05/1984  495
ca002   01/01/1986  1096
ca002   01/01/1986  1096
ca002   29/12/1999  6206
ca002   21/03/2001  6654
ca002   31/12/2004  8035
ca004   01/01/1967  0
ca004   01/01/1972  1826
ca004   01/01/1989  8036
ca004   01/01/2006  14245
ca004   01/01/2006  14245

Any help greatly appreciated.

Body:
Assuming your data is in the A and B columns, the first row is a header row, and your dates for each participant are in chronological order, you can type this formula into cell C2 and drag down as far as necessary:

= B2-INDEX(B$2:B2,MATCH(A2,A$2:A2,0))


问:
Tokenizer efficiency question
I'm writing a compiler front end for a project and I'm trying to understand what's the best method of tokenize the source code.
I can't choose between two ways:

1) the tokenizer read all tokens:

```<code>bool Parser::ReadAllTokens()
{
  Token token;
  while( m_Lexer->ReadToken( &token ) )
  {
    m_Tokens->push_back( token );
    token.Reset(); // reset the token values..
  }

  return !m_Tokens->empty();
}
</code>```

and then the parsing phase begins, operating on the m_Tokens list. In this way the methods getNextToken(), peekNextToken() and ungetToken() are relatively easy to implement by iterator, and the parsing code is well written and clear ( not broken by getNextToken() i.e. :

```<code> getNextToken();
 useToken();
 getNextToken();
 peekNextToken();
 if( peeked is something )
  ungetToken();
 ..
 ..
</code>```

)

2) the parsing phase begins and when needed, the token is created and used ( the code seems not so clear )

What's the best method??and why??and the efficiency??
thanks in advance for the answers

答:
Your method (1) is generally overkill - it is not required to tokenize an entire file prior parsing it.

A good way to go is to implement a buffered tokenizer, which will store in a list the tokens that were poke or unget, and which will consume the element of this list on "get" or read tokens from the file when the list gets empty (a la FILE*).

ContentLicense: CC BY-SA 2.5

Title: Tokenizer efficiency question

Body:
I'm writing a compiler front end for a project and I'm trying to understand what's the best method of tokenize the source code.
I can't choose between two ways:

1) the tokenizer read all tokens:

bool Parser::ReadAllTokens()
{
  Token token;
  while( m_Lexer->ReadToken( &token ) )
  {
    m_Tokens->push_back( token );
    token.Reset(); // reset the token values..
  }

  return !m_Tokens->empty();
}

and then the parsing phase begins, operating on the m_Tokens list. In this way the methods getNextToken(), peekNextToken() and ungetToken() are relatively easy to implement by iterator, and the parsing code is well written and clear ( not broken by getNextToken() i.e. :

 getNextToken();
 useToken();
 getNextToken();
 peekNextToken();
 if( peeked is something )
  ungetToken();
 ..
 ..

)

2) the parsing phase begins and when needed, the token is created and used ( the code seems not so clear )

What's the best method??and why??and the efficiency??
thanks in advance for the answers


问:
Replace all occurrences of a substring, one at a time
I have the following method which replaces all occurrences of a {TIMESTAMP} substring with the value returned by String.valueOf(System.nanoTime()), the intention is to get a different time mark per substring occurrence, but it results in all substrings being replaced by just the same value.

```<code>class StringUtils {
    private static String resolveTimestamp(String s) {
        String timestamp = "\\{TIMESTAMP}";
        return s.replaceAll(timestamp, String.valueOf(System.currentTimeMillis()));
    }
}

class Sample {
    public static void main(String[] args) {
        StringUtils.resolveTimestamp("{TIMESTAMP}, {TIMESTAMP}, {TIMESTAMP}")
    }
}

// The execution of the code above would result in:
// 241170886964203, 241170886964203, 241170886964203

// But I want to get this:
// 241733154573329, 241734822930540, 241751957270934
</code>```

I would like to know which is the best way of doing what I want, as there are several ways of doing that coming to my mind right now:

A loop with s.matches(timestamp) as condition to iterate over each occurrence of the substring, and s.replaceFirst(timestamp, String.valueOf(System.nanoTime())) to perform the replacement inside the loop.

Use the substring to explode the string into several chunks with s.split(timestamp), and iterate over the chunks joining each pair with the value returned by String.valueOf(System.nanoTime()))

Probably some other choices

NOTE: Please be aware that this is not the same problem addressed in this question. There they need to replace several occurrences of a fixed pattern with just the same value, while I need to replace several occurrences of the same substring, each one by a different value calculated at runtime.

答:
You need to call a method to return a random string within your replace all method. </p>

```<code>str.replaceAll("timestamp", randomTimestamp());

private String randomTimestamp() {
    Random rand = new Random();
    int randomNumber= rand.nextInt(1000);
    return String.valueOf(System.currentTimeMillis() + randomNumber);
}
</code>```

Body:
I have the following method which replaces all occurrences of a {TIMESTAMP} substring with the value returned by String.valueOf(System.nanoTime()), the intention is to get a different time mark per substring occurrence, but it results in all substrings being replaced by just the same value.

class StringUtils {
    private static String resolveTimestamp(String s) {
        String timestamp = "\\{TIMESTAMP}";
        return s.replaceAll(timestamp, String.valueOf(System.currentTimeMillis()));
    }
}

class Sample {
    public static void main(String[] args) {
        StringUtils.resolveTimestamp("{TIMESTAMP}, {TIMESTAMP}, {TIMESTAMP}")
    }
}

// The execution of the code above would result in:
// 241170886964203, 241170886964203, 241170886964203

// But I want to get this:
// 241733154573329, 241734822930540, 241751957270934

I would like to know which is the best way of doing what I want, as there are several ways of doing that coming to my mind right now:

A loop with s.matches(timestamp) as condition to iterate over each occurrence of the substring, and s.replaceFirst(timestamp, String.valueOf(System.nanoTime())) to perform the replacement inside the loop.

Use the substring to explode the string into several chunks with s.split(timestamp), and iterate over the chunks joining each pair with the value returned by String.valueOf(System.nanoTime()))

Probably some other choices

NOTE: Please be aware that this is not the same problem addressed in this question. There they need to replace several occurrences of a fixed pattern with just the same value, while I need to replace several occurrences of the same substring, each one by a different value calculated at runtime.

Body:
You need to call a method to return a random string within your replace all method.

str.replaceAll("timestamp", randomTimestamp());

private String randomTimestamp() {
    Random rand = new Random();
    int randomNumber= rand.nextInt(1000);
    return String.valueOf(System.currentTimeMillis() + randomNumber);
}


问:
Code Completion -- Aptana Eclipse Plugin
I have been doing javascript development for the last couple weeks and have tried JSDT and Aptana to assist in code completion.  JSDT wasn't very good at all, but I did have more luck with Aptana (used as eclipse plug-in, not the standalone product).  The problem I'm encountering is that when I create javascript classes I cannot get code completion to work.  For example, if I use the following then code completion doesn't work:

```<code>var foo = new function(value){
   this.myMethod= function(){
   }
}
</code>```

I have also verified that the following won't work:

```<code>function foo(value){
   this.myMethod= function(){
   }
}
</code>```

I have found that using a JSON style does work:

```<code>var foo = {
    myMethod: function(){

    }
}
</code>```

Does anyone know why Aptana works for the last style, but not the first?  Using the JSON style won't work for me because I have to have seperate instances of the class in question.

Also, I am not very successful in getting code completion to work across files.  For example, if I have 3 files in the javascript directory then I usually cannot get Aptana to pick up the JSON style markup in the other two classes.  This DID work at one point (for the first 2 classes I created), but since then whenever I add new classes they aren't picked up.

Thank you very much for you assistance.

Jeremy

I have identified that the following works:

```<code>/**
* The foo function
*/
function foo() {
}

/**
* The bar function
* @param {Object} a Object a
 * @param {Object} b Object b
 */
function bar(a, b){
};

foo.prototype.b = bar;

var x = new foo();
x.b
</code>```

In the above example the key is that you are registering the method using prototype.  I also tried the following, but it didn't work.

```<code>/**
* The foo function
*/
var foo = new function() {
}

/**
* The bar function
* @param {Object} a Object a
 * @param {Object} b Object b
 */
function bar(a, b){
};

foo.prototype.b = bar;

var x = new foo();
x.b
</code>```

Any ideas what the difference is?  Is the second a valid class in javascript?

答: What is your default  JavaScript Editor in Aptana (under Windows > Preferences > File Associations > *.js)? I use the Aptana JS Editor and not the JavaScript Editor (default by installation). Note that these settings can be different per project.</p>

Body:
I have been doing javascript development for the last couple weeks and have tried JSDT and Aptana to assist in code completion.  JSDT wasn't very good at all, but I did have more luck with Aptana (used as eclipse plug-in, not the standalone product).  The problem I'm encountering is that when I create javascript classes I cannot get code completion to work.  For example, if I use the following then code completion doesn't work:

var foo = new function(value){
   this.myMethod= function(){
   }
}

I have also verified that the following won't work:

function foo(value){
   this.myMethod= function(){
   }
}

I have found that using a JSON style does work:

var foo = {
    myMethod: function(){

    }
}

Does anyone know why Aptana works for the last style, but not the first?  Using the JSON style won't work for me because I have to have seperate instances of the class in question.

Also, I am not very successful in getting code completion to work across files.  For example, if I have 3 files in the javascript directory then I usually cannot get Aptana to pick up the JSON style markup in the other two classes.  This DID work at one point (for the first 2 classes I created), but since then whenever I add new classes they aren't picked up.

Thank you very much for you assistance.

Jeremy

I have identified that the following works:

/**
* The foo function
*/
function foo() {
}

/**
* The bar function
* @param {Object} a Object a
 * @param {Object} b Object b
 */
function bar(a, b){
};

foo.prototype.b = bar;

var x = new foo();
x.b

In the above example the key is that you are registering the method using prototype.  I also tried the following, but it didn't work.

/**
* The foo function
*/
var foo = new function() {
}

/**
* The bar function
* @param {Object} a Object a
 * @param {Object} b Object b
 */
function bar(a, b){
};

foo.prototype.b = bar;

var x = new foo();
x.b

Any ideas what the difference is?  Is the second a valid class in javascript?


问:
Receive an http post from an external server with servlet
on my public web application running on JBoss 5 with Java 6 I need to implement something that receive an http post from another external server with some parameters (server to server call) .

The server that call me doesn't need an answer, just standard http code reponse( es 200 - OK).

Can I use a servlet for this?

If not what should I use? (I cant'use restfull or soap ws).

答:
To my knowledge, your best bet for given situation is REST or SOAP. But you already mentioned that you cannot use that.
I don't see any reason why a servlet can't be used here. You have request & response objects in servlet doPost method. You can manipulate the response object to set appropriate response code back. </p>


问:
Modern Akka DI with Guice
Java 8, Guice 4.0 and Akka 2.3.9 here. I am trying to figure out how to annotate my actor classes with JSR330-style @Inject annotations, and then wire them all up via Guice.

But literally every single article I have read (some examples below) either uses Scala code examples, a criminally-old version of Guice, or a criminally-old version of Akka:

Let It Crash

Scala-Guice

So, given the following Guice module:

```<code>public interface MyService {
    void doSomething();
}

public class MyServiceImpl implements MyService {
    @Override
    public void doSomething() {
        System.out.println("Something has been done!");
    }
}

public class MyActorSystemModule extends AbstractModule {
    @Override
    public void configure() {
        bind(MyService.class).to(MyServiceImpl.class);
    }
}
</code>```

And given the FizzActor that gets injected with a MyService:

```<code>public class FizzActor extends UntypedActor {
    private final MyService myService;

    @Inject
    public FizzActor(MyService myService) {
        super();

        this.myService = myService;
    }

    @Override
    public void onReceive(Object message) {
        // .. Do fizz stuff inside here.
    }
}
</code>```

Then I ask: How do I rig up MyActorSystemModule to create instances of FizzActor and properly inject them with Java (not Scala!)?

Please note: FizzActor is not the only actor in my actor system!

答:
So I have been playing around with Akka and Guice recently alot and I feel that those two don't play too well together.

What I suggest is you take a similar approach what Play is doing.

Kutschkem's answer comes closest to that.

use the ActorCreator interface

make sure you have an argumentless Creator. Don't try to do @AssisstedInject in your Creator as this will imply that you will need a new creator for every Actor that you want to create. Personally I believe that initializing this in the actor is better done through messaging.

let the ActorCreator consume an injector such that you can easily create the Actor Object within the Creator.

Here is a code example using current Akka 2.5. This is the preferred setup we chose for our Akka 2.5 deployment. For brevity I did not provide the Module, but it should be clear from the way the Members are injected, what you want to provide.

Code:

```<code> class ActorCreator implements Creator<MyActor>
   @Inject
   Injector injector;
   public MyActor create() {
     return injector.getInstance(MyActor.class);
   }
 }

 class MyActor extends AbstractActor {
   @Inject
   SomeController object;

   @Nullable
   MyDataObject data;

   public ReceiveBuilder createReceiveBuilder() {
    return receiveBuilder()
      .match(MyDataObject.class, m -> { /* doInitialize() */ })
      .build();
   }
}

class MyParentActor extends AbstractActor {
   @Inject
   ActorCreator creator;

   void createChild() {
     getContext().actorOf(new Props(creator));
   }

   void initializeChild(ActorRef child, MyDataObject obj) {
     child.tell(obj);
   }
}
</code>```

Title: Modern Akka DI with Guice

Body:
Java 8, Guice 4.0 and Akka 2.3.9 here. I am trying to figure out how to annotate my actor classes with JSR330-style @Inject annotations, and then wire them all up via Guice.

But literally every single article I have read (some examples below) either uses Scala code examples, a criminally-old version of Guice, or a criminally-old version of Akka:

Let It Crash

Scala-Guice

So, given the following Guice module:

public interface MyService {
    void doSomething();
}

public class MyServiceImpl implements MyService {
    @Override
    public void doSomething() {
        System.out.println("Something has been done!");
    }
}

public class MyActorSystemModule extends AbstractModule {
    @Override
    public void configure() {
        bind(MyService.class).to(MyServiceImpl.class);
    }
}

And given the FizzActor that gets injected with a MyService:

public class FizzActor extends UntypedActor {
    private final MyService myService;

    @Inject
    public FizzActor(MyService myService) {
        super();

        this.myService = myService;
    }

    @Override
    public void onReceive(Object message) {
        // .. Do fizz stuff inside here.
    }
}

Then I ask: How do I rig up MyActorSystemModule to create instances of FizzActor and properly inject them with Java (not Scala!)?

Please note: FizzActor is not the only actor in my actor system!

Body:
So I have been playing around with Akka and Guice recently alot and I feel that those two don't play too well together.

What I suggest is you take a similar approach what Play is doing.

Kutschkem's answer comes closest to that.

use the ActorCreator interface

make sure you have an argumentless Creator. Don't try to do @AssisstedInject in your Creator as this will imply that you will need a new creator for every Actor that you want to create. Personally I believe that initializing this in the actor is better done through messaging.

let the ActorCreator consume an injector such that you can easily create the Actor Object within the Creator.

Here is a code example using current Akka 2.5. This is the preferred setup we chose for our Akka 2.5 deployment. For brevity I did not provide the Module, but it should be clear from the way the Members are injected, what you want to provide.

Code:

 class ActorCreator implements Creator<MyActor>
   @Inject
   Injector injector;
   public MyActor create() {
     return injector.getInstance(MyActor.class);
   }
 }

 class MyActor extends AbstractActor {
   @Inject
   SomeController object;

   @Nullable
   MyDataObject data;

   public ReceiveBuilder createReceiveBuilder() {
    return receiveBuilder()
      .match(MyDataObject.class, m -> { /* doInitialize() */ })
      .build();
   }
}

class MyParentActor extends AbstractActor {
   @Inject
   ActorCreator creator;

   void createChild() {
     getContext().actorOf(new Props(creator));
   }

   void initializeChild(ActorRef child, MyDataObject obj) {
     child.tell(obj);
   }
}


问:
Reading HDF5 files
Is there a way to read HDF5 files using the Scala version of Spark?

It looks like it can be done in Python (via Pyspark), but I can't find anything for Scala.

答:
There's a new product that can talk to HDF5 from Apache Spark via Scala:

https://www.hdfgroup.org/downloads/hdf5-enterprise-support/hdf5-connector-for-apache-spark/

With the above product, you can open and read HDF5 like below in Scala:

```<code>//
// HOW TO RUN:
//
// $spark-2.3.0-SNAPSHOT-bin-hdf5s-0.0.1/bin/spark-shell -i demo.scala

import org.hdfgroup.spark.hdf5._
import org.apache.spark.sql.SparkSession
val spark = SparkSession.builder().appName("Spark SQL HDF5 example").getOrCreate()

// We assume that HDF5 files (e.g., GSSTF_NCEP.3.2008.12.31.he5) are
// under /tmp directory. Change the path name ('/tmp') if necessary.
val df=spark.read.option("extension", "he5").option("recursion", "false").hdf5("/tmp/", "/HDFEOS/GRIDS/NCEP/Data Fields/SST")

// Let's print some values from the dataset.
df.show()

// The output will look like below.
//
//+------+-----+------+
//|FileID|Index| Value|
//+------+-----+------+
//|     0|    0|-999.0|
//|     0|    1|-999.0|
//|     0|    2|-999.0|
//...

System.exit(0)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Reading HDF5 files

Body:
There's a new product that can talk to HDF5 from Apache Spark via Scala:

https://www.hdfgroup.org/downloads/hdf5-enterprise-support/hdf5-connector-for-apache-spark/

With the above product, you can open and read HDF5 like below in Scala:

//
// HOW TO RUN:
//
// $spark-2.3.0-SNAPSHOT-bin-hdf5s-0.0.1/bin/spark-shell -i demo.scala

import org.hdfgroup.spark.hdf5._
import org.apache.spark.sql.SparkSession
val spark = SparkSession.builder().appName("Spark SQL HDF5 example").getOrCreate()

// We assume that HDF5 files (e.g., GSSTF_NCEP.3.2008.12.31.he5) are
// under /tmp directory. Change the path name ('/tmp') if necessary.
val df=spark.read.option("extension", "he5").option("recursion", "false").hdf5("/tmp/", "/HDFEOS/GRIDS/NCEP/Data Fields/SST")

// Let's print some values from the dataset.
df.show()

// The output will look like below.
//
//+------+-----+------+
//|FileID|Index| Value|
//+------+-----+------+
//|     0|    0|-999.0|
//|     0|    1|-999.0|
//|     0|    2|-999.0|
//...

System.exit(0)


问:
Python Variables across Class functions - how to call them?
Instead of using a global variable, I'm trying to make an instance of a variable in a class, as it seems to be best practice. How do I reference this variable across other functions in the class?  I would have thought that Test.running_sum would work or at least running_sum in test_function, but I'm not having any luck with either. Thanks very much!

```<code>class Test:
    def __init__(self):
        self.root = None
        running_sum = 0

    def test_function(self):
        print(Test.running_sum)
        return

    x = Test()
    x.test_function()
</code>```

Error:

```<code>Traceback (most recent call last):
  File "so.py", line 1, in <module>
    class Test:
  File "so.py", line 10, in Test
    x = Test()
NameError: name 'Test' is not defined
</code>```

答:
In your __init__ function, you've created a local variable. That variable will no longer exist after the function has completed.

If you want to create a variable specific to the object x then you should create a self.running_sum variable

```<code>class Test:
    def __init__(self):
        self.root = None
        self.running_sum = 0

    def test_function(self):
        print(self.running_sum)
</code>```

If you want to create a variable specific to the class Test then you should create a Test.running_sum variable.

```<code>class Test:
    running_sum = 0
    def __init__(self):
        self.root = None

    def test_function(self):
        print(Test.running_sum)
</code>```

Body:
Instead of using a global variable, I'm trying to make an instance of a variable in a class, as it seems to be best practice. How do I reference this variable across other functions in the class?  I would have thought that Test.running_sum would work or at least running_sum in test_function, but I'm not having any luck with either. Thanks very much!

class Test:
    def __init__(self):
        self.root = None
        running_sum = 0

    def test_function(self):
        print(Test.running_sum)
        return

    x = Test()
    x.test_function()

Error:

Traceback (most recent call last):
  File "so.py", line 1, in <module>
    class Test:
  File "so.py", line 10, in Test
    x = Test()
NameError: name 'Test' is not defined

Body:
In your __init__ function, you've created a local variable. That variable will no longer exist after the function has completed.

If you want to create a variable specific to the object x then you should create a self.running_sum variable

class Test:
    def __init__(self):
        self.root = None
        self.running_sum = 0

    def test_function(self):
        print(self.running_sum)

If you want to create a variable specific to the class Test then you should create a Test.running_sum variable.

class Test:
    running_sum = 0
    def __init__(self):
        self.root = None

    def test_function(self):
        print(Test.running_sum)


问:
mobx state tree as module in typescript
I cannot export mobx model as module.
I found some advice but I dont know how to do it.

```<code>import { types } from 'mobx-state-tree'

export default types.model('Test')
</code>```

[ts] Default export of the module has or is using private name 'IModelType'.

or

```<code>const model = types.model('Login')
export default model
</code>```

[ts] Exported variable 'model' has or is using name 'IModelType' from external module "..." but cannot be named.

答:
You have set "declaration": true in your tsconfig.json and you need to explicitly export IModelType so that the consumer of your library have the appropriate typings.

Either add

```<code>export { IModelType } from 'mobx-state-tree'
</code>```

to this source file or set "declaration": false in your tsconfig.json if you're not publishing your library.

Title: mobx state tree as module in typescript

Body:
I cannot export mobx model as module.
I found some advice but I dont know how to do it.

import { types } from 'mobx-state-tree'

export default types.model('Test')

[ts] Default export of the module has or is using private name 'IModelType'.

or

const model = types.model('Login')
export default model

[ts] Exported variable 'model' has or is using name 'IModelType' from external module "..." but cannot be named.

Body:
You have set "declaration": true in your tsconfig.json and you need to explicitly export IModelType so that the consumer of your library have the appropriate typings.

Either add

export { IModelType } from 'mobx-state-tree'

to this source file or set "declaration": false in your tsconfig.json if you're not publishing your library.


问:
Is Array of size 0 illegal by definition?
Is Array of size 0 illegal by definition or it depends on language? </p>

答:
It is not illegal by definition, yet it does depend on the language.  Java is fine with it, depending on the compiler used in C you might have trouble with it but in general it works there too.

Somewhat related discussion on C++ and zero length arrays: Array of zero length


问:
Executing query from SSDT
I'm using Visual Studio 2015, SSIS to run set of sql tasks in Execute Sql task and then do a data transfer between tables which are in SSMS by executing package in SSIS. When we run a series of sql statements on SSMS, we get results like rows effected for every sql successful activity. However, now I want to automate the process using SSIS to reduce the turn around time. I would like to get the rows effected for every sql query like select, insert, delete which are in execute sql task. How can it be done in SSIS? I don't have dbo_owner permission to stored procedures in SSMS. I'm thinking SSIS would be a quick way. But it is very important for me to make a log of rows effected to validate the data, as it is financial data. I have nearly 10 sql statements in each sql task like select and delete. But the output is only one table.

                                                                               For example my sql task is like below

```<code>select * from dbo.table1;
select * from dbo.table2 where city = 'Chicago';
create dbo.table3(id int, name varchar(50);
insert into dbo.table3(1,'a');
select * from dbo.table3;
</code>```

If I execute this in SSMS I get rows effected for each select statement and also table is created. If I execute the same through package in SSIS, how will get messages for each of them?

答:
I assume your data lies on SQL Server. With selects, you could use data flow tasks and row counts instead of Excecute Sql's.

For inserts and updates there's a few ways to get affected rowcount, like this: https://stackoverflow.com/a/1834264/5605866

or like this: http://microsoft-ssis.blogspot.fi/2011/03/rowcount-for-execute-sql-statement.html

Basically the same thing but with a bit different syntax.

Title: Executing query from SSDT

Body:
I'm using Visual Studio 2015, SSIS to run set of sql tasks in Execute Sql task and then do a data transfer between tables which are in SSMS by executing package in SSIS. When we run a series of sql statements on SSMS, we get results like rows effected for every sql successful activity. However, now I want to automate the process using SSIS to reduce the turn around time. I would like to get the rows effected for every sql query like select, insert, delete which are in execute sql task. How can it be done in SSIS? I don't have dbo_owner permission to stored procedures in SSMS. I'm thinking SSIS would be a quick way. But it is very important for me to make a log of rows effected to validate the data, as it is financial data. I have nearly 10 sql statements in each sql task like select and delete. But the output is only one table.

                                                                               For example my sql task is like below

select * from dbo.table1;
select * from dbo.table2 where city = 'Chicago';
create dbo.table3(id int, name varchar(50);
insert into dbo.table3(1,'a');
select * from dbo.table3;

If I execute this in SSMS I get rows effected for each select statement and also table is created. If I execute the same through package in SSIS, how will get messages for each of them?


问:
Empty RecyclerView from JSON Data
thanks for all the help so far. This is a bit odd question from me. I am making a network request to fetch data from server and updating the UI with the json strings. I have done the json parsing correctly and printed the result in my log cat like this:

```<code>11-17 22:57:02.143 25111-25111/com.billionusers.tingting D/MyReviewsFragment: FAN Lib My Reviews Response is:   {"success":true,"reviews":[{"_id":"5a0ef724b004b53e48eafaf6","updatedAt":"2017-11-17T14:50:12.700Z","createdAt":"2017-11-17T14:50:12.700Z","for":"5a0d90b8f690f625df370bb6","by":"5a0aa8f7aecfbc47838fb89b","body":"Lorem Ipsum","__v":0}]}
</code>```

I have used a model class to save the reviews and created the adapter from recyclerview procedure. My model class contains the name, image, time and body of the review data from server.

Here is my adapter code:

```<code>public class ReviewsAdapter extends RecyclerView.Adapter<MyReviewsHolder> {

private final Context context;
private List<Reviews> itemsList;

public ReviewsAdapter(Context context, List<Reviews> itemsList) {
    this.context = context;
    this.itemsList = itemsList;
}

@Override
public MyReviewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_reviews_item_layout, parent, false);
    return new MyReviewsHolder(view);
}

@Override
public void onBindViewHolder(MyReviewsHolder viewholder, int position) {
    Reviews reviews = itemsList.get(position);
    Picasso.with(context)
            .load(reviews.getReviewerImg())
            .into(viewholder.reviewerProfileImg);
    viewholder.reviewerNameTV.setText(reviews.getReviewerName());
    viewholder.reviewTimeTV.setText(reviews.getReviewTime());
    viewholder.reviewBodyTV.setText(reviews.getReviewBody());
}

@Override
public int getItemCount() {
    if (itemsList == null) {
        return 0;
    }
    return itemsList.size();
}
}
</code>```

In my fragment, I have initialized the views and fields like:

```<code>private TextView dummy;
private RecyclerView my_reviews_recyclerView;

private List<Reviews> itemsList = new ArrayList<>();
private ReviewsAdapter adapter;

private boolean success;

public MyReviewsFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_my_reviews, container, false);

    dummy = view.findViewById(R.id.dummy);

    my_reviews_recyclerView = view.findViewById(R.id.my_reviews_recyclerView);
    my_reviews_recyclerView.setHasFixedSize(true);
    my_reviews_recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    fetchMyReviews();

    return view;
}
</code>```

Code for making the network request. I have also done json parsing here and tried updating the UI with data but recyclerview shows empty state.

Here's the network and UI code:

```<code>AndroidNetworking.get(Constants.GET_MY_REVIEWS_ENDPOINT)
            .addHeaders("x-access-token", token)
            .setTag("Get My Reviews")
            .setPriority(Priority.HIGH)
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "FAN Lib My Reviews Response is: \t" + response.toString());

                    try {
                        JSONObject object = response.getJSONObject("");
                        success = (boolean) object.get("success");

                        JSONArray reviewsArray = object.getJSONArray("reviews");
                        for (int i = 0; i < reviewsArray.length(); i++){
                            JSONObject body = reviewsArray.getJSONObject(i);
                            String revId = body.getString("_id");
                            String revTime = body.getString("createdAt");
                            String revFor = body.getString("for");
                            String revBy = body.getString("by");
                            String revMsgBody = body.getString("body");

                            // TODO: 11/17/2017  Get Reviewer Details

                            //Reviews reviews = new Reviews("", "Demo User", revMsgBody, revTime);
                            Reviews reviews = new Reviews();
                            reviews.setReviewerName("Abhiram Labhani");
                            reviews.setReviewerImg("");
                            reviews.setReviewBody(revMsgBody);
                            reviews.setReviewTime(revTime);
                            itemsList.add(reviews);

                            adapter = new ReviewsAdapter(getActivity(), itemsList);
                            my_reviews_recyclerView.setAdapter(adapter);

                            if (adapter.getItemCount() > 0){
                                dummy.setVisibility(View.GONE);
                                Log.d(TAG, "Adapter size is:\t" + adapter.getItemCount());
                            } else {
                                dummy.setVisibility(View.VISIBLE);
                                Log.d(TAG, "Adapter size is:\t" + adapter.getItemCount());
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(ANError anError) {

                }
            });
</code>```

Could someone point out what I'm missing as I don't know where the problem is. Thanks.

答:
This is the error:

```<code>JSONObject object = response.getJSONObject("");
                        success = (boolean) object.get("success");
                        JSONArray reviewsArray = object.getJSONArray("reviews");
</code>```

Why are you using empty jsonobject from response?  Use it directly :

```<code>                    success = (boolean) response.get("success");
                    JSONArray reviewsArray = response.getJSONArray("reviews");
</code>```

Title: Empty RecyclerView from JSON Data

Body:
thanks for all the help so far. This is a bit odd question from me. I am making a network request to fetch data from server and updating the UI with the json strings. I have done the json parsing correctly and printed the result in my log cat like this:

11-17 22:57:02.143 25111-25111/com.billionusers.tingting D/MyReviewsFragment: FAN Lib My Reviews Response is:   {"success":true,"reviews":[{"_id":"5a0ef724b004b53e48eafaf6","updatedAt":"2017-11-17T14:50:12.700Z","createdAt":"2017-11-17T14:50:12.700Z","for":"5a0d90b8f690f625df370bb6","by":"5a0aa8f7aecfbc47838fb89b","body":"Lorem Ipsum","__v":0}]}

I have used a model class to save the reviews and created the adapter from recyclerview procedure. My model class contains the name, image, time and body of the review data from server.

Here is my adapter code:

public class ReviewsAdapter extends RecyclerView.Adapter<MyReviewsHolder> {

private final Context context;
private List<Reviews> itemsList;

public ReviewsAdapter(Context context, List<Reviews> itemsList) {
    this.context = context;
    this.itemsList = itemsList;
}

@Override
public MyReviewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_reviews_item_layout, parent, false);
    return new MyReviewsHolder(view);
}

@Override
public void onBindViewHolder(MyReviewsHolder viewholder, int position) {
    Reviews reviews = itemsList.get(position);
    Picasso.with(context)
            .load(reviews.getReviewerImg())
            .into(viewholder.reviewerProfileImg);
    viewholder.reviewerNameTV.setText(reviews.getReviewerName());
    viewholder.reviewTimeTV.setText(reviews.getReviewTime());
    viewholder.reviewBodyTV.setText(reviews.getReviewBody());
}

@Override
public int getItemCount() {
    if (itemsList == null) {
        return 0;
    }
    return itemsList.size();
}
}

In my fragment, I have initialized the views and fields like:

private TextView dummy;
private RecyclerView my_reviews_recyclerView;

private List<Reviews> itemsList = new ArrayList<>();
private ReviewsAdapter adapter;

private boolean success;

public MyReviewsFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_my_reviews, container, false);

    dummy = view.findViewById(R.id.dummy);

    my_reviews_recyclerView = view.findViewById(R.id.my_reviews_recyclerView);
    my_reviews_recyclerView.setHasFixedSize(true);
    my_reviews_recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    fetchMyReviews();

    return view;
}

Code for making the network request. I have also done json parsing here and tried updating the UI with data but recyclerview shows empty state.

Here's the network and UI code:

AndroidNetworking.get(Constants.GET_MY_REVIEWS_ENDPOINT)
            .addHeaders("x-access-token", token)
            .setTag("Get My Reviews")
            .setPriority(Priority.HIGH)
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "FAN Lib My Reviews Response is: \t" + response.toString());

                    try {
                        JSONObject object = response.getJSONObject("");
                        success = (boolean) object.get("success");

                        JSONArray reviewsArray = object.getJSONArray("reviews");
                        for (int i = 0; i < reviewsArray.length(); i++){
                            JSONObject body = reviewsArray.getJSONObject(i);
                            String revId = body.getString("_id");
                            String revTime = body.getString("createdAt");
                            String revFor = body.getString("for");
                            String revBy = body.getString("by");
                            String revMsgBody = body.getString("body");

                            // TODO: 11/17/2017  Get Reviewer Details

                            //Reviews reviews = new Reviews("", "Demo User", revMsgBody, revTime);
                            Reviews reviews = new Reviews();
                            reviews.setReviewerName("Abhiram Labhani");
                            reviews.setReviewerImg("");
                            reviews.setReviewBody(revMsgBody);
                            reviews.setReviewTime(revTime);
                            itemsList.add(reviews);

                            adapter = new ReviewsAdapter(getActivity(), itemsList);
                            my_reviews_recyclerView.setAdapter(adapter);

                            if (adapter.getItemCount() > 0){
                                dummy.setVisibility(View.GONE);
                                Log.d(TAG, "Adapter size is:\t" + adapter.getItemCount());
                            } else {
                                dummy.setVisibility(View.VISIBLE);
                                Log.d(TAG, "Adapter size is:\t" + adapter.getItemCount());
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(ANError anError) {

                }
            });

Could someone point out what I'm missing as I don't know where the problem is. Thanks.

Body:
This is the error:

JSONObject object = response.getJSONObject("");
                        success = (boolean) object.get("success");
                        JSONArray reviewsArray = object.getJSONArray("reviews");

Why are you using empty jsonobject from response?  Use it directly :

                    success = (boolean) response.get("success");
                    JSONArray reviewsArray = response.getJSONArray("reviews");


问:
Accessing values from a multidimensional array in PHP
In my PHP application, I need to take a multidimensional array and extract values in a for loop. The query will always return 9 rows.

```<code>$w = mysqli_query($con,"SELECT age, percent FROM drive03_2_monthly_income WHERE birthYear='1956' AND (age LIKE '%.00%') ORDER BY birthYear,age ");

$row = mysqli_fetch_array($w);
    for($n=0;$n<9;$n++) {
        echo $row[$n]->age." -- ".$row[$n]->percent."<br />";
        }
</code>```

When I run this, I get the data I want in $w, but having a problem extracting values in the loop.

答:
here you are.</p>

```<code><?php
$w = mysqli_query($con,"SELECT age, percent FROM drive03_2_monthly_income WHERE birthYear='1956' AND (age LIKE '%.00%') ORDER BY birthYear,age ");
while ($row = mysqli_fetch_array($w, MYSQLI_ASSOC))
{
     echo $row['age']->age." -- ".$row['percent']->percent."<br />";
}
?>
</code>```

Body:
In my PHP application, I need to take a multidimensional array and extract values in a for loop. The query will always return 9 rows.

$w = mysqli_query($con,"SELECT age, percent FROM drive03_2_monthly_income WHERE birthYear='1956' AND (age LIKE '%.00%') ORDER BY birthYear,age ");

$row = mysqli_fetch_array($w);
    for($n=0;$n<9;$n++) {
        echo $row[$n]->age." -- ".$row[$n]->percent."
";
        }

When I run this, I get the data I want in $w, but having a problem extracting values in the loop.

Body:
here you are.

<?php
$w = mysqli_query($con,"SELECT age, percent FROM drive03_2_monthly_income WHERE birthYear='1956' AND (age LIKE '%.00%') ORDER BY birthYear,age ");
while ($row = mysqli_fetch_array($w, MYSQLI_ASSOC))
{
     echo $row['age']->age." -- ".$row['percent']->percent."<br />";
}
?>


问:
centos 6 kickstart cloud
I am trying to create a Kickstart script for Centos 6 that would be Cloud ready, so as a basic pre-requisite it will have just 1 partition so the cloud-init scripts will be capable of growing the partition.

While I have been successful with Centos 7, I am finding lot of issues with Centos 6.

The far I have gone is creating just 1 partition, but kickstart seems failing to make it bootable and there it breaks.

Also note I am using QUEMU + PACKER, so I got the VIRTIO drivers loaded as part of the build.

So, this has been my code so far

```<code>install
url --url http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/os/x86_64/
repo --name updates --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/updates/x86_64/
repo --name="os" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/os/x86_64/ --cost=100
repo --name="updates" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/updates/x86_64/ --cost=100
repo --name="extras" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/extras/x86_64/ --cost=100

# for too new hardware
unsupported_hardware

text
skipx
bootloader

firewall --disabled
selinux --disabled
firstboot --disabled

lang en_GB.UTF-8
keyboard uk
timezone --utc Etc/UTC

zerombr
clearpart --all --initlabel
part / --ondisk=vda --size=8191 --grow

rootpw password
authconfig --enableshadow --passalgo=sha512

reboot

%packages --nobase
@core
-*firmware
-b43-openfwwf
-efibootmgr
-audit*
-libX*
-fontconfig
-freetype
sudo
openssh-clients
openssh-server
gcc
make
perl
kernel-firmware
kernel-devel
%end

%post
sed -i 's/^.*requiretty/#Defaults requiretty/' /etc/sudoers
sed -i 's/rhgb //' /boot/grub/grub.conf
%end
</code>```

And I just got stuck there.
I have tried many combinations in terms of partition but nothing seems to work.

For Centos7 I do not have any of those problems, but Centos 6.9 seems harder.

Any help, please?

Many thanks.

答:
In the end this just worked as stated below...:

```<code>install
url --url http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/os/x86_64/
repo --name updates --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/updates/x86_64/
repo --name="os" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/os/x86_64/ --cost=100
repo --name="updates" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/updates/x86_64/ --cost=100
repo --name="extras" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/extras/x86_64/ --cost=100

# for too new hardware
unsupported_hardware

text
skipx
bootloader

firewall --disabled
selinux --disabled
firstboot --disabled

lang en_GB.UTF-8
keyboard uk
timezone --utc Etc/UTC

zerombr
clearpart --all --initlabel
part / --ondisk=vda --size=3000 --grow

rootpw password
authconfig --enableshadow --passalgo=sha512
</code>```

I assume the ondisk was the missing bit on all this.

Title: centos 6 kickstart cloud

Body:
I am trying to create a Kickstart script for Centos 6 that would be Cloud ready, so as a basic pre-requisite it will have just 1 partition so the cloud-init scripts will be capable of growing the partition.

While I have been successful with Centos 7, I am finding lot of issues with Centos 6.

The far I have gone is creating just 1 partition, but kickstart seems failing to make it bootable and there it breaks.

Also note I am using QUEMU + PACKER, so I got the VIRTIO drivers loaded as part of the build.

So, this has been my code so far

install
url --url http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/os/x86_64/
repo --name updates --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/updates/x86_64/
repo --name="os" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/os/x86_64/ --cost=100
repo --name="updates" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/updates/x86_64/ --cost=100
repo --name="extras" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/extras/x86_64/ --cost=100

# for too new hardware
unsupported_hardware

text
skipx
bootloader

firewall --disabled
selinux --disabled
firstboot --disabled

lang en_GB.UTF-8
keyboard uk
timezone --utc Etc/UTC

zerombr
clearpart --all --initlabel
part / --ondisk=vda --size=8191 --grow

rootpw password
authconfig --enableshadow --passalgo=sha512

reboot

%packages --nobase
@core
-*firmware
-b43-openfwwf
-efibootmgr
-audit*
-libX*
-fontconfig
-freetype
sudo
openssh-clients
openssh-server
gcc
make
perl
kernel-firmware
kernel-devel
%end

%post
sed -i 's/^.*requiretty/#Defaults requiretty/' /etc/sudoers
sed -i 's/rhgb //' /boot/grub/grub.conf
%end

And I just got stuck there.
I have tried many combinations in terms of partition but nothing seems to work.

For Centos7 I do not have any of those problems, but Centos 6.9 seems harder.

Any help, please?

Many thanks.

Body:
In the end this just worked as stated below...:

install
url --url http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/os/x86_64/
repo --name updates --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/updates/x86_64/
repo --name="os" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/os/x86_64/ --cost=100
repo --name="updates" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/updates/x86_64/ --cost=100
repo --name="extras" --baseurl=http://mirrors.ukfast.co.uk/sites/ftp.centos.org/6/extras/x86_64/ --cost=100

# for too new hardware
unsupported_hardware

text
skipx
bootloader

firewall --disabled
selinux --disabled
firstboot --disabled

lang en_GB.UTF-8
keyboard uk
timezone --utc Etc/UTC

zerombr
clearpart --all --initlabel
part / --ondisk=vda --size=3000 --grow

rootpw password
authconfig --enableshadow --passalgo=sha512

I assume the ondisk was the missing bit on all this.


问:
Look_down problem finding the
Im trying to get my ip address from whatismyipaddress.com and Ive found the details of the corresponding div using firebug, but im having trouble retrieving the contents.

```<code>my $tree = HTML::TreeBuilder->new_from_content($resp->content);
my @colors = $tree->look_down(_tag => 'span class', class => 'ip blue' );

foreach(@colors)
 {
 print $_;
 }
</code>```

thanks

答:
One thing that's certainly wrong is:

```<code>_tag => 'span class'
</code>```

this should be:

```<code>_tag => 'span'
</code>```

But also note the following in the HTML source:

```<code><!-- contact us before using a script to get your IP address -->
</code>```

That is, they don't appreciate you doing this without permission...  Aside from the legal issues, they might also block the default LWP user agent.  You can override that, but that doesn't solve the legal issues.

Title: Look_down problem finding the

Body:
Im trying to get my ip address from whatismyipaddress.com and Ive found the details of the corresponding div using firebug, but im having trouble retrieving the contents.

my $tree = HTML::TreeBuilder->new_from_content($resp->content);
my @colors = $tree->look_down(_tag => 'span class', class => 'ip blue' );

foreach(@colors)
 {
 print $_;
 }

thanks

Body:
One thing that's certainly wrong is:

_tag => 'span class'

this should be:

_tag => 'span'

But also note the following in the HTML source:

<!-- contact us before using a script to get your IP address -->

That is, they don't appreciate you doing this without permission...  Aside from the legal issues, they might also block the default LWP user agent.  You can override that, but that doesn't solve the legal issues.