Q: how to fix Copy other pages data below mainActivity data in Android I want develop Android application for one website, i fetch website posts from JSON and show in RecyclerView. I show title, image, description and category in MainActivity and i want when click on Category go to categoryActivity and show this category posts!
I write below codes, but when go to the categoryActivity and back to MainActivity i see removed lasted post and added Category post in instead of MainActivity last post!
For example : my MainActivity is image 1 :
when click on post #2 (from category #2) and back to MainActivity, in MainActivity show such as this image :
Copy this post in below activity and remove the lasted post!
Adapter class: (i use for 2 activities from one adapter)
public class MainAdapter_loadMore extends RecyclerView.Adapter {

    private List<MainDataModel> mDateSet;
    private Context mContext;

    private final int VIEW_ITEM = 1;
    private final int VIEW_PROG = 0;

    // The minimum amount of items to have below your current scroll position
    // before loading more.
    private int visibleThreshold = 7;
    private int lastVisibleItem, totalItemCount;
    private boolean loading;
    private OnLoadMoreListener onLoadMoreListener;

    public MainAdapter_loadMore(Context context, RecyclerView recyclerView, List<MainDataModel> dataSet) {
        this.mContext = context;
        this.mDateSet = dataSet;

        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {

            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
                    .getLayoutManager();
            recyclerView
                    .addOnScrollListener(new RecyclerView.OnScrollListener() {
                        @Override
                        public void onScrolled(RecyclerView recyclerView,
                                               int dx, int dy) {
                            super.onScrolled(recyclerView, dx, dy);
                            totalItemCount = linearLayoutManager.getItemCount();
                            lastVisibleItem = linearLayoutManager
                                    .findLastVisibleItemPosition();
                            if (!loading
                                    && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                                // End has been reached
                                // Do something
                                if (onLoadMoreListener != null) {
                                    onLoadMoreListener.onLoadMore();
                                }
                                loading = true;
                            }
                        }
                    });
        }
    }

    @Override
    public int getItemViewType(int position) {
        return mDateSet.get(position) != null ? VIEW_ITEM : VIEW_PROG;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        RecyclerView.ViewHolder vh;
        if (viewType == VIEW_ITEM) {
            View v = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.post_card_layout, parent, false);

            vh = new DataViewHolder(v);
        } else {
            View v = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.progressbar_item, parent, false);

            vh = new ProgressViewHolder(v);
        }
        return vh;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

        if (holder instanceof DataViewHolder) {
            ((DataViewHolder) holder).main_post_title.setText(Html.fromHtml(mDateSet.get(position).getTitle()));

            Glide.with(mContext)
                    .load(mDateSet.get(position).getThumbnail())
                    .placeholder(R.drawable.post_image)
                    .crossFade()
                    .into(((DataViewHolder) holder).main_post_image);

            ((DataViewHolder) holder).main_post_content.setText(Html.fromHtml(mDateSet.get(position).getContent()));

            ((DataViewHolder) holder).main_dateTime.setText(Html.fromHtml(mDateSet.get(position).getDateTime()));

            ((DataViewHolder) holder).main_author.setText(Html.fromHtml(mDateSet.get(position).getAuthor()));

            ((DataViewHolder) holder).main_category.setText(Html.fromHtml(mDateSet.get(position).getCategory()));
            ((DataViewHolder) holder).main_category.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = holder.getPosition();
                    MainDataModel model = mDateSet.get(pos);
                    v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
                            .putExtra("categoryTitle", model.getCategory())
                            .putExtra("categoryID", model.getCategoryID()));
                }
            });

            ((DataViewHolder) holder).main_post_image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = holder.getPosition();
                    MainDataModel model = mDateSet.get(pos);
                    v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
                            .putExtra("title", model.getTitle())
                            .putExtra("image", model.getThumbnail())
                            .putExtra("content", model.getContent())
                            .putExtra("dateTime", model.getDateTime())
                            .putExtra("author", model.getAuthor())
                            .putExtra("category", model.getCategory()));

                }
            });

        } else {
            ((ProgressViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
        }
    }

    public void setLoaded() {
        loading = false;
    }

    @Override
    public int getItemCount() {
        return mDateSet.size();
    }

    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }

    public void remove(int position) {
        mDateSet.remove(position);
        notifyItemRemoved(position);
    }

    public void clear() {
        mDateSet.clear();
        notifyDataSetChanged();
    }

    public void add(List<MainDataModel> models) {
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    public void update(List<MainDataModel> models) {
        mDateSet.clear();
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    public class DataViewHolder extends RecyclerView.ViewHolder {

        private TextView main_post_title, main_post_content, main_dateTime, main_author, main_category;
        private ImageView main_post_image;

        public DataViewHolder(final View itemView) {
            super(itemView);

            main_post_title = (TextView) itemView.findViewById(R.id.post_content_title);
            main_post_image = (ImageView) itemView.findViewById(R.id.post_picture_image);
            main_post_content = (TextView) itemView.findViewById(R.id.post_content_text);
            main_dateTime = (TextView) itemView.findViewById(R.id.post_date_text);
            main_author = (TextView) itemView.findViewById(R.id.post_name_text);
            main_category = (TextView) itemView.findViewById(R.id.post_category_text);
        }
    }

    public static class ProgressViewHolder extends RecyclerView.ViewHolder {
        public AVLoadingIndicatorView progressBar;

        public ProgressViewHolder(View v) {
            super(v);
            progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
        }
    }
}

MainActivity AsyncTask codes:
public class MainDataInfo_loadMore {
    private Context mContext;
    private String ServerAddress = ServerIP.getIP();

    public void getMainDataInfo_loadMore(Context context, int pageNumber) {
        mContext = context;
        new getInfo().execute(ServerAddress + "page=" + pageNumber);
    }

    private class getInfo extends AsyncTask<String, Void, String> {
        EventBus bus = EventBus.getDefault();
        private String ou_response;
        private List<MainDataModel> infoModels;

        @Override
        protected void onPreExecute() {
            //CustomProcessDialog.createAndShow(mContext);
            infoModels = new ArrayList<>();
        }

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();

            String url = (String) params[0];
            Request request = new Request.Builder()
                    .url(url)
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .build();

            Response response;
            try {
                response = client.newCall(request).execute();
                ou_response = response.body().string();
                response.body().close();
                if (ou_response != null) {
                    try {
                        JSONObject postObj = new JSONObject(ou_response);
                        JSONArray postsArray = postObj.optJSONArray("posts");
                        infoModels = new ArrayList<>();

                        for (int i = 0; i <= infoModels.size(); i++) {
                            JSONObject postObject = (JSONObject) postsArray.get(i);
                            // Thumbnail
                            JSONObject images = postObject.optJSONObject("thumbnail_images");
                            JSONObject imagesPair = images.optJSONObject("medium");
                            // Author
                            JSONObject Author = postObject.optJSONObject("author");
                            // Category
                            JSONArray category = postObject.getJSONArray("categories");
                            for (int j = 0; j < category.length(); j++) {
                                JSONObject categoryObject = category.getJSONObject(j);

                                int id = postObject.getInt("id");
                                String title = postObject.getString("title");
                                String content = postObject.getString("content");
                                String dateTime = postObject.getString("date");
                                String thumbnail = imagesPair.getString("url");
                                String authorShow = Author.getString("name");
                                String categoryShow = categoryObject.getString("title");
                                String category_id = categoryObject.getString("id");

                                Log.d("Data", "Post ID: " + id);
                                Log.d("Data", "Post title: " + title);
                                Log.d("Data", "Post image: " + thumbnail);
                                Log.d("Data", "Post author: " + authorShow);
                                Log.d("Data", "Post category: " + categoryShow);
                                Log.d("Data", "Post category ID: " + category_id);
                                Log.d("Data", "---------------------------------");

                                //Use the title and id as per your requirement
                                infoModels.add(new MainDataModel(id, title, content, dateTime, authorShow, categoryShow, category_id, thumbnail));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ou_response;
        }

        @Override
        protected void onPostExecute(String result) {
            //CustomProcessDialog.dissmis();
            if (result != null) {
                bus.post(infoModels);
            }
        }
    }
}

CategoryActivity AsyncTask:
public class CatDataInfo {
    private Context mContext;
    private String ServerAddress = ServerIP_cat.getCatIP();

    public void getCatDataInfo(Context context, String catID) {
        mContext = context;
        new getInfo().execute(ServerAddress + "id=" + catID);
    }

    private class getInfo extends AsyncTask<String, Void, String> {
        EventBus bus = EventBus.getDefault();
        private String ou_response;
        private List<MainDataModel> infoModels;

        @Override
        protected void onPreExecute() {
            CustomProcessDialog.createAndShow(mContext);
            infoModels = new ArrayList<>();
        }

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();

            String url = (String) params[0];
            Request request = new Request.Builder()
                    .url(url)
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .build();

            Response response;
            try {
                response = client.newCall(request).execute();
                ou_response = response.body().string();
                response.body().close();
                if (ou_response != null) {
                    try {
                        JSONObject postObj = new JSONObject(ou_response);
                        JSONArray postsArray = postObj.optJSONArray("posts");
                        infoModels = new ArrayList<>();

                        for (int i = 0; i < postsArray.length(); i++) {
                            JSONObject postObject = (JSONObject) postsArray.get(i);
                            // Thumbnail
                            JSONObject images = postObject.optJSONObject("thumbnail_images");
                            JSONObject imagesPair = images.optJSONObject("medium");
                            // Author
                            JSONObject Author = postObject.optJSONObject("author");
                            // Category
                            JSONArray category = postObject.getJSONArray("categories");
                            for (int j = 0; j < category.length(); j++) {
                                JSONObject categoryObject = category.getJSONObject(j);

                                int id = postObject.getInt("id");
                                String title = postObject.getString("title");
                                String content = postObject.getString("content");
                                String dateTime = postObject.getString("date");
                                String thumbnail = imagesPair.getString("url");
                                String authorShow = Author.getString("name");
                                String categoryShow = categoryObject.getString("title");
                                String category_id = categoryObject.getString("id");

                                Log.d("CatData", "Cat Post ID: " + id);
                                Log.d("CatData", "Cat Post title: " + title);
                                Log.d("CatData", "Cat Post image: " + thumbnail);
                                Log.d("CatData", "Cat Post author: " + authorShow);
                                Log.d("CatData", "Cat Post category: " + categoryShow);
                                Log.d("CatData", "Cat Post category ID: " + category_id);
                                Log.d("CatData", "---------------------------------");

                                //Use the title and id as per your requirement
                                infoModels.add(new MainDataModel(id, title, content, dateTime, authorShow, categoryShow, category_id, thumbnail));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ou_response;
        }

        @Override
        protected void onPostExecute(String result) {
            CustomProcessDialog.dissmis();
            if (result != null) {
                bus.post(infoModels);
            }
        }
    }
}

MainActivity class:
public class Main_page extends AppCompatActivity {

    private static final long RIPPLE_DURATION = 250;
    private Toolbar toolbar;
    private RelativeLayout root;
    private ImageView menu_image, toolbar_refresh;
    private RecyclerView main_recyclerView;
    private MainAdapter_loadMore mAdaper;
    private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
    protected Handler handler;
    private RelativeLayout loadLayout;
    private LinearLayoutManager mLayoutManager;
    private int pageCount = 1;
    String ServerAddress = ServerIP.getIP();
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {//go to the click action
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        // Initializing
        handler = new Handler();
        context = getApplicationContext();
        toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        mLayoutManager = new LinearLayoutManager(this);
        loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
        // Toolbar
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle(null);
        }
        // Load First Data
        LoadData();
        // Menu
        root = (RelativeLayout) findViewById(R.id.main_root);
        View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
        root.addView(guillotineMenu);
        menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
        new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
                .setStartDelay(RIPPLE_DURATION)
                .setActionBarViewForAnimation(toolbar)
                .setClosedOnStart(true)
                .build();
        // RecyclerView and setData
        main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
        main_recyclerView.setHasFixedSize(true);
        main_recyclerView.setLayoutManager(mLayoutManager);
        mAdaper = new MainAdapter_loadMore(this, main_recyclerView, dataModels);
        main_recyclerView.setAdapter(mAdaper);
        // Load More data
        mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                dataModels.add(null);
                mAdaper.notifyItemInserted(dataModels.size() - 1);
                LoadMoreData(pageCount);
            }
        });
    }

    @Subscribe
    public void onEvent(List<MainDataModel> mainInfoModels) {
        if (dataModels.size() > 0) {
            dataModels.remove(dataModels.size() - 1);
            mAdaper.notifyItemRemoved(dataModels.size());
            mAdaper.setLoaded();
        }

        mAdaper.add(mainInfoModels);
        mAdaper.notifyDataSetChanged();
        pageCount++;

        if (dataModels.isEmpty()) {
            main_recyclerView.setVisibility(View.GONE);
            loadLayout.setVisibility(View.VISIBLE);

        } else {
            main_recyclerView.setVisibility(View.VISIBLE);
            loadLayout.setVisibility(View.GONE);
        }
    }

    private void LoadData() {
        MainDataInfo dataInfo = new MainDataInfo();
        // here getMainDataInfo() should return the server response
        dataInfo.getMainDataInfo(this);
    }

    private void LoadMoreData(int pageNumber) {
        MainDataInfo_loadMore dataInfo_loadMore = new MainDataInfo_loadMore();
        // here getMainDataInfo() should return the server response
        dataInfo_loadMore.getMainDataInfo_loadMore(this, pageNumber);
    }
}

Attention : Please don't give me negative points, I search in google but not find answer to my question. I am amateur and I really need you helps! thanks all<3

A: Try removing static so that
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
        public AVLoadingIndicatorView progressBar;

        public ProgressViewHolder(View v) {
            super(v);
            progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
        }
    }

becomes
public class ProgressViewHolder extends RecyclerView.ViewHolder {
        public AVLoadingIndicatorView progressBar;

        public ProgressViewHolder(View v) {
            super(v);
            progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
        }
    }


Q: How to add image at the end of text line using pdfmake? I'm using pdfmake. I'm trying to figure out how to add image to the end of text line instead of the new line.
For example:
var dd = {
    content: [
        'Test text',
        {image: 'sampleImage.jpg', width: 24, height: 24}
    ]
}

Using this description pdfmake generates PDF where first line is 'Test text', and second contains image.
I need that text and image would be in single line like 'Test text [image]'.
Has anyone done this before?
I would like to get some advice on how to do it. Thanks.

A: Use columns
var dd = {
  content: [
    {
      columns: [
        {
          width: 'auto',
          text: 'Test text'
        },
        {
          width: '*',
          image: 'sampleImage.jpg',
          width: 24,
          height: 24
        }
      ]
    }
  ]
}

A: If you want the image to be inline with your Multiline text you can use columns + stack
Example:
columns: [
 {
        image: "URL",
        height: 150,
        width: 180
 },

{
    stack: [
    {
        columns: [
          {
              text: 'First column first line',
              width: '35%'
          },

          {
               text: 'Second column first line',
               width: '35%'
          },

          {
               text: 'Third column first line',
               width: '30%'
          }
        ]
    },

    {
         columns: [
          {
               text: 'First column second line',
               width: '35%'
          },

          {
               text: 'Second column second line',
               width: '35%'
          },

          {
               text: 'Third column second line',
               width: '30%'
          }
        ]
    }
    ],
        width: '*'
 }]


Q: Add unmarshalling method to JAXB generated POJOs I have a bunch of XSDs that i transform into POJO with the jaxb maven plugin.
For logging purposes, i'd like to have a "unmarshal" method directly integrated inside the JAXB objects, so that i could call something like generatedPOJO.toXMLString(), knowing that generatedPOJO is the POJO generated from the XSD file via JAXB.
I tried to look in the Custom bindings documentation, but i got nothing out of that.
Thank you for your help.
EDIT: What i want is that JAXB, in addition to generating POJOs from XSD files, adds a toXMLString() method to these POJOs.
This method needs to be generated by JAXB, since i can't edit the generated POJOS.

A: In short, don't do this, it won't be a good design.
While, as @j.con pointed out, it is possible to add further methods to the generated classes, using -xinject-code or a custom XJC plugin, adding a marshalling method is not a good idea. With JAXB API, it will be pretty ugly.
To do anything you'll need an instance of JAXBContext. Either you'll pass it to your method or instantiate within the method.
The latter isn't quite good as JAXBContext is instantiated for a collection of classes or packages (context path). So you'll basically have to preset, with which classes your class may be used together. Doing so, you're losing flexibility.
Next, JAXB marshallers produce many things, not just strings/stream results but also DOM or SAX or StAX. JAXB API is quite cool about that. Opting just for strings seems to be a shortsighted choice to be.
Finally, I don't think adding toXMLString() or whatever is so much sweet syntactic sugar compared to a simple utility service or class. And hacking into code generation for that really feels like misplaced effort.


Q: EF Check a Lazy Property without load it I have an instance of class loaded by db.MyclassSet.AsNoTracking(). So the entity is not tracked on the context. I need to know if the OneToMany property of MyClass is loaded.
If I try to access by reflections I get an exception:

When an object is returned with a NoTracking merge option, Load can only be called when the EntityCollection or EntityReference does not contain objects.

Any idea?


Q: Profile wrongly suspended I apologize for asking this question here, because I must ask it on Ask Ubuntu website where my account is suspended for a reason I see as unfair (because I deleted 10 of my former questions that were of bad quality, not even commented, not answered and very poorly visited), but this is not my question.
The moderator sent me a message in which he said he blocks my account for 3 days only, but I guess he did a mistake because he suspended me for 29 days. How can I fix this?
I have asked in the past through the contact form about other problems, but I never received an answer.

A: I contacted the user, and I explained to him the actions taken. Especially the 30 day suspension, since he has been suspended before, and that there was no valid reason to delete the question, since most of them were only just asked recently.
He replied professionally, understanding the actions.


Q: Draw inscribe square into the circle I am trying to draw inscribing square into the circle, but I don't know, how should I calculate the start and end point:
import numpy as np
import cv2

img = np.zeros([300,300,3],dtype=np.uint8)
img.fill(255) # or img[:] = 255

imageWithCircle = cv2.circle(img, (150,150), 60, (0, 0, 255), 2)

#startpoint = ...
#endpoint = ...

imageWithInscribingSquare = cv2.rectangle(imageWithCircle, startpoint, endpoint, (0, 0, 255) , 2)

cv2.imshow("Circle", imageWithCircle)
cv2.waitKey(0)
cv2.destroyAllWindows()

A: Check this:
import numpy as np
import cv2

img = np.zeros([300,300,3],dtype=np.uint8)
img.fill(255) # or img[:] = 255

imageWithCircle = cv2.circle(img, (150,150), 60, (0, 0, 255), 2)

r = 60
startpoint = (int(150+(r/(2**0.5))),int(150-(r/(2**0.5))))
endpoint = (int(150-(r/(2**0.5))),int(150+(r/(2**0.5))))

print(startpoint,print(endpoint))

imageWithInscribingSquare = cv2.rectangle(imageWithCircle, startpoint, endpoint, (255, 0, 0) , 2)

cv2.imshow("Circle", imageWithCircle)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

Calculation:
If the radius is 'r', then the side of the square will be √2r, From the center the start point would be √2r/2 less in width and √2r/2 more in height, and vice versa for endpoint.


Q: How to connect reactJS front-end with PHP? I am developing a front-end with ReactJS.
How can I serve this app via PHP (plain PHP or Yii1)?

A: I suppose you'd want to go through the HTTP Protocol to create communication between the two.
In ReactJSX you want to make a fetch/get call that is provided with an EndPoint/REST from your backend.
// at the beginning of your file
import axios from 'axios';

// in your component constructor
state = {
  yourStateWithTheRecievedData: "",
}

// as a component method
componentDidMount = () => {
  axios
    .get('http://localhost:8080/YourBackendAPI')
    .then(response => {
      this.setState({
        yourStateWithTheRecievedData: response.data.yourStateWithTheRecievedData
      })
      console.log(response.data.yourStateWithTheRecievedData)
    })
}

You should now have a state with the data you've recieved. If you have a hard time doing this, i suggest you start off by first applying it to a public API.
You can find a list of public API's  here


Q: I would like to disable fast forward but not rewind in Youtube I am curious if there is an embed code that will allow me to disable the fast forward feature, but still allow a user to rewind videos in Youtube.  I am trying to embed a video used by students.


Q: Round Robin Matches using mysql I have table like below and Want to generate a round robin match schedule.
Input Table.
TID  PlayerID
2    14
2    1
2    21
2    37
2    17

Output
14 V  1
14 V  21
14 V  37
14 V  17
1 V  21
1 V  37
1 V 17
21 V 37
21 V 17
37 V 17

A: If you want all possible combinations regardless or left/right order you can do:
select
  a.player_id,
  b.player_id
from player a
join player b on b.player_id < a.player_id


Q: Show only a portion of an image with java If I have a large image that is made up of 25 x 25 smaller images in a grid. How can I use java to only show a portion of that larger grid (such as drawing a portion that starts at 125,25 and ends showing at 150,50)?

A: I'd break up the image into smaller images, put the smaller image cells into their own ImageIcons and then display whichever Icons I desired in JLabels, perhaps several of them. BufferedImage#getSubimage(...) can help you break the big image into smaller ones.
(decided to make it an answer)

A: If you don't need a physical copy of the sub image and only need to display it then you could add the image to a JLabel which you add to a JScrollPane without any scrollbars. Set the preferredSize() of the scrollpane equal to the dimension of your sub images (25x25). Then you can use
scrollPane.getViewport().setViewPosition(...);

to position the viewport to disply any sub image.


Q: Role provider in console/WPF/WinForms application I have written a role provider which assumes Windows authentication and so far works well with WCF services and ASP.NET. Is it possible to use it also with a console/WPF/WinForm application? I tried a configuration like this on a very simple console app but the Initialize method of the provider doesn't even get called (thanks in advance):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

    <system.web>

        <authentication mode="Windows" />

        <roleManager enabled="true"
                     defaultProvider="Authorization.RoleProvider">
            <providers>
                <clear/>
                <add name="Authorization.RoleProvider"
                     type="Authorization.RoleProvider, Authorization.RoleProvider"
                     applicationName="urn:AuthorizationDemo:Program"
                     authorizationServiceUrl="net.pipe://localhost/Authorization/Authorization.svc"/>
            </providers>
        </roleManager>
    </system.web>

</configuration>


Q: Wordpress plugin uninstall.php I am trying to write a simple plugin that, among other things, creates a custom post type.
I have been searching everywhere but I have really no idea on how to write the uninstall function that delete the custom post type and all its entries from the db.
I have found this on the WordPress codex, but I don't understand what to do with it.. shame
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) )
    exit();

$option_name = 'plugin_option_name';

delete_option( $option_name );

// For site options in multisite
delete_site_option( $option_name );

//drop a custom db table
global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}mytable" );

Can anyone help?
Thanks in advance
Would this be correct?
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) )
    exit();

    global $wpdb;

    $posts_table = $wpdb->posts;

    $query = "
        DELETE FROM wp_posts
        WHERE post_type = 'messages'
    ";

$wpdb->query($query);

A: The WP codex page http://codex.wordpress.org/Function_Reference/register_uninstall_hook has 2 important pieces of information, only 1 of which you list in your question. You do need to make sure that you register the hook.
That aside, if you want to remove all custom post data (regardless if it is upon uninstallation or as another person commented having a seperate button to remove data as many plugins do) you need to be sure to remove the postmeta records as well.
global $wpdb;
$cptName = 'messages';
$tablePostMeta = $wpdb->prefix . 'postmeta';
$tablePosts = $wpdb->prefix . 'posts';

$postMetaDeleteQuery = "DELETE FROM $tablePostMeta".
                      " WHERE post_id IN".
                      " (SELECT id FROM $tablePosts WHERE post_type='$cptName'";
$postDeleteQuery = "DELETE FROM $tablePosts WHERE post_type='$cptName'";

$wpdb->query($postMetaDeleteQuery);
$wpdb->query($postDeleteQuery);


Q: React parsing Unexpected token I'm having some problems with my React code.
I'm trying to add authentication but it's giving me error like

./src/components/UserInfo/index.js   Line 29:  Parsing error:
  Unexpected token, expected ","
27 |    28 |

29 |        {authenticated ? (
         |        ^   30 |                  31 |                    32 |

Here is my code
import React, { Component } from "react";
import { connect } from "react-redux";
import { Avatar, Popover } from "antd";
import { userSignOut } from "appRedux/actions/Auth";

class UserInfo extends Component {

  render() {
    const { authenticated } = this.props;

    const userMenuOptions = (

My Account

Connections

 this.props.userSignOut()}>Logout

    );

    return (
       {authenticated ? (
              <Popover overlayClassName="gx-popover-horizantal" placement="bottomRight" content={userMenuOptions}
                trigger="click">
                <Avatar src={require("assets/images/w-logo.png")}
                  className="gx-avatar gx-pointer" alt="" />
              </Popover>
            ) : (
                <Popover overlayClassName="gx-popover-horizantal" placement="bottomRight" content={userMenuOptions}
                  trigger="click">
                  <Avatar src={require("assets/images/w-logo.png")}
                    className="gx-avatar gx-pointer" alt="" />
                </Popover>
              )}

    )

  }
}

const mapStateToProps = state => {
  //console.log(state.auth.token);
  return {
    authenticated: state.auth.token !== null,
    locale: state.settings.locale
  }
}

export default connect(mapStateToProps, { userSignOut })(UserInfo);

A: The problem lies in that line because you are returning
return (
    {authenticated ? (...) : (...)});

Which means, that you're trying to return an object, and that's not what you actually want. So you should change it to this:
return authenticated ? (
          <Popover overlayClassName="gx-popover-horizantal" placement="bottomRight" content={userMenuOptions}
            trigger="click">
            <Avatar src={require("assets/images/w-logo.png")}
              className="gx-avatar gx-pointer" alt="" />
          </Popover>
        ) : (
            <Popover overlayClassName="gx-popover-horizantal" placement="bottomRight" content={userMenuOptions}
              trigger="click">
              <Avatar src={require("assets/images/w-logo.png")}
                className="gx-avatar gx-pointer" alt="" />
            </Popover>
          );


Q: Using validationRules in Models to validate form Codeigniter 4 So I have these variables $skipValidation (set specifically to FALSE), $validationRules, $validationMessages set according to this documentation
but for the life of me I can't figure out what trigger this $validationRules to run, I just assume that $skipValidation meant Codeigniter-4 already got me covered (automatically validates input before doing any queries)..
I even put $UserModel->errors() in case the validation rules catch an error
if($userModel->insert($data) === false) {
  return view('form', ['validation' => $userModel->errors()])
} else {
  redirect()->to('home');
}

I have these rules required and min_length[] applied to $validationRules but the model just skips the validationRules and insert it immediately to database rendering $validationRules useless..
Any ideas how to get validationRules in Models working? or how is it supposed to be used? I keep looping in the documentation because I don't know any better.

A: Dumb me, i was trying to figure out what is wrong with the code this whole time when its just a simple problem.. i have two models with the same filename (backup project) and i blindly edits model file that is inside the backup project..
Perhaps for future readers seeking an answer, don't forget to check your folder path for your model file, you might make the same mistake as i did.


Q: ORA-01427: SELECT * FROM TABLE gives error single-row subquery returns more than one row I tried using the following variants:
SELECT * FROM "DB"."TABLE"
SELECT COUNT(1) FROM "DB"."TABLE"
SELECT reference FROM "DB"."TABLE"
SELECT reference FROM "DB"."TABLE" WHERE rownum < 2

where reference was a specific field of type cx_Oracle.STRING
All of those return the following error:
cx_Oracle.DatabaseError: ORA-01427: single-row subquery returns more than one row

I don't see why the final example would return an error complaining about returning more than one row, nor why returning more than one row would be a problem here in any of the examples.
I've seen a lot of similar problems on SO, but they all have nested selects where I can understand this being problematic, but these should just be simple selects.
The database is Oracle 11g Enterprise Edition, and it is being accessed through the cx_Oracle python interface.

A: It turns out the 'table' I was pulling from was in fact a database view, a sort of pseudo-table, which is composed of sql joining together other tables.
The error actually lay in the view, rather than in my SQL, which is where the subquery referred to in the error was. Thanks for the help in the comments!


Q: Calling multiple arguments in an array from a function [PHP] I am trying to call multiple arguments from a function in php using an array.
Class useful {
    function callFunctionFromClass($className, $function, $args = array()) {
            return $className::$function($args);
     }
}

<?php
    require("library/class.php");

    $u = new useful;

    $u::callFunctionFromClass(new useful, "text", "Test", "Test");
?>

I have the function text() created aswell like so:
function text($msg, $msg2) {
    echo $msg;
    echo $msg2;
}

I am getting this error message:
Warning: Missing argument 2 for useful::text(),
  called in htdocs\class\library\class.php on line 16
  and defined in htdocs\class\library\class.php on line 11
Test
Notice: Undefined variable: msg2 in htdocs\class\library\class.php on line 13

This works fine without $msg2 & a second argument. So how is multiple         arguments pulled off?

A: you must use call_user_func_array. Also you are calling callFunctionFromClass as a static method but it isn't static
Class useful
{
    public function callFunctionFromClass($className, $function, $args = array())
    {
        return call_user_func_array(array($className, $function), $args);
    }

    public function text($msg, $msg2)
    {
        echo $msg;
        echo $msg2;
    }
}

$u = new useful;

$test = $u->callFunctionFromClass('useful', "text", array("Test", "Test"));


Q: Proper approach of listening solidity events in NestJS I am developing dApp. I am using NestJS and I have written contracts in solidity.
There are few events emitted from solidity. I need to listen to those events in NestJS.
My code to listen to solidity events is
contract.on('EventName', async(val, event)=>{
// do something
})

What is the appropriate way to listen to events in NestJS?
Right now I am trying to place event listening code in onModuleInit but wanted to confirm if there are any other better approach to do this.


Q: Passing ant command line options to an exec'd ant process? I'm using ant to build a mixture of Java and C++ (JNI) code that makes up a client project here. I've recently switched the C++ part of the build to using ant with cpptasks to build the C++ code instead of having ant invoke the various versions of Visual Studio that are necessary to build the code.
In order to get this to work, it is necessary to use ant's exec task to spawn off a shell in which a shell script or a batch file executes to set up the compiler environment before triggering another ant that executes the cpptasks-based C++ build. Essentially, the C++-related build tasks in the main ant build file look like this for Windows:
<target name="blah">
    <exec executable="cmd" failonerror="true">
      <arg value="/C"/>
      <arg line=""${cpp.compiler.path}/vsvars32.bat" && %ANT_HOME%/bin/ant -f cpp-build.xml make-cpp-stuff" />
    </exec>
</target>

There is no way to get rid of the vsvars32.bat invocation as the code has to be built with multiple VS versions and on build machines where none of the Visual Studio setup can be part of the build user's environment.
The above works, but the issue I'm running into is that I would like to pass certain command line options (like -verbose, -quiet, -emacs) through to the child ant if they have been passed to the parent ant. Is it possible to get access at the command line options given to the parent ant at all? Please note I'm not talking about the usual property definitions, but the ant-internal options.

A: <target name="blah">
    <property environment="env"/>
    <exec executable="cmd" failonerror="true">
      <arg value="/C"/>
      <arg value="${cpp.compiler.path}/vsvars32.bat"/>
      <arg value="&&"/>
      <arg value="${env.ANT_HOME}/bin/ant.bat"/>
      <arg value="-f" />
      <arg value="cpp-build.xml" />
      <arg value="make-cpp-stuff" />
    </exec>
</target>

Addition
You can create an external batch file that will run the vsvars and the ant, and then you will have only one process to create. I believe the && is not working as you expect it to:
run-ant-vs.bat:

....\vsvars32.bat
%ANT_HOME\bin\ant.bat -f cpp-build.xml make-cpp-stuff

A: I'm not sure if this could help you. Is Java client execution using a parameter you pass when you execute ant build, you can try to adapt this example (exec is more generic than java task, but is a similar concept)
Ant task example:
<target name="run">
  <java classname="my.package.Client" fork="true" failonerror="true">
    <arg line="-file ${specific.file}"/>
  </java>
</target>

Invocation example:
ant run -Dspecific.file=/tmp/foo.txt


Q: Google Apps Script Function generating an extra blank row I have an Apps Script function that manipulates rows of data in a sheet by first repositioning them and then transposing column data into rows. Everything works well except that I end up with an extra blank row between each block of 48 rows of data.see sheet 2 "Raw Data"
Here is the portion of the function code where something is going wrong.
// find the initial last row in the 'Raw Data' sheet
    var sheet2LastRow = sheet2.getLastRow();
    Logger.log(sheet2LastRow);                                        // 47
    var numRows = (sheet2LastRow - 1);
    Logger.log(numRows);                                              // 46

// find the Current Row to process and move to the destination row
    for (var CR = 1 ; CR < sheet2LastRow; CR++) {
    Logger.log(CR);                                                  //   1 > 46
    sheet2.getRange((CR + 1), 1, 1, 59).moveTo(sheet2.getRange((CR * 49), 1));

 // transpose data from rows to columns for Data Studio
    sheet2.getRange(1, 12, 1, 48).copyTo(sheet2.getRange((CR * 49), 10), SpreadsheetApp.CopyPasteType.PASTE_VALUES, true);           // Dimension
    sheet2.getRange((CR * 49), 12, 1, 48).copyTo(sheet2.getRange((CR * 49), 11), SpreadsheetApp.CopyPasteType.PASTE_VALUES, true);   // Opportunity
    sheet2.getRange((CR * 49), 1, 1, 9).copyTo(sheet2.getRange((CR * 49), 1, 48, 9), SpreadsheetApp.CopyPasteType.PASTE_VALUES);     // Respondent Info

A: I think that the reason of your issue is this line sheet2.getRange(row, 1, 1, 9).copyTo(sheet2.getRange(row, 1, 48, 9), SpreadsheetApp.CopyPasteType.PASTE_VALUES). In this line, the value is copied to 48 rows. But at the next loop, the value is copied to the row of (48 + 1).
In order to remove this issue, how about the following modification?
Pattern 1:
In this modification pattern, the for loop is modified by adjusting the row number.
From:
for (var CR = 1 ; CR < sheet2LastRow; CR++) {
  Logger.log(CR);                                                  //   1 > 46
  sheet2.getRange((CR + 1), 1, 1, 59).moveTo(sheet2.getRange((CR * 49), 1));
// transpose data from rows to columns for Data Studio
  sheet2.getRange(1, 12, 1, 48).copyTo(sheet2.getRange((CR * 49), 10), SpreadsheetApp.CopyPasteType.PASTE_VALUES, true);           // Dimension
  sheet2.getRange((CR * 49), 12, 1, 48).copyTo(sheet2.getRange((CR * 49), 11), SpreadsheetApp.CopyPasteType.PASTE_VALUES, true);   // Opportunity
  sheet2.getRange((CR * 49), 1, 1, 9).copyTo(sheet2.getRange((CR * 49), 1, 48, 9), SpreadsheetApp.CopyPasteType.PASTE_VALUES);     // Respondent Info
}

To:
for (var CR = 1 ; CR < sheet2LastRow; CR++) {
  var row = (CR * 49) - (CR - 1);
  sheet2.getRange((CR + 1), 1, 1, 59).moveTo(sheet2.getRange(row, 1));
  sheet2.getRange(1, 12, 1, 48).copyTo(sheet2.getRange(row, 10), SpreadsheetApp.CopyPasteType.PASTE_VALUES, true);
  sheet2.getRange(row, 12, 1, 48).copyTo(sheet2.getRange(row, 11), SpreadsheetApp.CopyPasteType.PASTE_VALUES, true);
  sheet2.getRange(row, 1, 1, 9).copyTo(sheet2.getRange(row, 1, 48, 9), SpreadsheetApp.CopyPasteType.PASTE_VALUES);
}

Pattern 2:
In this modification pattern, the for loop is not modified. After all values were copied, the empty rows are deleted.
From:
sheet2.deleteRows(2, 47);
var sheet2NewLastRow = sheet2.getLastRow();

To:
sheet2.deleteRows(2, 47);
var values = sheet2.getRange("A2:DL").getValues();
for (var i = values.length - 1; i >= 0; i--) {
  if (values[i].every(e => !e.toString())) sheet2.deleteRow(i + 2);
}
var sheet2NewLastRow = sheet2.getLastRow();


Q: Predict probablilities from glm models after purrr::map with a new dataset I am replacing r for loop with purrr::map, and predicting probabilities with a new dataset.
Using for-loop, I have been able to obtain predicted probabilities for different subgroups with a new dataset. I am trying to reproduce the same  analysis with purrr::map as a new R user, but just not sure where to find the relevant instructions.
library(tidyverse)
data("mtcars")
newdata <- expand.grid(mpg = 10:34)
output <- setNames(data.frame(matrix(ncol = 3, nrow = 0)),
              c("mpg", "am", "pr_1"))
for (i in c(0, 1)) {
md_1 <- glm(vs ~ mpg, data = filter(mtcars, am == i), family ="binomial")
  pr_1 <- predict(md_1, newdata, type = "response")
  output_1 <- data.frame(newdata, am = i, pr_1)
  output <- bind_rows(output_1, output)
}
# Try purrr::map
my_predict<-mtcars %>%
split(.$am) %>%
map(~glm(vs~mpg, family = "binomial", data = .x))
# then? predict(my_predict, newdata, type="response") not working

I expect a new dataset with predicted probabilities for different subgroups just like the for-loop above.

A: We could use new group_split to split the dataframe based on groups (am) and then use map_df to create a new model for each group and get the prediction values based on that.
library(tidyverse)

mtcars %>%
  group_split(am) %>%
  map_df(~{
  model <- glm(vs~mpg, family = "binomial", data = .)
  data.frame(newdata,am = .$am[1], pr_1 = predict(model,newdata, type = "response"))
})

#   mpg am         pr_1
#1   10  0 0.0000831661
#2   11  0 0.0002519053
#3   12  0 0.0007627457
#4   13  0 0.0023071316
#5   14  0 0.0069567757
#6   15  0 0.0207818241
#7   16  0 0.0604097519
#8   17  0 0.1630222293
#9   18  0 0.3710934960
#10  19  0 0.6412638468
#.....


Q: Linq Retrieve Entities using a Navigational Property Linq and EF.
I'm pretty new so I have some problem to retrieve entities using a Navigational Property (CmsContents).
I can return as an List but not as an IEnumerable.

*

*Could you tell me what is wrong in my code?

*Also do you know a better approach to retrieve Entities suing Navigational Properties?

Please provide me an example of code thanks!
    public IEnumerable<CmsGroupsType> GetMostPopularContents()
    {
        using (var context = new CmsConnectionStringEntityDataModel())
        {
            context.CmsGroupsTypes.MergeOption = MergeOption.NoTracking;
            var contents = context.CmsGroupsTypes.Single(g => g.GroupTypeId == 1).CmsContents;
            return contents.ToList();
        }
    }

Error   1   Cannot implicitly convert type 'System.Collections.Generic.List<WebProject.DataAccess.DatabaseModels.CmsContent>' to 'System.Collections.Generic.IEnumerable<WebProject.DataAccess.DatabaseModels.CmsGroupsType>'. An explicit conversion exists (are you missing a cast?)

A: The generic types don't match: Your .ToList() is of CmsContent, but your return type is an IEnumerable of CmsGroupsType. I'm not sure if that was intentional, but changing the return type to IEnumerable<CmsContent> will make everything work.

A: Change your return type from CmsGroupsType to WebProject.DataAccess.DatabaseModels.CmsContent


Q: Modify working AddHandler to match files only in the CURRENT directory, NOT child directories The following works fine for allowing PHP to be executed on two XML files:
<FilesMatch ^(opensearch|sitemap)\.xml$>
AddHandler application/x-httpd-php5 .xml
</FilesMatch>

However unfortunately this rule would allow this to happen in any child directory as well.

*

*/opensearch.xml, working/desired match

*/henchman24/opensearch.xml, working/NOT desired match

How do we force Apache to only match the files in the current directory and not child directories?
I'd really like to:

*

*Avoid adding a child .htaccess file in every possible child directory.

*Avoid using an absolute server path.

A: If directive can be used to provide a condition for the handler to be added only for files matching the pattern in the current folder.
The following example will add the handler for only files in the document root, such as /sitemap.xml and /opensearch.xml but not for /folder/sitemap.xml and /folder/opensearch.xml
<FilesMatch ^(opensearch|sitemap)\.xml$>
<If "%{REQUEST_URI} =~ m#^\/(opensearch|sitemap)\.xml$#">
  AddHandler application/x-httpd-php .xml
</If>
</FilesMatch>

In the above example, the condition is checking that the REQUEST_URI matches the regex pattern delimited in m# #.
The ~= comparison operator checks that a string match a regular expression.
The pattern ^\/(opensearch|sitemap)\.xml$ matches REQUEST_URI variable  (the path component of the requested URI) such as /opensearch.xml or /sitemap.xml
^                      # startwith
\/                     # escaped forward-slash
(opensearch|sitemap)   # "opensearch" or "sitemap"
\.                     # .
xml                    # xml
$                      # endwith

A: Have you tried H= in a RewriteRule?
RewriteEngine On
RewriteRule ^(opensearch|sitemap)\.xml$ . [H=application/x-httpd-php5]

Rewrite in htaccess has the built-in property that those filenames in any subdir will have the subdir present in the string the regex tests against so the anchored regex will not match in subdirs.


Q: Angular FormBuild email validation fails on the init (the value is an object) In my Angular v5.1.2 project I'm using FormBuilder to create simple form:
this.userDetailsForm = this.formBuilder.group({
  id: [{value: this.user.userid || '', disabled: true}, [Validators.required]],
  email: [{value: this.user.email || ''}, [Validators.required, Validators.email]],
  firstName: [{value: this.user.firstName || ''}, [Validators.required]],
  lastName: [{value: this.user.lastName || ''}, [Validators.required]]
});

And I have an issue with email field. It becomes invalid after the Form has been initialized. If I switch the initialization of the email field value from object notation to
email: [this.user.email, [Validators.required, Validators.email]]

the things going work properly.
I made a little investigation and with the help of custom validator I realized that the Form field value is an object and it remains the object until any manual change has been done. For example,
email: [{value: this.user.email || ''}, [Validators.required, this.myCustomValidator]],

where
private myCustomValidator(control) {
  console.log(control.value);
}

gives following:

*

*control.value is equal to { value: 'test@test.test' } on init

*control.value is equal to 'test@test.test' after edit

That's why I didn't see problems with other fileds: they have only required validator and !!({ value: ... })  is always true.
So, is it possible to use object notation for FormBuilder fields initialization and what could be wrong in my case? I'd like to have a possibility to set up options like {value: 'myValue', disabled: true} but currently I can't use it due to validators issue.

A: Angular distinguishes so-called boxed and unboxed values.
Boxed value is a value satisfying the following condition:
_isBoxedValue(formState: any): boolean {
  return typeof formState === 'object' &&
        formState !== null &&
        Object.keys(formState).length === 2 &&
        'value' in formState &&
       'disabled' in formState;
}

https://github.com/angular/angular/blob/7c414fc7463dc90fe189db5ecbf3e5befcde6ff4/packages/forms/src/model.ts#L621-L624
As we can see we should provide both value and disabled properties for boxed value.
If you pass unboxed value then angular will treat it like a value.
More information could be found here

*

*https://github.com/angular/angular/blob/master/packages/forms/test/form_control_spec.ts#L50-L77


Q: How to import the google map timeline Json data into a DataFrame I got my commuting report from google map timeline and it is in json format. I use these codes:
with open('Location History.json', encoding='utf-8') as data_file:
  data = json.loads(data_file.read())
  pd.DataFrame(data)

the dataframe has only one 'location' column.
{"locations" : [ {
"timestampMs" : "1501812184856",
"latitudeE7" : 390632197,
"longitudeE7" : -771227158,
"accuracy" : 10,
"velocity" : 1,
"heading" : 226,
"altitude" : 146,
"verticalAccuracy" : 12
 }, {
"timestampMs" : "1501813902831",
"latitudeE7" : 390624516,
"longitudeE7" : -771212199,
"accuracy" : 10,
"velocity" : 5,
"heading" : 316,
"altitude" : 126,
"verticalAccuracy" : 16
 },

any advice how I can read the file into multiple columns and one row for each member of dict.

A: extract 'location' from initial json, and then convert to DataFrame
with open('Location History.json', encoding='utf-8') as data_file:
    data = json.loads(data_file.read())

pd.DataFrame(data['locations'])


Q: Call custom javascript before loading any SPFX webparts I have a requirement, where i want to fetch certain properties from user profile.For this i have created a file which fetches data from user profile and store in global variable.
I was able to add script to modern page and classic page ( Add-PnPJavaScriptLink )
Based on these user profile properties each of my webpart are getting loaded on modern page.
i dont want to call the userprofile js each time for each webpart.
I just want to call it once.Once present in global variable i should be able to access it for all other webparts
But the problem is the custom javascript is getting called after webpart is rendered
any suggestions ?

A: SharePoint does have a function in the onclick event that looks for any PreSaveItem events.  You can create a function called PreSaveAction(); within you client code to have you custom actions run before SharePoint does it's thing after the Save button is clicked.  Look at a Save button in a form in Developer Tools, and you will see what I am saying.  There is a check at the beginning that says:
onclick="(!PreSaveItem()) return false; blah blah blah"

Try running this function:
PreSaveAction() {
    //do my stuff here
}

Make sure this function is place above any $(document).ready(function() {});, _spBodyOnLoadFunctionNames.push("myCustom");, or any other page ready type event for it to fire.  This should work for you.  Hope this helps!

A: What about creating a global function which would return a promise and also cache the data? Only first call to the function would cause loading the data for the user profile. Subsequent calls would be handled from cache.
Using promises would also solve your problem with async calls.
More about promises: https://developers.google.com/web/fundamentals/primers/promises
Example:
function getDataGlobal(){
    return new Promise(function(resolve, reject) {
    // Your api call here
    if (/* everything turned out fine */) {
        resolve(yourApiData);
    }
    else {
        reject(Error("It broke"));
    }
    });
 }
//In webpart
 getDataGlobal().then(function(result) {
    console.log(result); /* result is the "yourApiData" from resolve(yourApiData);*/
  }, function(err) {
    console.log(err); // Error: "It broke"
  });


Q: FileNotFound Exception MediaPlayer android I have a1.ogg in the res/raw file
try {
    mp = MediaPlayer.create(this, R.raw.a1);
} catch (Exception e)
{ Log.e("msg",e.getMessage());  }

Give me java.io.FileNotFoundException
The same file in wav format work

A: Try this:
MediaPlayer mp = new MediaPlayer();

mp.setDataSource("/data/test.ogg"); // replace with correct location
mp.prepare();
mp.start();


Q: EMC VNXe3200 LUN cli command I'm using the below command to view the LUN configuration in VNXe1600.
/stor/prov/luns/lun show -detail.
 And i'm trying the same command in VNXe3200 but, nothing is display.
/metrics/metric show This command is used to list all performance command supported by VNXe.
Is there any Unisphere commands to list all configuration command supported by VNXe.
Thanks in advance.


Q: Spring Boot: Prevent Jackson from "reformatting" XMLGregorianCalendar upon JSON serialization My Spring boot application queries an external SOAP service. Having generated the classes from its WSDL/XSDs this is what a class looks like.
As you can see, the dateOfBirth is of type XMLGregorianCalendar. The SOAP response contains the date of birth in the following format: 1991-11-08+01:00.
public class Applicant {

    // other properties

    @XmlElement(required = true)
    @XmlSchemaType(name = "date")
    protected XMLGregorianCalendar dateOfBirth;

    // getters & setters
}

The Spring application receives the response body from the SOAP service and returns it "as is" to its calling client as JSON serialized by Jackson. The problem is, it seems as if Jackson serializes the dateOfBirth into another format.
This is the format the cilent finally receives:
{
  "dateOfBirth": "1976-11-12T23:00:00.000+00:00"
}

Is there some configuration or custom implementation I could use so that Jackson won't reformat this date? In the worst case I could write a class which maps the SOAP response but this sounds quite tedious.

A: Try configuring your mapper like so:
mapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy+hh:mm"));

that should work
but if you want more control you can use @JsonFormat annotation:
public class Applicant {

    @XmlElement(required = true)
    @XmlSchemaType(name = "date")
    @JsonFormat( shape = JsonFormat.Shape.STRING, pattern ="dd-MM-yyyy+hh:mm")
    protected XMLGregorianCalendar dateOfBirth;
}

for even more control : https://www.baeldung.com/jackson-annotations
source : https://github.com/FasterXML/jackson-docs


Q: Android Listview Item Remove I want to remove the item in setOnItemLongClickListener, deletion isn't working. Can anyone see what the problem is in the code ?
Adapter
public abstract class myArrayAdapter<T> extends ArrayAdapter<T> {

    protected List<T> items = new ArrayList<>();

    protected int resource;
    protected LayoutInflater layoutInflater;

    public myArrayAdapter(Context context, int resource) {
        super(context, resource);
        this.resource = resource;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = layoutInflater.inflate(resource, null, false);
        getView(position, getItem(position), view);
        return view;
    }

    public abstract void getView(int position, T model, View view);

    public void setItems(List<T> items) {
        this.items = items;
        notifyDataSetChanged();
    }

    @Override
    public T getItem(int position) {
        return items.get(position);
    }

    @Override
    public int getCount() {
        return items.size();
    }

    public List<T> getItems() {
        return items;
    }

    @Override
    public int getPosition(T item) {
        return items.indexOf(item);
    }

}

my activity
public class QuoteDetailActivity extends Activity {

    @Inject
    QuoteDetailViewModel viewModel;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.price_text)
    TextView priceTextView;

    @BindView(R.id.list_view_materials)
    ListView materialsListView;

    private int quoteId;

    myArrayAdapter<LinkedTreeMap<String, Object>> adapter;

    public static void start(Context context, int quoteId) {
        Intent starter = new Intent(context, QuoteDetailActivity.class);
        starter.putExtra("QUOTE_ID", quoteId);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quote_detail);
        ButterKnife.bind(this);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(v -> finish());

        quoteId = getIntent().getIntExtra("QUOTE_ID", 0);

        initMaterialList();
        bindToViewModel();
    }

    private void bindToViewModel() {

        viewModel.quoteModel()
                .compose(bindToLifecycle())
                .subscribe(quoteModel -> {
                    getSupportActionBar().setTitle(String.valueOf(quoteModel.get("QuoteName")));
                    priceTextView.setText(String.valueOf(quoteModel.get("TotalCost")) + " + KDV");
                });

        viewModel.quoteMaterialModel()
                .compose(bindToLifecycle())
                .subscribe(materialsModel -> {
                    adapter.setItems(materialsModel);
                });

        //teklif silme
        viewModel.materialDelete()
                .compose(bindToLifecycle())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        finish();
                    }
                });

        attachToViewModel(viewModel);
    }

    @Override
    protected void onResume() {
        super.onResume();
        viewModel.getQuoteDetail(quoteId);
    }

    private void initMaterialList(){
        adapter = new myArrayAdapter<LinkedTreeMap<String, Object>>(this, R.layout.layout_listview_item_quote_material) {
            @Override
            public void getView(int position, LinkedTreeMap<String, Object> model, View view) {
                TextView materialNameTextView = (TextView) view.findViewById(R.id.material_name);
                TextView priceAndAmountNameTextView = (TextView) view.findViewById(R.id.price_and_amount);
                TextView totalCostNameTextView = (TextView) view.findViewById(R.id.total_cost);

                materialNameTextView.setText(String.valueOf(model.get("MaterialName")));
                priceAndAmountNameTextView.setText("Fiy. x Mik : " + String.valueOf(model.get("Cost")) + " x " + String.valueOf(model.get("MaterialCount")));
                totalCostNameTextView.setText(String.valueOf(model.get("TotalCost")));
            }
        };
        materialsListView.setAdapter(adapter);

        materialsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                Resources r = getResources();
                int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
                int pxTop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6, r.getDisplayMetrics());

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(QuoteDetailActivity.this);
                alertDialog.setTitle("Delete.");

                alertDialog.setPositiveButton("Yes", (dialog, which) -> {

                    LinkedTreeMap<String, Object> selectedItem = adapter.getItem(position);
                    int QuoteMaterialId = ((Double) selectedItem.get("QuoteMaterialId")).intValue();

                    viewModel.deleteMaterial(quoteId,QuoteMaterialId);

                    adapter.remove(adapter.getItem(position));
                    adapter.notifyDataSetChanged();

                });
                alertDialog.setNegativeButton("No", (dialog, which) -> {
                    dialog.dismiss();
                });

                alertDialog.show();
                return true;            }

        });

    }

    @Override
    public void setupComponent(ActivityComponent activityComponent) {
        DaggerQuoteComponent.builder()
                .activityComponent(activityComponent)
                .build()
                .inject(this);
    }

}

Deletion is not happening. Where am I making mistakes? Thanks.

A: You have to work with the data set, not with the adapter.
e.g: If you fill a ListView with a ArrayList<T> object, if you want to delete a row in the list you have to delete it from the ArrayList and then call the notifyDataSetChanged().
// ArrayList<T> items filled with data
// delete the item that you want
items.remove(position);
// so, communicate to the adapter that the dataset is changed
adapter.notifyDataSetChanged();

In your specific case, the item from materialsModel, then notufy it to the adapter, something like follwing:
// remove the item
// I don't know which method you must call, hope you do ;)
materialsModel.remove(position)
// then notify the adapter that the dataset is changed
adapter.notifyDataSetChanged();

A: try the following code:
materialsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            Resources r = getResources();
            int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
            int pxTop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6, r.getDisplayMetrics());

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(QuoteDetailActivity.this);
            alertDialog.setTitle("Delete.");

            alertDialog.setPositiveButton("Yes", (dialog, which) -> {

                LinkedTreeMap<String, Object> selectedItem = adapter.getItem(position);
                int QuoteMaterialId = ((Double) selectedItem.get("QuoteMaterialId")).intValue();

                viewModel.deleteMaterial(quoteId,QuoteMaterialId);

                adapter.remove(selectedItem);
                adapter.notifyDataSetChanged();
                //adapter.remove(adapter.getItem(position));
                //adapter.notifyDataSetChanged();

            });
            alertDialog.setNegativeButton("No", (dialog, which) -> {
                dialog.dismiss();
            });

            alertDialog.show();
            return true;            }

    });

A: Either use a different constructor with list items in MyArrayAdapter
public MyArrayAdapter(Context context, int resource, List<T> objects) {
    super(context, resource, objects);
}

or override the remove method of the adapter and manually delete the items
@Override
public void remove(T object) {
    items.remove(object);
}


Q: Inheritance - Sharing info between child and parent controllers Context
I have a custom Event Entity which has several child Entities: Problem and Maintenance (and few others but those two should be enough to describe the problem) entity classes inherit from Event entity class.
The addAction(), seeAction() and modifyAction() of ProblemController and MaintenanceController are (obviously) very similar but with some differences.
I want to have a button to display the see view of an Event, no matter if it is a Problem or a Maintenance. Same for modify.
For the add action it is a bit different: the user has to say (by clicking on child-specific button) what kind of child he want to add.
How I handle this so far
In my seeAction() and modifyAction(), I just forward the "call" depending on the type of the child:
public function seeAction(Event $event)
{
    if($event instanceof \Acme\EventBundle\Entity\Problem){
        return $this->forward('AcmeEventBundle:Problem:see', array('event_id' => $event->getId()));
    }
    elseif($event instanceof \Acme\EventBundle\Entity\Maintenance){
        return $this->forward('AcmeEventBundle:Maintenance:see', array('maintenance_id' => $event->getId()));
    }
}

I have no Event::addAction() but I have a Event::addCommon() which gathers the common parts of the addAction of Problem and Maintenance. Then I call this Event::addCommon() with Controller inheritance.
class ProblemController extends EventController
{
  public function addAction(MeasurementSite $measurementSite)
  {
    $problem = new Problem();
    $problem->setMeasurementSite($measurementSite);
    $form = $this->createForm(new ProblemType($measurementSite), $problem);

    $response = parent::addCommon($problem, $form);
    return $response;
  }

Problem
All this looks pretty ugly to me. If I want to share common things between Problem::seeAction() and Maintenance::seeAction(), I will have to call an Event function, but Event already forwarded something!! Information jumps from Parent to Child and vice versa...
I would like to know what is the proper way to manage this problem?
I looked a bit at setting Controller as a service, using PHP Traits, Routing inheritance but I couldn't extract anything clear and clean from this research...

A: I can see how you might end up chasing your tail on this sort of problem.
Instead of multiple controllers, consider have one EventController for all the routes along with individual ProblemHelper and MaintainenceHelper objects. The helper objects would have your add/see/modify methods and could extend a CommonHelper class.
Your controller would check the entity type, instantiate the helper and pass control over to it.


Q: Datepicker change event fires multiple times on manual entry I have a datepicker, that has onSelect property that will execute a "change" function on the datepicker input field. The "Change" event runs a function to fill a select list. This works so long as I choose the datepicker, but if I manually enter in a date in the input field, the change event will execute twice and the select list will have duplicated values.
    $("#txtStartDate").datepicker({
    defaultDate: +1,
    dateFormat: "mm/dd/yy", //yy format represents a (4) digit year
    minDate: new Date($("#ctl00_ContentPlaceHolder2_hidfldJunDate").val()),
    maxDate: new Date($("#ctl00_ContentPlaceHolder2_hidfldMayDate").val()),
    showOtherMonths: true,
    changeMonth: true,
    changeYear: true,
    beforeShowDay: $.datepicker.noWeekends,
    firstDay: 1,
    showButtonPanel: true,
    showOn: "button",
    onSelect: function () { $(this).change(); },
    buttonImage: "../Scripts/JQuery/ui/calendar.gif",
    buttonImageOnly: true
}).mask("99/99/9999");

$("#txtStartDate").change(function () {
    if (($("#txtStartDate").val() != "") && ($("#txtStartDate").val() != "__/__/____")) {
        var DoDate = CheckDate($("#txtStartDate").val());
        if (DoDate != "Good") {
            alert("Please enter a valid Start Date");
            $("#txtStartDate").val("");
            $("#txtStartDate").focus();
        }
        else {
            SemesterList($("#txtStartDate").val(), 0);
        }
    }
});

So what do I need to do to prevent the multiple firings of this change event so I don't get duplicates in the select list. I have even tried selectlist.remove thinking this would remove all elements in the list, but it still multiplies.
Any help is appreciated.

A: Use this syntax to remove the original binding by the Datepicker:
$("#txtStartDate").unbind('change').change(function () {
          // your code
});


Q: How to set the width of dates in moderncv? How can you custom the with of this col/field to adapt "Jun-Sep,2011" in just one line.

The MWE is copied from Moderncv: Extra vertical space after cvitem
\documentclass[11pt,a4paper,sans]{moderncv}
\moderncvstyle{classic} % banking, casual, classic, empty, oldstyle options
\moderncvcolor{blue}   % black, blue, green, grey, orange, purple, red options
\usepackage[scale=0.85]{geometry} % default scale=0.7. height= scale * layoutheight

\firstname{John}
\familyname{Doe}
\title{R\'esum\'e}     % optional

\makeatletter
\@ifpackageloaded{moderncvstyleclassic}{%
\let\oldsection\section%
\renewcommand{\section}[1]{\leavevmode\unskip\vspace*{-\baselineskip}\oldsection{#1}}%
}{%
}
\makeatother

\begin{document}
\makecvtitle
\section{Professional Experience}
    \cventry{Start--End, Year}{Intern}{Company}{Nowhere}{State}{
    \begin{itemize}
        \item Did something important here.
    \end{itemize}}

% problem with vertical space-------------------------------------------------
\section{Education}
    \cventry{Jun-Sep, 2011}{Bachelor of Arts \LaTeX}{University of \LaTeX}{}{\textit{4.0/4.0}}{}
%\vspace*{-6mm} %this will fix vertical spacing for \moderncvstyle{classic}, but create vertical spacing issues for other \moderncvstyle{xyz}.

% problem with vertical space -------------------------------------------------
\section{Skills}
    \cvitem[-0.5em]{}{
    \begin{itemize}
        \item \LaTeX
    \end{itemize}}
%\vspace*{-6mm} %this will fix vertical spacing for \moderncvstyle{classic}, but create vertical spacing issues for other \moderncvstyle{xyz}.

\section{Languages}
    \cvitem[-0.5em]{}{
    \begin{itemize}
        \item TeX-speak
    \end{itemize}}
% \cvitem{}{job description text here}

\end{document}

A: The length you need to adjust is called \hintscolumnwidth. The default is
\setlength{\hintscolumnwidth}{0.175\textwidth}

Example Output for 0.3\textwidth:

EDIT: You can also adjust the width automatically to the width of Jun-Sep, 2011 with:
\settowidth{\hintscolumnwidth}{Jun-Sep, 2011}


Q: Detect mouse speed using jQuery I want to detect mouse speed, for example the event will be fired only if the detected number is greater than 5
I found one example which I think is something similar: http://www.loganfranken.com/blog/49/capturing-cursor-speed/
but i am not able to make it see the number which is inside div and fire the event based on the resulting number, this is my attempt:
<!doctype html>

<meta charset="UTF-8">
<title>Untitled Document</title>

A: (I'm the author of the plug-in that's causing the trouble here)
The example isn't working because this.value isn't referring to the speed (it's undefined). Here's an updated version of your example:
http://jsfiddle.net/eY6Z9/
It would probably be more efficient to store the speed value in a variable rather than within the text value of an HTML element. Here’s an updated version with that enhancement:
http://jsfiddle.net/eY6Z9/2/
Hope that helps!


Q: Best practice to authenticate synchronized realm Trying to find any guidance on how to best authenticate to a synchronized realm and making sure not to use any reference to it before.
Let's assume there is no need for a user to login, but e.g. a tableview that is being populated by binding it to a realm.objects query.
If I authenticate to the remote realm in e.g. viewDidLoad() that is too late, applicationDidFinishLaunching() also too late.
I could, of course, show an empty results list first or an empty local realm, but to me that all doesn't look clean.
Any suggestions?

A: I'd recommend you to not to use Realm before you have an authenticated user, you can show some login view to handle authentication and show your other view controller after user is authenticated.
// LogInViewController

...

func logIn() {
    SyncUser.authenticate(with: credential, server: serverURL) { user, error in
        if let user = user {
            Realm.Configuration.defaultConfiguration = Realm.Configuration(
                syncConfiguration: (user, syncURL)
            )

            // Show your table view controller or use `try! Realm()`
        } else {
            // Present error
        }
    }
}

Please check also RealmTasks example here: https://github.com/realm/RealmTasks


Q: How can I use a list to create a table in html? I am writing a django app with bootstrap and I have a table with a head in one of my pages like the one below:

            header 1
            header 2
            header 3
            header 4
            header 5
            header 6
            header 7
            header 8
            header 9
            header 10

In the above example each header has its own line of code, 10 headers, 10 lines. There is a lot of repetition. I am looking for a way using HTML and not django, to not type almost the same line of code every time.
Using django I could pass the list with the headers from the page's view, like so:

        {% for header in table_headers %}
            header
        {% endfor %}

Below is a mock up in HTML of what it could be like:
table_headers = ["header_1", "header_2", ....]

        for header in table_headers
            header

Can I do something like this just in html and in django ?


Q: How do I set up proper ownership of these files? I need the directory /var/www/ (and everything inside it) to be modifiable by only authorized users.
The way I tried to do this was:
sudo groupadd webmasters
sudo usermod -G webmasters pi # My user is pi
sudo chown -R root:webmasters /var/www/
sudo chmod -R ug+rw /var/www/

...but I can't modify anything in /var/www/, nor can I create new files in it.
What am I doing wrong? How do I set this up the way it needs to be?
What I'm envisioning is:

*

*Everyone in the group webmasters can create, delete, and edit files in /var/www/

*All newly-created files/folders are owned by root:webmasters

*All newly created files have permissions 775: -rwxrwxr-x

*Is is vital that no one without authorization be able to have write permissions, OR any sort of Setuid/Setgid ability. (Authorization for write access can only be granted by Root.)

Am I taking the wrong approach to this? Do I have the right idea, but I'm just messing something up? What's going wrong?

A: It's not enough that a user's been added to a group in the /etc/group file through the usermod -G command. This updates the "database" but any shells/processes that have been already created prior to this update will not reflect that the user that owns them, pi, has been added to this new group.
Usually you don't want to use the getent commands when interrogating a shell, but rather the command id, or more specifically id -a.
example
Here I've just added my username saml to the group newgrp. The command getent confirms this:
$ getent group newgrp
newgrp:x:10000:saml

But the command id -a tells a different story in one of the shells that I already had open:
$ id -a
uid=500(saml) gid=501(saml) groups=501(saml),502(vboxusers),503(jupiter)

If I start up a new shell I'll see newgrp:
$ ssh localhost
Last login: Fri Jun 28 00:17:13 2013 from localhost.localdomain

$ id -a
uid=500(saml) gid=501(saml) groups=501(saml),502(vboxusers),503(jupiter),10000(newgrp)


Q: How to validate the length of character is equals to 5 using express-validator? I am planning to make partnerid field character length as 5 which means user will get error message if he enters less than 5 character or more than 5 characters which will include alpha-numeric character.
How can we do it using express-validator?
I tried using below code but it didn't worked
Thanks
   req.checkBody('partnerid', 'Partnerid field must be 5 character long ').len(5);

A: You can use isLength() option of the express-validator to check max and min length of 5:
 req.checkBody('partnerid', 'Partnerid field must be 5 character long ').isLength({ min: 5, max:5 });

A: You can use matches option of express-validator to check if the partner field only contains alphanumeric and has a length of 5
req.checkBody('partnerid', 'Partnerid field must be 5 character long ').matches(/^[a-zA-Z0-9]{5}$/, "i");

A: .len(5) not support in express validation, you can use .isLength(5) to check for a max and min length of 5.
req.checkBody('partnerid', 'Partnerid field must be 5 character long strong text').isLength(5);


Q: Added new website to IIS8 and still goes to Default Website Setting up a new server - 2012 with IIS8. I added a new web site to IIS8. I set the IP address and the hostname.
Yet when I browse to the site, it goes to the Default Website instead. I stopped the Default web site and I get a 404. I tried restarting IIS as well.
I read a few pages on how to set up a new website and I seem to be in compliance. The Default Website is just a fallback as I understand it. With the hostname and/or the IP address set, IIS should direct traffic to the new web site, right?
I made sure the folder had permissions for the app pool (though the Test Settings is still failing the Authorization Test.) and the IUSR. I temporarily used the Administrator account instead of pass-thtough so I could pass the Authorization Test.
I enabled ASP.Net impersonation.
I verified default document file name. I tried a simple .html to get around any ASP.net issues.
I deleted it and started from scratch, using the DefaultAppPool this time.
What am I missing here?
Thanks,
Brad


Q: Higher validation accuracy, than training accurracy using Tensorflow and Keras I'm trying to use deep learning to predict income from 15 self reported attributes from a dating site.
We're getting rather odd results, where our validation data is getting better accuracy and lower loss, than our training data. And this is consistent across different sizes of hidden layers.
This is our model:
for hl1 in [250, 200, 150, 100, 75, 50, 25, 15, 10, 7]:
    def baseline_model():
        model = Sequential()
        model.add(Dense(hl1, input_dim=299, kernel_initializer='normal', activation='relu', kernel_regularizer=regularizers.l1_l2(0.001)))
        model.add(Dropout(0.5, seed=seed))
        model.add(Dense(3, kernel_initializer='normal', activation='sigmoid'))

        model.compile(loss='categorical_crossentropy', optimizer='adamax', metrics=['accuracy'])
        return model

    history_logs = LossHistory()
    model = baseline_model()
    history = model.fit(X, Y, validation_split=0.3, shuffle=False, epochs=50, batch_size=10, verbose=2, callbacks=[history_logs])

And this is an example of the accuracy and losses:
 and .
We've tried to remove regularization and dropout, which, as expected, ended in overfitting (training acc: ~85%). We've even tried to decrease the learning rate drastically, with similiar results.
Has anyone seen similar results?

A: You can check the Keras FAQ and especially the section "Why is the training loss much higher than the testing loss?".
I would also suggest you to take some time and read this very good article  regarding some "sanity checks" you should always take into consideration when building a NN.
In addition, whenever possible, check if your results make sense. For example, in case of a n-class classification with categorical cross entropy the loss on the first epoch should be -ln(1/n).
Apart your specific case, I believe that apart from the Dropout the dataset split may sometimes result in this situation. Especially if the dataset split is not random (in case where temporal or spatial patterns exist) the validation set may be fundamentally different, i.e less noise or less variance, from the train and thus easier to to predict leading to higher accuracy on the validation set than on training.
Moreover, if the validation set is very small compared to the training then by random the model fits better the validation set than the training.]

A: There are a number of reasons this can happen.You do not shown any information on the size of the data for training, validation and test. If the validation set is to small it does not adequately represent the probability distribution of the data. If your training set is small there is not enough data to adequately train the model. Also your model is very basic and may not be adequate to cover the complexity of the data. A drop out of 50% is high for such a limited model. Try using an established model like MobileNet version 1. It will be more than adequate for even very complex data relationships. Once that works then you can be confident in the data and build your own model if you wish.
Fact is validation loss and accuracy do not have real meaning until your training accuracy
gets reasonably high say 85%.

A: I solved this by simply increasing the number of epochs

A: This indicates the presence of high bias in your dataset. It is underfitting. The solutions to issue are:-

*

*Probably the network is struggling to fit the training data. Hence, try a
little bit bigger network.

*Try a different Deep Neural Network. I mean to say change the architecture
a bit.

*Train for longer time.

*Try using advanced optimization algorithms.

A: This actually a pretty often situation. When there is not so much variance in your dataset you could have the behaviour like this. Here you could find an explaination why this might happen.

A: This happens when you use Dropout, since the behaviour when training and testing are different.
When training, a percentage of the features are set to zero (50% in your case since you are using Dropout(0.5)). When testing, all features are used (and are scaled appropriately). So the model at test time is more robust - and can lead to higher testing accuracies.

A: Adding dropout to your model gives it more generalization, but it doesn't have to be the cause. It could be because your data is unbalanced (has bias) and that's what I think..

A: I don't think that it is a drop out layer problem.
I think that it is more related to the number of images in your dataset.
The point here is that you are working on a large training Set and a too small validation/test set so that this latter is way too easy to computed.
Try data augmentation and other technique to get your dataset bigger!

A: I agree with @Anas answer, the situation might be solved after you increase the epoch times.
Everything is ok, but sometimes, it is just a coincidence that the initialized model exhibits a better performance in the validation/test dataset compared to the training dataset.


Q: Data returns array instead of an object Its probably some stupid mistake but tell me what am i doing wrong?
I made it in 2 ways.

*

*In the first solution i send the data from my VsCode to the database and then retrieve it.

*In the second solution i just send parsed json file as a resposne directly from VsCode folder.
I want the data from the first solution return me an object (like in the 2nd solution)  not an array.
1 solution:

//IMPORTING TO DATABASE

const questions = JSON.parse(
  fs.readFileSync(`${__dirname}/questions.json`, "utf-8")
);

const importData = async () => {
  try {
    await Questions.create(questions);
    console.log("Data successfully loaded!");
  } catch (err) {
    console.log(err);
  }
  process.exit();
};

//MODEL

const mongoose = require("mongoose");

const questionsSchema = new mongoose.Schema({
  beginner: [
    {
      questionText: String,
      answerOptions: Array,
    },
  ],
  intermediate: [
    {
      questionText: String,
      answerOptions: Array,
    },
  ],
  advanced: [
    {
      questionText: String,
      answerOptions: Array,
    },
  ],
});

// RESPONSE
const getAllQuestions = async (req, res, next) => {
  try {
    const data = await Questions.find();

    res.status(200).json({
      status: "success",
      data,
    });
  } catch (err) {
    res.status(500).json({
      status: "fail",
      message: err,
    });
  }

  next();
};

my json structure:
{
  "beginner": [...],
  "intermediate": [...],
   "advanced": [...],
}

2nd solution:
When i just simply read the json file and send it as a response it works correctly:

const fs = require("fs");
const dataPath = require("path").resolve(__dirname, "../data/questions.json");

const data = JSON.parse(fs.readFileSync(dataPath));

exports.getAllQuestions = async (req, res, next) => {
  try {
    res.status(200).json({
      status: "success",
      data,
    });
  } catch (err) {
    res.status(500).json({
      status: "fail",
      message: err,
    });
  }

  next();
};

A: To add further to @eol's response, if you want to query on the entry db collection, you need to pass an empty object to the Question.find({}) method.
If you want to return one of the different difficulties within the doc, then I believe you treat the response like any other object with properties.


Q: Neo4j not performing for undirected relationship I've been working with neo4j 4.1 for a while now and whilst I feel that the graph structure should be a good fit for my problem, I can't get it to perform in any reasonable time.
I'll detail the model and problem below, but I'm wondering whether (a) graphs are just not a good fit or (b) I've modelled the problem incorrectly.
In my domain, I have two labels: Person and Skill. Each as an id attribute and there is an index on this attribute.
Skills are related to one another in a parent-child relationship, implying that one or more child skills belong to the parent skill, as follows:
(s:Skill)-[r:IS_IN_CAT]->(s2:Skill)
A Person is related to a Skill as follows:
(p:Person)-[r:HAS_SKILL]->(s:Skill)
This is illustrated as below:

The question I want to ask is, given a Person who has a skill, find me all paths to all other people via that skill.
In the diagram above, if Person A was the person, I'd expect 2 paths:
(Person A) - [HAS_SKILL] - (Skill 1-1-1) - [IS_IN_CAT] - (Skill 1-1) - [IS_IN_CAT] - (Skill 1-1-2)  - [HAS_SKILL] - (Person B)
And
(Person A) - [HAS_SKILL] - (Skill 1-1-1) - [IS_IN_CAT] - (Skill 1-1) - [IS_IN_CAT] - (Skill 1)  - [IS_IN_CAT] - (Skill 1-2) - [HAS_SKILL] - (Person C)
The way I'm asking this query is as follows.
MATCH (p:Person {id: 100}) - [h:HAS_SKILL] -> (s:Skill) - [r:IS_IN_CAT*..] - (s2:Skill) <- [h2:HAS_SKILL] - (p2:Person)
For any moderately sized graph (10,000 skills, 1000 people, 5 skills per person) this doesn't ever return.
I'm fairly sure it's the undirected nature of the [r:IS_IN_CAT*..] part of the query but I don't see how to re-model to make this perform any better.
Any help would be appreciated.

A: I eventually solved this by changing my query to rely on directed relationships only. This brought the performance down to sub-second for very large data sets.
The query ended up looking like:
MATCH (p:Person {id: 100}) - [h:HAS_SKILL] -> (s:Skill) - [r:IS_IN_CAT*..] -> (parentSkill:Skill) <- [r:IS_IN_CAT*..] - (s2:Skill) <- [h2:HAS_SKILL] - (p2:Person)

The introduction of the parentSkill allowed the relationships to stay directional.