text:
Q: TFS Build Architecture I am preparing to move my team's source control from VSS over to TFS 2008.
This is for an asp.net website, and I am currently using a combination of nant scripts and Cruise Control to do all of the builds and deployments.
I've been trying to wrap my head around the best way to architect TFS build to do the same thing I'm doing with NANT and Cruise Control, but I can't determine the best approach.
Here are my requirements:

*

*When code reaches a certain point, I manually apply a label to it.

*This labeled code needs to be built and deployed to any of our 25 different Dev, QA, or production environments.

*Any of these 25 environments can be on any current or past labeled version of the application.

*I need to be able to deploy any labeled version of the application to any of the environments.

I'm currently accomplishing the above using NANT to perform the build, and using Cruise Control to just pass in command line options for which environment(s) to build and deploy. I have a Nant config file with a list of all of my environments, and an associated label each environment should currently be using. This file gets manually updated whenever a new label is created.
I know the approach I'm using for NANT probably won't be the same as with Team Build, but has anyone done something similar with Team Build and could share how you accomplished it?

A: *

*Labeling in TFS is much more robust than in VSS.  When you create a label, you can create based on a changeset, date, workspace version, heck even a different label.  (BTW, I was grabbing a link and came across this post that you might find relevant.)

*By default, a Team Build will build from the latest version of code in source, but you can override the "CoreGet" target in a build to build a specific version.  Aaron Hallberg (a.k.a. TFS's John Skeet) shows an example here.

*see 4.

*I haven't personally had this difficult of a requirement, but I've done something similar.  When you queue the build, you can pass in any number of parameters in a couple important ways, 1) through the response file and 2) at queue time (simple example here).      In either case, two parameters could be which environment and which label/version number.  At my current project, I have continuous integration turned on, so when code in a workspace is checked in, the current code is automatically labeled, pull the specifics for my drop location from the response file, then deploy to the respective location.
Given the fact that you have ~25 environments and n number of versions/labels, you could build a simple GUI that reads the current labels through the TFS API and lets you pick which version to build to a particular environment.

A: To answer the question, the way I addressed this was to use a combination of a custom build task, cruise control, and msbuild.
The custom build task allowed me to get the latest version from a specific branch and label.
Cruise control allowed me to pass in specific information for a specific build to MSbuild, using a config file, but initiate the build from a UI.
msbuild was used like normal, however it was called from cruise control, and the custom build task did most of the work.


text:
Q: Website Button does not work in mobile Layout I have a really weird error that I'm trying to resolve. On a website I built with the visual composer, one of the buttons that leads to an internal anchor (#whatwedosmall) on the same site just wont work on the mobile layout.
This is the site: https://b8j3ssh.myraidbox.de/
I created 3 layouts (large, medium, small) and each section has a certain ID (for example the What we do section in large is named: #whatwedolarge and so on. Within the site there are buttons that lead to these sections and it works great!
However, the very first button on mobile (breakpoint smaller than 600px) just wont work at all. I tried everything but I cannot get it to work...
Can you help me?

A: When you inspect the page at a breakpoint < 600px you can see that your button (actually an ) is being covered by the rev_slider_1_1 so the actual  can never be hovered or clicked.

If you delete that slider from the DOM in DevTools or set the height manually, then the hovering and click work. As you can see in the screenshot below, manually setting the Slider height to 850px allows me to hover and click

You need to determine how the height of that slider is being determined and fix that in your code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Asp.net MVC 3 global querystring? I'm building a generic web application for two business groups. The logo/banner needs to be changed based on the querystring. For example, if the url is http://foo.com/test?bg=a it shows the logo for business group a and if the url is http://foo.com/test?bg=b it shows the logo for business group b. This is not a problem if I only had one action. But I have many actions.
I could check the query string on all actions but there must be a nice way to do it. I have an perception that I need to do something with the routing stuff but just don't know how. Can anyone please let me know how to do it?

A: You can write a Custom Routing Handler and use routing to extract the querystring as a parameter, and pass into RouteData where it can be accessed anywhere.
public class RouteWithQueryStringValueHandler : MvcRouteHandler
{
    private readonly string key;

    public RouteWithQueryStringValueHandler(string key)
        : base()
    {
        this.key = key;
    }

    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var request = requestContext.HttpContext.Request;
        var qsValue = requestContext.HttpContext.Request[key];
        var router = base.GetHttpHandler(requestContext);
        requestContext.RouteData.DataTokens[key] = qsValue;
        return router;
    }
}

Register as follows:
routes.Add(new Route("{controller}/{action}/{id}",
                 new RouteValueDictionary(
                         new { controller = "Home",
                               action = "Index",
                               id = UrlParameter.Optional
                         }),
                 new RouteWithQueryStringValueHandler("bg")));

Get the logo for Routing data:
var logo = RouteData.DataTokens["bg"];

A: You could write a custom helper method which based on the query string parameter will append a given class name to some div. Then of course you would have different class definitions in your CSS file applying a background-image.
For example:
public static class HtmlExtensions
{
    public static string BannerClass(this HtmlHelper html)
    {
        var bg = html.ViewContext.Controller.ValueProvider.GetValue("bg");
        if (bg == null || string.IsNullOrEmpty(bg.AttemptedValue))
        {
            // no bg parameter => return a default class
            return "default_banner";
        }

        if (string.Equals("a", bg.AttemptedValue))
        {
            return "banner_a";
        }
        else if (string.Equals("b", bg.AttemptedValue))
        {
            return "banner_b";
        }

        // unknown value for the bg parameter => return a default class
        return "default_banner";
    }
}

and then in your _Layout you could apply this class to some placeholder like a div or even the body:

OK

This way it will always be applied for all view in your application.
Now all that's left is to define your CSS rules for the different banners:
.default_banner {
    background-image: url('../images/default_banner.png')
}

.banner_a {
    background-image: url('../images/banner_a.png')
}

.banner_b {
    background-image: url('../images/banner_b.png')
}

A: If you are using Razor (and I believe this does break the separation of responsibilities guideline) change the _ViewStart.cshtml to do it.
@{
    if (/* Context.QueryString Params, not at my development box*/)
    {
        Layout = "~/Views/Shared/Layout-Group1.cshtml";
    }
    else
    {
        Layout = "~/Views/Shared/Layout-Group2.cshtml";
    }
}

I prefer this route because it makes any future requests (layout + css + javascript) fairly easy because they can all be updated within the Layout.

A: Place some code in your master page(s) to make the decision as to which banner to display based on the query string. Ideally the code wouldn't be completely inline i.e. it'd be in a helper class.


text:
Q: How to correctly setup RabbitMQ on Openshift I have created new app on OpenShift using this image: https://hub.docker.com/r/luiscoms/openshift-rabbitmq/
It runs successfully and I can use it. I have added a persistent volume to it.
However, every time a POD is restarted, I loos all my data. This is because RabbitMq uses a hostname to create database directory.
For example:
node           : rabbit@openshift-rabbitmq-11-9b6p7
home dir       : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config
cookie hash    : BsUC9W6z5M26164xPxUTkA==
log            : tty
sasl log       : tty
database dir   : /var/lib/rabbitmq/mnesia/rabbit@openshift-rabbitmq-11-9b6p7

How can I set RabbitMq to always use same database dir?

A: You should be able to set an environment variable RABBITMQ_MNESIA_DIR to override the default configuration. This can be done via the OpenShift console by add an entry to environment in the deployment config or via the oc tool, for example:
oc set env dc/my-rabbit RABBITMQ_MNESIA_DIR=/myDir
You would then need to mount the persistent volume inside the Pod at the required path. Since you have said it is already created, then you just need to update it, example:
oc volume dc/my-rabbit --add --overwrite --name=my-pv-name --mount-path=/myDir
You will need to make sure you have correct r/w access on the provided mount path
EDIT: Some additional workarounds based on issues in comments
The issues caused by the dynamic hostname could be solved in a number of ways:
1.(Preferred IMO) Move the deployment to a StatefulSet. StatefulSet will provide stability in the naming and hence network identifier of the Pod, which must be fronted by a headless service. This feature is out of beta as of Kubernetes 1.9 and tech preview in OpenShift since version 3.5

*Set the hostname for the Pod if Statefulsets are not an option. This can be done by adding the environment variable oc set env dc/example HOSTNAME=example to make the hostname static and setting RABBITMQ_NODENAME to do likewise.

A: I was able to get it to work by setting the HOSTNAME environment variable. OSE normally sets that value to the pod name, so it changes everytime the pod restarts.  By setting it the pod's hostname doesn't change when the pod restarts.
Combined with a Persistent Volume the the queues, messages users and i assume whatever other configuration is persisted through pod restarts.
This was done on an OSE 3.2 server.  I just added an environment variable to the deployment config.  You can do it through the UI or with the OC CLI:
oc set env dc/my-rabbit HOSTNAME=some-static-name

This will probably be an issue if you run multiple pods for the service, but in that case you would need to setup proper RabbitMq clustering, which is a whole different beast.

A: The easiest and production-safest way to run RabbitMQ on K8s including OpenShift is the RabbitMQ Cluster Operator.
See this video on how to deploy RabbitMQ on OpenShift.


text:
Q: Deleting Rows in UITableView Swift 3 okay im making an app where you add items to a cart and it updates as you add. i do all the adding fine, but i cant get deleting to work. in the cart cell i would need to remove from 3 arrays, but that doesn't seem to be the problem because i keep getting this error:

"Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'"

i'm not really sure what i'm doing wrong here. i've followed a few tutorials and they all seem to be doing the same thing. any help is appreciated thanks in advance.
heres some of my code:
//declaring arrays to show in cell
var cartKeys = [String]()
var cartValues = [String]()

var deets = [[String]]()
var count = 0

//populating arrays from original arrays
func populateCart(){

    for (key,value) in MenuStore.shared.cart {

        self.cartKeys.append(key)
        self.cartValues.append(value)
    }

    for i in MenuStore.shared.cartAndItems{
        for (k,v) in i {
            deets.append(v)
        }
    }

    print("DEETS \(deets)")

    for c in cartView.visibleCells {

        count += 1

    }

}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    switch tableView{

    case cartView:
        if editingStyle == .delete{
            let index = indexPath.row
            print(index)

            cartKeys.remove(at: index)
            cartValues.remove(at: index)

            deets.remove(at: index)

            tableView.deleteRows(at: [indexPath], with: .automatic)

        }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    switch tableView{

    case cartView:
        let cartCell = tableView.dequeueReusableCell(withIdentifier: "cartCell", for: indexPath) as? CartCell

        cartCell?.cartTitle.text = cartKeys[(indexPath as NSIndexPath).row]
        cartCell?.cartPrice.text = cartValues[(indexPath as NSIndexPath).row]
        cartCell?.cartDetails.text = deets[count].joined(separator: ", ")

        return cartCell!

ps. if anyone wants to help with replacing the visible cells call thatd be great. id like to loop through all the cells even if their not visible on the screen.


text:
Q: Hiding 'Bottom Navigation Bar' whilst keyboard is present - Android I have a small demo chat UI application. This application has a bottom navigation bar. I need the bottom navigation bar to hide when the keyboard appears.
Here is an example of the chat UI
As you can see when you click in the EditText element, the keyboard appears but the bottom navigation bar stays visible. I have tried methods such as this measurement method, but the UI elements flicker like this.
Is there a proper way to hide the bottom navigation bar when the keyboard is visible?
EDIT:
In the below activity you can see where I set the keyboard listener to adjust the position of UI elements when the keyboard is determined as being visible.
This is my activity code, uses setKeyboardListener method from the above link and set it in onCreateView:
package uk.cal.codename.projectnedry.TeamChatFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.roughike.bottombar.BottomBar;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import uk.cal.codename.projectnedry.R;
import uk.cal.codename.projectnedry.TeamChatFragment.ListAdapter.TeamChatListAdapter;
import uk.demo.cal.genericmodelviewpresenter.GenericMvp.GenericMvpFragment;

import static android.view.View.GONE;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link TeamChatView.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link TeamChatView#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TeamChatView extends GenericMvpFragment implements TeamChatContract.RequiredViewOps {

    private OnFragmentInteractionListener mListener;
    @BindView(R.id.teamChatList)
    RecyclerView mTeamChatRecyclerView;
    @BindView(R.id.teamChatSendButton)
    ImageButton mTeamChatSendButton;
    @BindView(R.id.messageTextInput)
    EditText mMessageTextInput;
    TeamChatListAdapter mTeamChatListAdapter;
    TeamChatListAdapter.ClickListener mTeamChatListClickListener;
    private ArrayList<String> mTestMessageList;

    public interface OnKeyboardVisibilityListener {
        void onVisibilityChanged(boolean visible);
    }

    public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
        final View activityRootView = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);

        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            private boolean wasOpened;

            private final int DefaultKeyboardDP = 100;

            // From @nathanielwolf answer...  Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
            private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);

            private final Rect r = new Rect();

            @Override
            public void onGlobalLayout() {
                // Convert the dp to pixels.
                int estimatedKeyboardHeight = (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());

                // Conclude whether the keyboard is shown or not.
                activityRootView.getWindowVisibleDisplayFrame(r);
                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                boolean isShown = heightDiff >= estimatedKeyboardHeight;

                if (isShown == wasOpened) {
                    Log.d("Keyboard state", "Ignoring global layout change...");
                    return;
                }

                wasOpened = isShown;
                listener.onVisibilityChanged(isShown);
            }
        });
    }

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment TeamChatView.
     */
    public static TeamChatView newInstance() {
        TeamChatView fragment = new TeamChatView();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(TeamChatPresenter.class, TeamChatModel.class, savedInstanceState);
    }

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

        mTestMessageList = new ArrayList<>();
        this.mTeamChatListAdapter = new TeamChatListAdapter(mTestMessageList);
        this.mTeamChatRecyclerView.setAdapter(this.mTeamChatListAdapter);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        this.mTeamChatRecyclerView.setLayoutManager(linearLayoutManager);

        this.mTeamChatSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!String.valueOf(mMessageTextInput.getText()).equals("")) {
                    getSpecificImpOfGenericPresenter().sendMessage(String.valueOf(mMessageTextInput.getText()));
                    mMessageTextInput.setText("");
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                }
            }
        });

        setKeyboardListener(new OnKeyboardVisibilityListener(){
            @Override
            public void onVisibilityChanged(boolean visible) {
                RelativeLayout contentFrame = (RelativeLayout) getActivity().findViewById(R.id.content_company_navigation);
                BottomBar lowerNavigationBar = (BottomBar) getActivity().findViewById(R.id.bottomBar);
                if (visible) { // if more than 100 pixels, its probably a keyboard...
                    lowerNavigationBar.setVisibility(GONE);
                    contentFrame.setPadding(0, 0, 0, 0);
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                } else {
                    contentFrame.setPadding(0, 0, 0, convertDpToPixel(60, getContext()));
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                    lowerNavigationBar.setVisibility(View.VISIBLE);
                }
            }
        });
        return view;
    }

    /**
     * This method converts dp unit to equivalent pixels, depending on device density.
     *
     * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent px equivalent to dp depending on device density
     */
    public static int convertDpToPixel(float dp, Context context){
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        int px = (int) (dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }

    public void addToTestMessageList(String str){
        this.mTestMessageList.add(str);
        this.mTeamChatListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
       // getView().getViewTreeObserver().removeGlobalOnLayoutListener(test);
    }

    @Override
    public TeamChatPresenter getSpecificImpOfGenericPresenter() {
        return (TeamChatPresenter) this.mPresenter;
    }
}

This is my XML layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="uk.cal.codename.projectnedry.TeamChatFragment.TeamChatView">

    <android.support.v7.widget.RecyclerView
        android:layout_above="@+id/chatViewMessageEntryLayout"
        android:id="@+id/teamChatList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:isScrollContainer="false"
        android:paddingTop="10dp"
        android:scrollbars="vertical" />

    <RelativeLayout
        android:id="@+id/chatViewMessageEntryLayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <View
            android:id="@+id/chatViewMessageEntrySeperator"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#e3e3e8" />

        <EditText
            android:id="@+id/messageTextInput"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            android:layout_below="@+id/chatViewMessageEntrySeperator"
            android:layout_toLeftOf="@+id/teamChatSendButton"
            android:background="@android:color/transparent"
            android:hint="Enter message"
            android:inputType="textCapSentences|textMultiLine"
            android:maxLength="1000"
            android:maxLines="4"
            android:paddingLeft="10dp" />

        <ImageButton
            android:id="@+id/teamChatSendButton"
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_gravity="center"
            android:background="#00B9EF"
            android:src="@drawable/ic_send_white_24dp" />

    </RelativeLayout>

</RelativeLayout>

A: Add this line in onResume() of your Activity or Fragment.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

It is worked for me. Just try it once.

A: Just add the attribute below to every activity in your AndroidManifest.xml file.
<activity
    android:name=".MainActivity"
    android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />

A: Actively listen for the Keyboard(IME) open/close events and show/hide bottom navigation accordingly.
We can make use of the WindowInsetsCompat API which makes this job effortless.
Step 1: Make sure you have migrated to AndroidX
Step 2: In your Fragment inside onCreateView add the listener for Keyboard(IME) events

ViewCompat.setOnApplyWindowInsetsListener(window.decorView.rootView) { _, insets ->

   //This lambda block will be called, every time keyboard is opened or closed

    val imeVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
    if(imeVisible){
     //Now show-hide bottom navigation accordingly
    }

    insets
}

This is all you need
For more info on window insets, you can check out this in-depth article
NOTE:Earlier detecting Keyboard open/close events was not an easy task. Android Devs resorted to all types of hacks to accomplish this. But after decades of requests, prayers and rants Google finally came up with WindowInsets API. Thank you, Google

A: For API 21+:
Firstly, set "android:windowSoftInputMode" for the activity to "adjustResize" in AndroidManifest.xml
Secondly, in your acticity's onCreate method register the following listener:
window.decorView.setOnApplyWindowInsetsListener { view, insets ->
    val insetsCompat = toWindowInsetsCompat(insets, view)
    val isImeVisible = insetsCompat.isVisible(WindowInsetsCompat.Type.ime())
    // below line, do the necessary stuff:
    dataBinding.bottomNavigation.visibility = if (isImeVisible) View.GONE else View.VISIBLE
    view.onApplyWindowInsets(insets)
}

A: you just add this code in your manifest like this way..
 <activity android:name=".MainActivity"
        android:windowSoftInputMode="adjustPan">

this works for me.. happy coding

A:  private boolean keyboardListenersAttached = false;
private ViewGroup rootLayout;

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

    rootLayout = (ViewGroup) view.findViewById(R.id.settings_layout);
    attachKeyboardListeners();

    return view;
}

    private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new
    ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int heightDiff = rootLayout.getRootView().getHeight() -
        rootLayout.getHeight();
        if (getActivity() != null) {
            int contentViewTop =
           getActivity().getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
            LocalBroadcastManager broadcastManager =
            LocalBroadcastManager.getInstance(getContext());
            Rect r = new Rect();
            rootLayout.getWindowVisibleDisplayFrame(r);
            int screenHeight = rootLayout.getRootView().getHeight();

            // r.bottom is the position above soft keypad or device button.
            // if keypad is shown, the r.bottom is smaller than that before.
            int keypadHeight = screenHeight - r.bottom;
            if (keypadHeight > screenHeight * 0.15) {
                onHideKeyboard();

                Intent intent = new Intent("KeyboardWillHide");
                broadcastManager.sendBroadcast(intent);
            } else {
                int keyboardHeight = heightDiff - contentViewTop;
                onShowKeyboard(keyboardHeight);

                Intent intent = new Intent("KeyboardWillShow");
                intent.putExtra("KeyboardHeight", keyboardHeight);
                broadcastManager.sendBroadcast(intent);
            }
        }else {

        }
    }
};

protected void onShowKeyboard(int keyboardHeight) {
    System.out.println("keyboard is shown");
    dashboardActivity.bottomNavigationView.setVisibility(View.VISIBLE);
    dashboardActivity.fab.setVisibility(View.VISIBLE);

}
protected void onHideKeyboard() {
    System.out.println("keyboard is hide");
    dashboardActivity.bottomNavigationView.setVisibility(View.INVISIBLE);
    dashboardActivity.fab.setVisibility(View.INVISIBLE);
}

protected void attachKeyboardListeners() {
    if (keyboardListenersAttached) {
        return;
    }

    rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);
    keyboardListenersAttached = true;
}

in Manifest.xml file add
<activity
        android:name=".Activity.DashboardActivity"
        android:windowSoftInputMode="adjustResize"

         />

A: Add the attribute : android:windowSoftInputMode="adjustResize"" in your manifest inside activity tag:
 <activity
        android:name=".YourActivity"
        android:windowSoftInputMode="adjustResize"/>

NB: I suggest, You should use NestedScrollView as the parent layout.
Hope this helps.

A: In my case, I am using DrawerLayout as a parent view with some layout content and A Navigation Bottom Bar.
In Manifest file add "android:windowSoftInputMode="adjustPan" this TAG with Activity and this working fine.

A: I ended up using the height measuring method that seems to be the standard way of soft keyboard detection which is described in this answer. However, I used this library's implementation of it, as it is still the same ViewTreeObserver.OnGlobalLayoutListener method, implemented well, and allowed me to abstract the code out of my applications main codebase.
When this keyboard visibility listener is triggered, I then hide/show the bottom navigation bar (which I have explained here).

A: The easiest implementation, Add AndroidManifest.xml in
<activity android:windowSoftInputMode="adjustPan"/>

hopefully this helps someone out. Enjoy !

A: <activity android:name=".Activities.OrderSceenWithOrder"
   android:windowSoftInputMode="adjustPan"
    >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

A: That answer might be helpful for people still looking for solution.
Bottom Navigation bar moves up with keyboard

A: Add this onResume() in your fragment
@Override
public void onResume() {
    Objects.requireNonNull(getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
    super.onResume();
}

Hope this helps someone!

A: That solution works for me and it also doesn't show overlapped bottom navbar
just add this line to your activity:
android:windowSoftInputMode="adjustResize|adjustPan"


text:
Q: How to create recurring event with every 2 days/weeks/months/years in Google Calendar API PHP I want to create a google calendar event like this through Google Calendar API V3 in PHP,
Repeat every 3 days/weeks/months/years with 5 cycles.
I've checked,
https://developers.google.com/calendar/v3/reference/events/insert
But how to add the event like that? Is there any way?
Thanks in advance.

A: What you want to create is a recurring event. Creating recurring events is similar to creating a regular (single) event with the event resource's recurrence field set. To learn more about recurrence rule, you can visit this link.
An example of a recurring event is:
$event = new Google_Service_Calendar_Event();
$event->setSummary('Appointment');
$event->setLocation('Somewhere');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2011-06-03T10:00:00.000-07:00');
$start->setTimeZone('America/Los_Angeles');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2011-06-03T10:25:00.000-07:00');
$end->setTimeZone('America/Los_Angeles');
$event->setEnd($end);
$event->setRecurrence(array('RRULE:FREQ=WEEKLY;UNTIL=20110701T170000Z'));
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail('attendeeEmail');

What makes this different from a single event is the following line:
$event->setRecurrence(array('RRULE:FREQ=WEEKLY;UNTIL=20110701T170000Z'));

This line makes the single event occur again every week until July 1.
Another example: An all-day event starting on June 1st, 2015 and repeating every 3 days throughout the month, excluding June 10th but including June 9th and 11th
...
"start": {
 "date": "2015-06-01"
},
"end": {
 "date": "2015-06-02"
},
"recurrence": [
 "EXDATE;VALUE=DATE:20150610",
 "RDATE;VALUE=DATE:20150609,20150611",
 "RRULE:FREQ=DAILY;UNTIL=20150628;INTERVAL=3"
],
…

For your case, you may create a recurring event that has an RRULE of FREQ=DAILY;UNTIL=20190229;INTERVAL=3 for every 3 days. Change FREQ to WEEKLY for every 3 weeks and UNTIL to adjust how many cycles.


text:
Q: How to get int from IndexPath I would like to calculate the int value of a IndexPath that has rows and sections to then use to select a object from a NSArray using ObjectAtIndex.
I only have a string value from the UITable so I am trying to relate the indexpath value selected to the ObjectAtIndex path of my actual array.
This is my code so far, but I am getting an error because I am trying to use indexPath in place of a int.
filterDataArray = [dataArrayOfDictionaries objectAtIndex:indexPath];

so my question is how can i change indexPath Into an int. any help would be greatly appreciated.

A: so in your case you can use combination of both the row and section values try like this,
int totalRows = indexPath.row; //current section row value

for (int n = 0; n < indexPath.section; n++) {//here current section value.

    totalRows += [tableView numberOfRowsInSection:n];// here add rows in every section
}

A: See this for better understanding about NSIndexPath.
If you are using NSArray and table view with only one section (one is by default if you do not specify numberOfSections: method). Try this.
filterDataArray = [dataArrayOfDictionaries objectAtIndex:indexPath.row];


text:
Q: Copy output of custom target in one CSPROJ into another CSPROJ So I'm developing a game engine framework for myself in C#/.NET and I have been trying to simplify building shader files (the rendering engine consumes SPIR-V files, which I want to generate from GLSL source).
My current approach has been to use a custom .targets file which is imported into a CSPROJ, and that file defines a custom target like this:
<Target
    Name="Vert"
    AfterTargets="Build">
    <MakeDir Directories="$(OutputPath)%(VertShader.RelativeDir)"/>
    <Exec Command='"$(ENGINE_ROOT)\tools\glslang\windows-x64\glslangValidator.exe" -V %(VertShader.Identity) %(VertShader.OptLevel) -o $(OutputPath)%(VertShader.Identity).spv'></Exec>
</Target>

The general idea behind this is it takes VertShader items, runs the .vert file through glslang, and spits the output .vert.spv file into the build output directory.
This works great, almost.
The problem is, if I have Project A that has a bunch of shaders, and then Project B which has a reference to Project A, I want to copy the .vert.spv shaders that Project A generates into the build output directory of Project B, but I haven't had much luck wrangling the target syntax to do what I want.
Is there any way I can get this working the way I'm describing?

A: I am not sure I understand your problem correctly, but if you want your .vert.spv copied to another folder use File.Copy()

A: Alright so I actually did manage to figure it out on my own I think, adding an answer in case it's helpful to anyone else.
Adding this to my .targets file appears to allow them to be copied to any dependent project. I believe this is basically registering all of the files I'm creating with a list of files that MSBuild copies to whatever the current build output directory is (which causes them to get copied to any project that references this one)
<Target
    Name="IncludeVert"
    BeforeTargets="GetCopyToOutputDirectoryItems">
    <ItemGroup>
        <CompiledVerts Include="@(VertShader -> '$(OutputPath)%(RelativeDir)%(Filename).vert.spv' )">
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
            <TargetPath>%(RelativeDir)%(Filename).vert.spv</TargetPath>
        </CompiledVerts>
        <AllItemsFullPathWithTargetPath Include="@(CompiledVerts->'%(FullPath)')"  />
    </ItemGroup>
</Target>


text:
Q: How to "$(document).ready()" on "frames"? I named "frames" the pages that contain some small content that I load multiple times in my php main page via AJAX on specific divs that will show up multiple times also in various places.
Real situation: I have a "Reply" div that contains all the replies to some message, and there is a "Reply" button that loads up a php page inside a div via AJAX with the Reply Input and form. I need to load a text editor on this input via javascript when this page loads up.
My problem is I use a  on every page that gets loaded:

And that loads it up fine, except when I keep opening that same pages again and again. Then it stops working.
When I look into the HTML to see what I'm getting I can't find the  that gets loaded with the page. It's like it didn't even load.
I don't think placing the  tags inside the php page is the best approach, I need to be able to create some kind of event that gets triggered when the pages gets loaded but without placing the  inside every page.
So here is the question: How to execute the action of loading the text editor via javascript when that page gets ready without placing a  inside every page?
I'm open to other approachs since this is very confusing to me and I don't know what are the best practices in this case.
Following real code (The page with the form tags is a php page with a "header" and "footer" which loads with every form).
reply_page.php:
(Notice that I use PHP to write the Id of the reply on the elements so they don't get the same name)

<?php
        echo 'Reply*';
        echo form_textarea(array('name'=>'reply-'.$text_add_itens, 'rows'=>'3',     'class'=>'form-control tinymce'.$this->uri->segment(3), 'id'=>'reply'),
                '');

?>

function "load_tinymce":
function load_tinymce(where)
{
    tinymce.init({
        selector: where,
        theme: "modern",
        plugins: [
            "autolink lists link image hr anchor",
            "code",
            "media nonbreaking contextmenu directionality",
            ""
        ],
        toolbar1: "undo redo | bold italic underline bullist numlist outdent indent | link image",
        language: "pt_BR",
        document_base_url: url_base,
        relative_urls: true,
        extended_valid_elements:"iframe[*],span[*],style[*]",
        content_css: url_base+"css/bootstrap.css",
        menubar:false,
        statusbar:false,
        forced_root_block : false,
    });
}

My alert "'it did get in here..'" always get triggered with the right Id on it, BUT the text editor does not load on the first page loaded AFTER I load the second page. Meaning that only the last page loaded works.
UPDATE:
Performing some more tests I was able to observe that it is behaving like this:
I have 3 messages which opens up replies forms.
I open the #1 message and open the reply form, the text editor gets loaded.
I open the #2 message and the text editor gets loaded, all good.
When I go back to #1, and close and open the reply form again, the text editor DOES NOT load. Ok. So it got overwrited right?
I open the #3 message and open the reply form, the text editor DOES NOT get loaded anymore.
After the second time I opened the reply form, none of the forms I opened after gets the text editor BUT I can close and open that second form all I want and it works fine.

A: Without really knowing how you call it, i could suggest following method. It first check if your script for editor was already loaded (in this case, jquery-ui), and if not loads it.
Once it is loaded, it also calls the function to show the dialog, if you click on another element (calling the same function), it doesn't reload, and simply calls the "editor" directly, the load function gets the div element as an argument, and this argument is added to the addEditorToScript function (in that case, as the this object)
Update
I made the update to use the tinymce. The script should go where you current jquery script is, the div should get a click event, and at least a unique id :) (it can be a textarea as well), does that help you better?

function loadMe(divElement) {
  console.log(divElement.innerHTML);
  if (divElement && divElement.innerHTML.indexOf('Click to reply')) {
    divElement.innerHTML = '... loading, please wait ...';
    var callEditor = addEditorToScript.bind(divElement);
    if ($('#editorScript').length === 0) {
      console.log('loading jquery-ui');
      var scriptTag = document.createElement('script');
      scriptTag.id = 'editorScript';
      scriptTag.src = 'http://tinymce.cachefly.net/4.1/tinymce.min.js';
      $(scriptTag).on('load', callEditor);
      document.body.appendChild(scriptTag);
      return;
    }
    setTimeout(callEditor, 0);
  }
}

function addEditorToScript() {
  console.log(this);
  console.log(arguments);
  tinymce.init({
    selector: '#' + this.id
  });
}

Lorem

    Ipsum

    Click to reply

Delorem

    Something

    Click to reply


text:
Q: Add new language to existing Xcode project localization I'm working on an existing Xcode 3.2.2 Universal iPhone OS project which is already localized for 4 languages (EN, IT, DE and FR). We are now adding a new language (JA) into this project.
Each existing .lproj folder (en.lproj, it.lproj, de.lproj and fr.lproj) has almost 60 files - including PNGs, HTMLs and the Localizable.strings file. Each one of those files appear as localized groups inside Groups & Files in Xcode. They're spread all over the tree.
If I right-click one of those groups (say, Localizable.strings) inside Xcode, Get Info, click on "Add Localization" and type "ja" - as the Xcode docs suggest, nothing happens. From what I read in this newgroup, it's possibly because of the way those folders are named. If they were named like English.lproj and Italian.lproj, this was supposed to work.
So, for me to actually import a new language localized file into the existing group, I have to:

*

*Right-click the localized group file.

*Choose "Add Existing File".

*Select the corresponding file inside the ja.lproj folder.

I'm about to get a new ja.lproj folder with those 60 localized files and would love to import them in the project in a way that doesn't involve searching for every single file in Groups & Trees and performing those steps... for every one of those 60 files.
Is that possible? Is there a right (or better) way to import a new language into this Xcode project?

A: I found one simple solution. After you right click any multi lingual resource file and choose |Add|Existing Files...| you can select at once all files you wish to add. After you choose the encoding, xCode will automatically add all files under the resources they should be in. I hope this will work for you.

A: In Xcode 7+ it's pretty simple:

*

*Choose your localizable.strings file and tap on "Localize...":

*Next window will ask you if you want the current localizable.strings file should be the default language, in my case English should be the default so I chose 'Base'

*Choose your project from the navigation bar, choose your project again, switch to 'Info' and tap the '+' button below the Localizations title:

*All you have to do now is to choose the langauge you want to translate and mark ONLY the Localizable.strings file:

*Now it will be added to the Localizble.strings file and the actual string that will be shown to the user will be according to his OS language (As long as you have NSLocalizedString all over your app):

A: This is what I found works:

*

*click add localization;

*replace all the files in the new .lproj folder with localized files;

*delete the localization, and choose "keeping files";

*done.

A: The mailing list post basically sums up the issue: Xcode expects to find language bundles with names like "English.lproj", "Italian.lproj", etc. If you change those names, Xcode looses the ability to treat them as language bundles, and then you have to add files using the method you described. There's nothing wrong with how you're adding them to the project, that's just how Xcode works.


text:
Q: The "GenerateJavaStubs" task failed unexpectedly Estoy utilizando Xamarin.Forms con base de datos local sqlite-net-pcl, creé un proyecto multiplataforma para Android, IOs y otros dos DLL para crear las clases del motor y acceso. He estado ejecutando el proyecto sin problemas pero hoy me salió el siguiente error:

Severity  Code    Description Project File    Line    Suppression State
Error     The "GenerateJavaStubs" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load assembly 'System.ObjectModel, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'. Perhaps it doesn't exist in the Mono
for Android profile?
File name: 'System.ObjectModel.dll'
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference
 reference, ReaderParameters parameters)
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference
reference)
   at Mono.Cecil.MetadataResolver.Resolve(TypeReference type)
   at Mono.Cecil.TypeReference.Resolve()
   at Java.Interop.Tools.Cecil.TypeDefinitionRocks.<GetTypeAndBaseTypes>d__1.MoveNext()
   at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
   at Java.Interop.Tools.Cecil.TypeDefinitionRocks.IsSubclassOf(TypeDefinition
type, String typeName)
   at Java.Interop.Tools.JavaCallableWrappers.JavaTypeScanner.AddJavaTypes(List`1
javaTypes, TypeDefinition type)
   at Java.Interop.Tools.JavaCallableWrappers.JavaTypeScanner.GetJavaTypes(IEnumerable`1
assemblies, IAssemblyResolver resolver)
   at Xamarin.Android.Tasks.GenerateJavaStubs.Run(DirectoryAssemblyResolver
res)
   at Xamarin.Android.Tasks.GenerateJavaStubs.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()texto
destacado
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()   SQLiteProyecto.Android

y por más que estoy mirando por internet no doy con ello.
¿Le ha surgido este mismo error a alguien? ¿Lo pudisteis solucionar?
Un saludo,
Miguel


text:
Q: Google Play Compatibility Issue I have released an app on Google Play that has a minimum API level of 17 (Android 4.2).
I have a test phone running Android 4.4.2.
The app is currently released only as beta. When I attempt to download it, it says its not compatible.
Has anyone got any ideas what could cause this?
apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
useLibrary 'org.apache.http.legacy'

defaultConfig {
    applicationId "com.delaneybiometrics.delaneymobile"
    minSdkVersion 17
    targetSdkVersion 23
    versionCode 9
    versionName "0.9"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'org.apache.httpcomponents:httpcore:4.4.3'
compile 'org.apache.httpcomponents:httpclient:4.5'

}
Here is the Manifest...
<?xml version="1.0" encoding="utf-8"?>

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<!--<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>-->

<uses-feature
    android:name="android.hardware.camera"
    android:required="false" />
<uses-feature
    android:name="android.hardware.camera.front"
    android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

        </intent-filter>
    </activity>
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/.
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".PunchActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".OnSiteActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".RegisterActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".TourActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".SplashActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

A: To fix, remove the <uses-feature android:name="android.hardware.camera.autofocus" /> tag from your manifest.  But dont worry, as the docs say below, your app will still work properly
http://developer.android.com/reference/android/hardware/Camera.AutoFocusCallback.html

Devices that do not support auto-focus will receive a "fake" callback
  to this interface. If your application needs auto-focus and should not
  be installed on devices without auto-focus, you must declare that your
  app uses the android.hardware.camera.autofocus feature, in the
   manifest element.


text:
Q: I don't get Lua weak tables Okay so I want to implement a cache generator, which returns a handle to me, but doesn't give me the actual data.
local module = {}

cache = {}
setmetatable(cache, { __mode = "k" })

function getItem(item)
  local result = cache[item] or cacheItem(item)
  return item
end

function cacheItem(item)
  print("Caching item")
  cache[item] = true
  return cache[item]
end

function printCache()
  for key, value in pairs(cache) do
    print(key.name .. " and " .. value)
  end
end

module.printCache = printCache
module.getItem = getItem

return module

But when I try to use it:
local module = require("./cache")

a = {
  name = "Jimmie"
}

function foo()
  local b = {
    name = "Bobbie"
  }

  local h1 = module.getCachedItem(a)
  module.getCachedItem(b)
  local h3 = module.getCachedItem({ name = "Lenny" })

  module.printCache()
end

foo()
module.printCache()

The first time around, I expect all names to be printed.
The second time around, I only expect "Jimmie" to be printed.
However all names are printed twice. lua -v returns 5.2.4.


text:
Q: How can I display the result of the child component in the parent component? my application consists of a filter select by provinces, the filter is a modal that shows me the result in the filter component (child), I would like to show the result in the parent not in the filter modal. I do not know what to pass to the parent to show the result or how to show it on the screen.
///parent component
import React, { useState, useEffect } from 'react'
import { useDispatch } from "react-redux";
import { getClinic } from '../../api/drupalAPI'
import {Clinic} from '@icofcv/common';
import { selectClinics } from '../../actions/detailClinics'
import { useNavigate } from "react-router-dom";
import contentUtils from '../../lib/contentUtils'
import { SearchFilterClinics } from './SearchFilterClinics'
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';

    const ClinicList = () => {

    const [clinicList, setClinicList] = useState<Clinic[]>([]);
    const [clinicListFiltered, setClinicListFiltered] = useState<Clinic[]>([]);
    const [searchClinic, setSearchClinic] = useState("");
    const dispatch = useDispatch();
    const navigate = useNavigate();
    ///modal control

    const [isOpen, setIsOpen] = useState(false);
    const openModal = () => setIsOpen(true);
    const closeModal = () => setIsOpen(false);

    console.log(searchClinic);

    const fetchClinicList = async () => {
        getClinic().then((response)=>{
            console.log(response)
            setClinicList(response);
            setClinicListFiltered(response)
        }).catch ( (error)  => {
            console.error(error);
            throw error;
        });
    }

    const handleChange=e=>{
        setSearchClinic(e.target.value);
        filter(e.target.value);
      }

      const filter=(termSearch)=>{
        const resultSearch= clinicList.filter((element)=>{
          if(element.title.toString().toLowerCase().includes(termSearch.toLowerCase())
          ){
            return element;
          }
        });
        setClinicListFiltered(resultSearch);
      }

      function handleAddToDetail(clinic) {
        dispatch(selectClinics(clinic));
        navigate('clinicdetail');
      }

      function goToPageSearchFilterClinics() {
        navigate('filterclinics');
    }

    useEffect (() => {
        fetchClinicList();
    }, []);

    return(
            <>

                        {/* <button  onClick={() => goToPageSearchFilterClinics()}>filtro</button>  */}
                        <button  onClick={openModal}>filtro</button>

                    < SearchFilterClinics  isOpen={isOpen} closeModal={closeModal} clinicFilter={clinicFilter}></SearchFilterClinics>

                    <Form className="d-flex">
                        <Form.Control
                        type="search"
                        value={searchClinic}
                        placeholder="Search"
                        className="me-2"
                        aria-label="Search"
                        onChange={handleChange}
                        />
                    </Form>

                    {
                         clinicListFiltered.map((clinic) => (

                                <button
                                    type="button"
                                    onClick={() => handleAddToDetail(clinic)}
                                    style={{all: 'unset'}}
                                    >

                                        {/*  */}

{clinic.title}

{clinic.propsPhone}

{clinic.mobile}

{clinic.email}

{clinic.registry}

                                </button>

                        ))
                    }

            </>
    )
}

 export default ClinicList;

////child component

import React, { useState, useEffect } from 'react'
import Select, { SingleValue } from 'react-select'
import { getClinic } from '../../api/drupalAPI'
import {Clinic} from '@icofcv/common';
import "./Modal.css";

interface Props {
    isOpen: boolean,
    clinicFilter: String,
    closeModal: () => void
}

export const SearchFilterClinics : React.FC<Props> = ({ children, isOpen, closeModal, clinicFilter }) => {

         ////filter

         type OptionType = {
            value: string;
            label: string;
          };

            const provincesList: OptionType[] = [
                { value: 'Todos', label: 'Todos' },
                { value: 'Valencia', label: 'Valencia' },
                { value: 'Castellon', label: 'Castellon' },
                { value: 'Alicante', label: 'Alicante' },

            ]

    const [clinicList, setClinicList] = useState<Clinic[]>([]);
    const [clinicListFilteredSelect, setClinicListFilteredSelect] = useState<Clinic[]>([]);
    const [filterSelectClinic, setFilterSelectClinic] = useState<SingleValue<OptionType>>(provincesList[0]);

    const handleChangeSelect = async (provinceList: SingleValue<OptionType>) => {
        getClinic().then((response) => {
            setClinicList(response);
            setClinicListFilteredSelect(response)
            setFilterSelectClinic(provinceList);
            filterSelect(provinceList );
          }).catch ((error) => {
            console.error(error);
            throw error;
        });
      }

      const filterSelect=(termSearch)=>{
        const resultFilterSelect = clinicList.filter((element) => {
          if(element.province?.toString().toLowerCase().includes(termSearch.value.toLowerCase() )

          ){
            return element;
          }
        });
        setClinicListFilteredSelect(resultFilterSelect);
      }

      const handleModalContainerClick = (e) => e.stopPropagation();

    return  (
                <>
                     <div className={`modal ${isOpen && "is-open"}`} onClick={closeModal}>

                            <button className="modal-close" onClick={closeModal}>x</button>
                            {children}

Encuentra tu clínica

                                    <form>

                                        Provincia
                                            <Select
                                                defaultValue={filterSelectClinic}
                                                options={provincesList}
                                                onChange={handleChangeSelect}
                                                />

                                       </form>

                                {

                                    clinicListFilteredSelect.map((clinicFilter) => (

{clinicFilter.title}

{clinicFilter.propsPhone}

{clinicFilter.mobile}

{clinicFilter.email}

{clinicFilter.province}

{clinicFilter.registry}

                                    ))
                                }

                </>
            )
}

A: You need to pass a callback function to the parent and set the state value in the parent, not in the child. (This is known as lifting state up.)
In your case this would involve moving
const [filterSelectClinic, setFilterSelectClinic] = useState<SingleValue<OptionType>>(provincesList[0]);

Into the parent component. Then passing the setFilterSelectClinic function into the child component.
<SearchFilterClinics setFilterSelectClinic={(value) => setFilterSelectClinic(value)} isOpen={isOpen} closeModal={closeModal} clinicFilter={clinicFilter}/>

The value (within the parenthesis) is being passed up by the child component. This is the value you set here:
getClinic().then((response) => {
 ...
 // this is the function we pass in from the parent. It set's the value
 // of the callback function to provinceList
    setFilterSelectClinic(provinceList);
 ...

We then setFilterSelectClinic to that value. Meaning filterSelectClinic now has the value passed up in the callback.


text:
Q: Lazy loading Objective-C class with int properties I use the following as a getter for a property in one of my classes:
- (NSString *)version
{
    if (_version == nil) {
        _version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    }
    return _version;
}

This works well.  However, when I try the same for an int property I obviously get an error since int are never nil.  What is the best way around this?
- (int)numberOfDays
{
    if (_numberOfDays == nil) {
        // relatively memory intense calculation that works out numberOfDays:
        _numberOfDays = X;
    }
    return _numberOfDays;
}

A: Firstly, using int is not recommended Objective-C if possible. If you need to use a primitive integer type, you should use NSInteger. The size of NSInteger is determined at compile time based on the architecture(s) being built for. int is a static size that will not widen for different architectures. It's OK to use it, just be aware.
Using NSInteger, you still face the same problem, it can't be nil. You should therefore make your property an NSNumber which you can init with the result of your computation with [NSNumber numberWithInteger:anInteger];. That way, you can keep you nil check on your property and only do the computation once to create your NSNumber.

A:
Use GCD.
static dispatch_once_t tok;
dispatch_once(&tok, ^{ memory_intensive_computation(); });

No, don't use GCD, I missed the point. In an instance method, you want to tie information to each instance, so using a static dispatch token is not appropriate. Maybe you should just stick with the "boolean flag as instance variable" approach.
Alternatively, you can initialize the int to a value which is known to be out of its valid range (for example, I suppose that numberOfDays can never be negative) and use that as a condition for performing the calculation.

A: Use a NSNumber to store the int value.
- (int)numberOfDays
{
    if (_numberOfDays == nil) {
        // relatively memory intense calculation that works out numberOfDays:
        _numberOfDays = @(X);
    }
    return [_numberOfDays intValue];
}

A: Add another boolean instance variable _numberOfDaysCalculated.
A thread-safe version would be
- (int)numberOfDays
{
    @synchronized(self) {
        if (!_numberOfDaysCalculated) {
            // relatively memory intense calculation that works out numberOfDays:
            _numberOfDays = X;
            _numberOfDaysCalculated = YES;
        }
    }
    return _numberOfDays;
}

Alternatively, if there is some "invalid" value of the property, you can use that
as a "not yet computed" marker. For example, if the computed value of numberOfDays has to be non-negative, you could initialize _numberOfDays = -1 in the init method,
and then test for if (_numberOfDays == -1) in the lazy getter method.

A: I would initialize the _numberOfDays in the -init with NSNotFound and test for that in the getter.


text:
Q: Import Typescript file in Javascript I'm making a Chrome extension and I'm trying to import a Typescript file in Javascript.
Both files are next to each others.
I'm importing it this way:
import { ApiParsing } from './ApiParsing.ts';

When I'm using the extension I have the following error:
Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

A: TypeScript cannot be executed from a browser / node.js environment directly. At first you have to transpile it into native javascript. To do this you will need to execute tsc.
https://www.typescriptlang.org/docs/handbook/compiler-options.html
https://www.typescriptlang.org/docs/tutorial.html
Typescript is a so called "Superset" of JavaScript which means that all typescript code will be transpiled into usual JS code from the typescript compiler. Often those compile processes are linked with a bundler like webpack.
https://webpack.js.org/concepts/
Knowing this your error The server responded with a non-JavaScript MIME type makes a lot of sense due to a typescript file is a "non-JavaScript MIME type".
Note:
You can't import typescript files into javascript files, but you can do it vice versa.

A: You can do that through babel. Follow below article
Article: How to use typescript file in javascript project


text:
Q: Encoding issue while annotating a sentence in Spanish with cleanNLP and stanford-corenlp backend I'm trying to annotate a sentence in Spanish with cleanNLP and stanford-corenlp backend. When I inspect the output tokens I notice that all non-ascii characters were removed and the words with these characters were splited.
Here is a repoducible example:
> library(cleanNLP)
>
> cnlp_init_corenlp(
+   language = "es",
+   lib_location = "C:/path/to/stanford-corenlp-full-2018-10-05")
Loading required namespace: rJava
>
> input <- "Esta mañana desperté feliz."
>
> Encoding(input)
[1] "latin1"
>
> input <- iconv(input, "latin1", "UTF-8")
>
> Encoding(input)
[1] "UTF-8"
>
> myannotation <- cleanNLP::cnlp_annotate(input)
>
> myannotation$token$word
[1] "ROOT"    "Esta"    "ma"      "ana"     "despert" "feliz"   "."

Session info:
> sessionInfo()
R version 3.6.0 (2019-04-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17134)

Matrix products: default

locale:
[1] LC_COLLATE=Spanish_Argentina.1252  LC_CTYPE=Spanish_Argentina.1252
[3] LC_MONETARY=Spanish_Argentina.1252 LC_NUMERIC=C
[5] LC_TIME=Spanish_Argentina.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] cleanNLP_2.3.0

loaded via a namespace (and not attached):
[1] compiler_3.6.0    tools_3.6.0       textreadr_0.9.0   data.table_1.12.2
[5] knitr_1.22        xfun_0.6          rJava_0.9-11      XML_3.98-1.19
>

A: In this GitHub issue the package creator gave me the answer. The problem was my machine's default encoding. I just had to add options(encoding = "UTF-8") before annotating the string.


text:
Q: Issue in passing a data id to bootstrap modal I have a listing page containing a link button to show modal repeating in a PHP loop. I have searched and found these:
Passing data to a bootstrap modal, Passing data to Bootstrap 3 Modal and Pass id to Bootstrap modal and some others but failed.
What I want
I have fetched the data  id from database and pass it to bootstrap modal and there I will use this id to display more info through MySQL queries.
I have written all the code but the ID is not passing to the modal.
Modal Link Button code
 <a class="btn btn-warning btn-minier" href="#modal-form-show" role="button" data-toggle="modal" data-target="#myModal" data-id="<?php echo $cottage_id ?>"> Reservation

Modal code

            <button type="button" class="close" data-dismiss="modal">×</button>

Reservation Details

Cottage Id :

Cottage Title :

ID WILL SHOW IN THIS TEXT FIELD.
           <input type="text" name="cottage" placeholder="cottage id" value="" id="cottage" />

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

JS code
$('#modal-form-show').on('show.bs.modal', function(e) {
  var c_id= $('a[href="#modal-form-show"]').data('id');
  //var c_id= $(this).data(id) - checked both
  $("#cottage").val(c_id);
});

I have taken a text input in modal named cottage and I want show that id in this input.

A: Try this snippet:
$('.btn-minier').click(function(){
  var c_id = $(this).attr('data-id');
  $('#cottage').val(c_id);
});

A: I have change little , when button click show the popup & i've set the value of data-id=2
Button
 Reservation

I add button in you modal

                    <button type="button" class="close" data-dismiss="modal">×</button>

Reservation Details

Cottage Id :

Cottage Title :

                        ID WILL SHOW IN THIS TEXT FIELD.
                        <input type="text" name="cottage" placeholder="cottage id" value="" id="cottage" readonly />

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-success" data-dismiss="modal" id="btnSubmit">Submit</button>

Javascript code

A: Try using attr method of JQuery
$('#modal-form-show').on('show.bs.modal', function(e) {
    // instead of this
    //var c_id= $('a[href="#modal-form-show"]').data('id');
    // try this one
    var c_id= $('a[href="#modal-form-show"]').attr('data-id');
    //var c_id= $(this).data(id) - checked both
    $("#cottage").val(c_id);
});


text:
Q: ASP and ' does not work I am not an ASP expert, just trying to help a friend.
It the past, HTML,I use ' for apostrophes in text.
Using the following it renders fine in Firefox but incorrect in IE 7.
asp:LinkButton ID="AceFrehley95Button" Text="Ace Frehley ' 95" OnCommand="lbtnSubMenu_Command" CommandArgument="AceFrehley95.wmv" Runat="Server"

In Firefox it renders: Ace Frehley '95
In IE 7 it renders: Ace Frehley &apos 95
How do I make IE render what Firefox does......
Jason

A: You could also try:
'

Which renders as:
'

A: HTML doesn't actually have a ' entity. A lot of browsers support it (probably because it is a part of XHTML), but "officially" it doesn't exist. You should use ' instead.

A: Unless you are a typography purist,
   ´

may be close enough.


text:
Q: What's the reason both Image and Bitmap classes don't implement a custom equality/hashcode logic? From MSDN documentation, it seems as both GetHashCode() and Equals() haven't been overriden in Bitmap. Neither have them been overriden in Image. So both classes are using the Object's version of them just compares references. I wasn't too convinced so I decided to fire up Reflector to check it out. It seems MSDN is correct in that matter.
So, is there any special reason why MS guys wouldn't implement "comparison logic", at least for the Bitmap class? I find it is kinda acceptable for Image, as it is an abstract class, but not so much for the Bitmap class. I can see in a lot of situations calculating the hash code can be an expensive operation, but it'd be alright if it used some kind of caching.
When wanting to compare 2 bitmaps, will I have to resort to having to run all over the picture comparing each one of its pixels?
Thanks

A: Let's flip that question around; is there any special reason why they would implement such a thing?
For one thing, it would be very, very expensive to compute the hash, making it all but useless for hash tables and the like.  Just try to imagine doing this on a whole slew of 1920x1200 bitmaps; doing it even one time for each bitmap would slow the program to a crawl.  I would expect that 9 times out of 10, when somebody has to compare two bitmaps, they want reference equality, not pixel-by-pixel value equality.
And what you refer to in your question isn't lazy evaluation, it's caching.  Caching is a non-trivial feature to implement, and every feature starts at minus 100 points.
With all that in mind, my answer to this would be that the methods aren't overridden because the overridden versions wouldn't be particularly useful to many people, relative to the cost of implementing and maintaining such a feature.  If you really want pixel-by-pixel comparisons (or checksums, or similar things), then you can always implement them yourself in 10 lines or so.

A: Equality semantics in the .net framework are pretty well standardized; it would seem to violate the principal of least surprise if references to bitmaps tested for equality in the way you expected.

A: When the built-in bitmap comparison that MS did not implement is run, it would need to resort to comparing each of the pixels.  Sure, MS would probably do a raw memory comparison (perhaps in an unsafe block), but you can do the same thing if you want.  Regardless, comparing two bitmaps will always be expensive.  And you cannot rely on hashes both because calculating a hash is generally going to be as expensive as a comparison...and you'll be forced to rely on a raw pixel comparison to verify equality when the hashes match, since hashes only prove inequality.
I have not provided a demonstration that Equals and GetHashCode are useless in a Bitmap.  However, I have provided a demonstration that they are often going to offer surprising, unexpected costs to users and will not be a good solution in ordinary use cases.  Adding extra functionality to a type like this is expensive, and I'm not convinced it would have much benefit.  And it would often cost a lot.  This is the kind of thing you should implement yourself, or use a 3rd party library.

A: Images and bitmaps are generally mutable reference types.  Mutable reference types should never override Equals(Object), since Equals(Object) is not supposed to report whether two objects happen to have the same state at the time it's called, but rather whether two objects will always and forevermore be equivalent.  Even if two mutable objects happen to have the same state at one moment in time, that would in no way imply that they will always do so.


text:
Q: why seatle.html is missing on subsites I am confused on how i should be editing master pages on site collection & sub sites.now i have a team site collection inside sharepoint 2013, and when i check its master pages inside SP designer i found the following, where seatle.html is missing:-

so i enable the "SharePoint Server Publishing Infrastructure" site collection feature and then i refresh the mater pages list where the seatle.html appear :-

now inside the team site i created a  new subsite of type team site, then i opened the new sub-site inside SP designer . But  i could not find seatle.html. and now i need to modify the master page for the sub site, so i did the following:-

*

*i copy/paste the seatle.master.

*then i define the new master page as the default and custom master page.

*then i edit the new master page and i did the modification

now my team sub site had the modification without any problem.
but i have the following questions on the above:-

*

*why the site collection will not have seatle.html unless i activate the site collection feature?

*for the sub-site , seems there is not any way to have a seatle.html for it , so is my process of copying the seatle.master and do the modification inside the new seatle.master copy a correct approach.

*now inside the team site collection which have the "SharePoint Server Publishing Infrastructure" feature enabled, i copy/paste the seatle.master but when edit the copy and try to save it i got the following error :-

server error: this file may not be moved,delete,renamed or otherwise
  edited

so why i was able to edit the seatle.master copy inside the subsite, while i could not do the same inside the site collection ?

A: The Html file is being used by Design Manager, and created as when you activate Publishing Infrastructure Feature. Html file doesn't come with team sites template.
Update after your comment:
It is something that you should decide at top level site of a new Site Collection, whether or not the publishing feature will be needed within that Site Collection because this can greatly impact the decision on which site template is the best choice for the top level site. If top site has publishing feature activated, so the subsites will inherit publishing, or else subsites based on team site template will eventually be converted to publishing with no real connection of publishing site collection as a parent. Also, master pages provisioning (.master/.html ) is decided at top site level, which largely decided if the site collection is publishing/team.


text:
Q: How to detect crosses and circles in 60x60 raster images? I have hand-written 60 pixel times 60 pixel squares. I need to detect whether they are empty, x or circle. TextRecognize function fails. Is there some other function to process this kind of raster images with text?

Harder example

Circles: (0,0..9), (0..5,0), (0..5,9), (5,0..9)
Crosses: (2,3..6), (4,4..5)
Empty: (1,1..8), (2,1..2), (3,1..8), (4,1..3), (4,6..8)

I try to summarize and help people to solve the harder puzzle. Work in progress. Have fun!

I. Preprocessing (example)

1.1. thread
    about getting grid from raster image
1.2. convexity
    fix
1.3. rotation

II. Testing

2.1. Further info about mathematical morphology and
    Mathematica's
    intro.

A: For robustness I think it would be best to apply multiple tests and check the results for agreement.  Here is one simple test you could include in that suite:
f = MorphologicalEulerNumber[Blur @ #, 0.8] &;

The function should return 0 for X's and 1 for O's.  Quoting the documentation:

MorphologicalEulerNumber[image] by default gives the total number of connected white regions in image, minus the number of black holes that occur inside those regions.

You can tune the parameter 0.8 according to the density of your images and the noise level.
You may also try other pre-filters besides Blur, such as MedianFilter.
Example:
imgs = Import /@
  {"http://i.stack.imgur.com/gDzKy.png",
   "http://i.stack.imgur.com/LMPQq.png"}

f /@ imgs

{0, 1}

The whole enchilada
f2 =
 Switch[
    {
      MorphologicalEulerNumber @ #,
      500 < Total[1 - ImageData[#], 2]
    } & @ Binarize[# ~Blur~ 4, 0.8],
    {1, True}, "O",
    {0, True}, "X",
    {_, False}, "",
    _, "Err"
 ] &;

img = Import["http://i.stack.imgur.com/NbTGY.jpg"];
grid = ImagePartition[
   ImageCrop[ImageRotate[img, 0.7 \[Degree]], {1180, 720}, {-0.15, 0.2}], {118, 119}];

Map[
 ImageCompose[#, Rasterize[Style[f2@#, Red], Background -> None]] &,
 grid, {2}
] // GraphicsGrid

A: As I said in the comment, ComponentMeasurements is a easy and robust way to differentiate simple shapes.
Using your image and binarizing it:
img = ColorConvert[Import["http://i.stack.imgur.com/NbTGY.jpg"],
  "Grayscale"];
bin = ColorNegate@Binarize[ImageAdjust[GaussianFilter[img, 5]]]

ComponentMeasurements calculates a list of measurements for each connected component.
components =
  ComponentMeasurements[
   bin, {"Centroid", "Area", "FilledCircularity",
    "EquivalentDiskRadius"}, #2 > 100 &];

In this case, it calculates the centroid, area and the filled area/perimeter ratio compared to a circle. That's a very good measure to recognize circles. The EquivalentDiskRadius is just there for the display:
Show[img,
 Graphics[
  {
   Thick,
   {If[#[[3]] > 0.5, Red, Blue], Circle[#[[1]], #[[4]]]} & /@
    components[[All, 2]]
   }]]

Objects with FilledCircularity < 0.5 are displayed as blue circles, FilledCircularity > 0.5 red:

A: This trick sometimes works:
i1 = Import["http://i.stack.imgur.com/gDzKy.png"];
i2 = Import["http://i.stack.imgur.com/LMPQq.png"];
TextRecognize@ImageAssemble[{i1, i2, i1, i2, i1, i2}]
(*
--> "XOXOXO"
*)

Use it by appending the unknown square to a bunch of known ones, and detecting the last character.


text:
Q: Can I make WordPress theme from html template designed by 3rd party? I am not a designer that's why I need to buy others template and then convert them to WordPress to sell in marketplace. I saw some awesome html templates I really love them and I didn't find these templates for WordPress. That's why I am willing to buy these html templates and convert them to WordPress theme.
Is it acceptable by themeforest and other marketplace?

A: Yes you can convert static HTML themes to Wordpress, but you would need some knowledge of Wordpress development to do so. It would entail replacing the content with the dynamic functions that Wordpress provides.
Buying themes from places like Themeforest is perfectly acceptable, and a great deal of small businesses and blogs do this. Just make sure the theme will do what you need it to. Also, worth checking their return policy - many premium themes and plugins have a 30-day money-back guarantee which will allow you to make sure the theme is right for you or you can get your money back, no questions asked.


text:
Q: ¿Como deshabilitar una fila en un datagridview al presionar un botón y que quede deshabilitada al cargar el formulario? tengo el siguiente código para "deshabilitar" la fila seleccionada en un DataGridView
     private void btnEliminar_Click(object sender, EventArgs e)
     {
            if(dgvProveedor.SelectedRows.Count > 0)
            {
                int filaElimar = dgvProveedor.CurrentRow.Index;
                dgvProveedor.CurrentCell = null;
                dgvProveedor.Rows[filaElimar].ReadOnly = false;
                dgvProveedor.Rows[filaElimar].DefaultCellStyle.ForeColor = Color.Gray;
            }
    }

La fila primero se selecciona la fila que se va a deshabilitar y al presionar el botón se deshabilita y le agregue un color para dar sentido de que esta deshabilitada. Pero cuando cierro la aplicación y la vuelvo a iniciar, la fila que "Elimine" vuelve a estar "Habilitada", como hago para que se quede deshabilitada al cerrar e iniciar la aplicación? Utilizo C# en visual studio 2017


text:
Q: Skip Build failure in maven if the integration test fails I want to skip the build failure even if the integration test fails. I am using maven-failsafe for Integration test. I am currently getting the following:
Failed to execute goal org.apache.maven.plugins:maven-failsafe-plugin:2.15:verify (default) on project xxxxx: There are test failures.

Question: Can I use the following for Maven Failsafe Plugin? I know it works for the Surefire plugin, but not sure for failsafe.
-Dmaven.test.failure.ignore=true

A: Yes, the same parameter is valid for the maven-failsafe-plugin. From the documentation of the verify goal, you can set the testFailureIgnore to true:

Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion.

*

*Type: boolean

*Required: No

*User Property: maven.test.failure.ignore

*Default: false

The corresponding user property is maven.test.failure.ignore, which means that setting that property on the command line will ignore tests failure.

A: The Maven Failsafe Plugin documentation for the verify goal also provides this option:

Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion.

The configuration entry is testFailureIgnore while the user property is indeed maven.test.failure.ignore.
So, running:
mvn clean install -Dmaven.test.failure.ignore=true

Would indeed ignore test failures as you guessed.


text:
Q: Value cannot be null Parameter Name: destinationTimeZone I have a function that basically sends automated email to my company email address, it has 6 parameters that I need to make it work, the issue is every time I call it to make it run it always throw this exception 'System.ArgumentNullException' in mscorlib.dll. I also made it show the exception in a console to get more details (see image below). What I want to know is what is triggering the exception and how do I fix it. (see code below)

Send Email Function
public static void SendEmail(Microsoft.Office.Interop.Outlook.Application Application, List<string> screenshotLocations, bool bi6Accessible, bool bi7Accessible, bool bi8Accessible, bool detailedReportingAccessible)
        {
            string recipients = ConfigurationManager.AppSettings["ToEmail"];
            StringBuilder mailBodyText = new StringBuilder();
            TimeZoneInfo India_Standard_Time = null;
            DateTime dateTime_Indian = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, India_Standard_Time);
            TimeZoneInfo Phillipines_Standard_Time = null;
            DateTime dateTime_PH = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, Phillipines_Standard_Time);
            Microsoft.Office.Interop.Outlook.MailItem mail = null;
            Microsoft.Office.Interop.Outlook.Recipients mailRecipients = null;
            Microsoft.Office.Interop.Outlook.Recipient mailRecipient = null;
            var logFile = @"C:\Users\kent.harvey.p.abrio\Documents\Visual Studio 2015\Projects\SConsoleApplication1\SConsoleApplication1\SanityCheckApplication\ScreenShots\loggers.txt";

            try
            {
                mail = Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem)
                    as Microsoft.Office.Interop.Outlook.MailItem;

                mail.Subject = string.Format("Hourly Sanity Check Automated Mail - {0} IST / {1} PHT", dateTime_Indian.ToString("yyyy-MM-dd HH:mm"), dateTime_PH.ToString("yyyy-MM-dd HH:mm"));
                //Attach Logs

                mail.Attachments.Add(logFile);
                //Attach Screenshots
                foreach (string item in screenshotLocations)
                {
                    //add the screenshot name
                    mail.Attachments.Add(item);
                }
                //Create Mail Body
                if (bi6Accessible)
                    mailBodyText.AppendLine("Tableau Accessibility : Bi6 reports are visible. Please refer to attached screenshot.\n");
                else
                    mailBodyText.AppendLine("Tableau Accessibility : Bi6 reports are not visible in IMP. Please take appropriate actions.\n");
                if (bi7Accessible)
                    mailBodyText.AppendLine("Qlik Accessibility : Bi7 reports are visible. Please refer to attached screenshot.\n");
                else
                    mailBodyText.AppendLine("Qlik Accessibility : Bi7 reports are not visible in IMP. Please take appropriate actions.\n");
                if (bi8Accessible)
                    mailBodyText.AppendLine("Qlik-Sense Accessibility : Bi8 reports are visible. Please refer to attached screenshot.\n");
                else
                    mailBodyText.AppendLine("Qlik-Sense Accessibility : Bi8 reports are not visible in IMP. Please take appropriate actions.\n");
                if (detailedReportingAccessible)
                    mailBodyText.AppendLine("Detailed reporting Accessibility : Offline reports list are visible. Please refer to attached screenshot.\n");
                else
                    mailBodyText.AppendLine("Detailed reporting Accessibility : Offline reports list are not visible in IMP. Please take appropriate actions.\n");

                mail.Body = Convert.ToString(mailBodyText);
                //Add and Resolve Recipient List
                mailRecipients = mail.Recipients;
                mailRecipient = mailRecipients.Add(recipients);
                mailRecipient.Resolve();

                if (mailRecipient.Resolved)
                {
                    mail.Send();
                    string firstLog = ("Email send to : " + recipients);
                    File.WriteAllText(logFile, firstLog);
                }
                else
                {

                    string secondLog = ("There is no such record in your address book.");
                    File.WriteAllText(logFile, secondLog);
                }
            }
            catch (System.Exception ex)
            {
                //Logger("An exception is occured in the code of add-in.");
                //Logger(ex.Message);
                //Logger("Stack Trace :" + ex.StackTrace);
                string thirdLog = ("An exception is occured in the code of add-in." + ex.StackTrace);
                File.WriteAllText(logFile, thirdLog);
            }
            finally
            {
                if (mailRecipient != null) Marshal.ReleaseComObject(mailRecipient);
                if (mailRecipients != null) Marshal.ReleaseComObject(mailRecipients);
                if (mail != null) Marshal.ReleaseComObject(mail);
            }
        }

This is how I called it.
 try
 {
     SendEmail(Application, screenshotLocations, bi6Accessible, bi7Accessible, bi8Accessible, detailedReportingAccessible);

  }
  catch (System.Exception e)
  {
     Console.WriteLine(e.Message);
     ieDriver.Quit();
  }

A: Change the lines
            TimeZoneInfo India_Standard_Time = null;
            DateTime dateTime_Indian = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, India_Standard_Time);
            TimeZoneInfo Phillipines_Standard_Time = null;
            DateTime dateTime_PH = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, Phillipines_Standard_Time);

to
            TimeZoneInfo India_Standard_Time = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
            DateTime dateTime_Indian = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, India_Standard_Time);
            TimeZoneInfo Phillipines_Standard_Time = TimeZoneInfo.FindSystemTimeZoneById("Taipei Standard Time");
            DateTime dateTime_PH = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, Phillipines_Standard_Time);

The reason to use Taipei for Philippines is in http://www.pinoy-web-application.com/blogs/c-how-to-get-time-zone-date-and-time-in-the-philippines/


text:
Q: Task Scheduler wait until first logon of the day but thereafter guarantee only run at 1 hour intervals I am trying to create a task in task scheduler to run every hour and pop up a dialogue that lets the user pick from a list what activity they are currently working on. These tasks need to be spaced evenly throughout the day to sample how frequently each task is being worked on - this will determine what % of the user's time is dedicated to each task.
I am trying to run

*

*On a daily schedule

*Starting at 8AM (or logon - whichever is later)

*With random delay to the start time

*Every hour

The issue is, if I set the task to "retry if scheduled start is missed" then my samples are not 1 hour apart which messes up my statistical analysis
I can't work out how to get the task to start a random amount of time < 1hr after startup and thereafter at exact 1 hour intervals. If the task is missed it must not run again, I want to log "Unknown" and resume the next hour.

My current settings:

A: In Task Manager, opposite click the task and choose "properties". On the "General" tab, do you have "run whether user is logged on or not" checked?
If, it's not checked, it will only run the task if the designated user is logged on.


text:
Q: Ansible win_xml removing xml element fails I am running the following task in an ansible playbook after installing iis trying to remove the default website document files from applicationhost.config.
  - name: Remove defaultDocument Files From applicationhost.config
    win_xml:
      path: C:\Windows\System32\inetsrv\Config\applicationHost.config
      xpath: /configuration/system.webServer/defaultDocument/files/*
      state: absent

The play fails with the following error:
The full traceback is:
The property 'removed' cannot be found on this object. Verify that the property exists.
At line:162 char:21
+ ...             $result.removed += $result.removed + $removedNode.get_Out ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : PropertyNotFoundStrict

ScriptStackTrace:
at <ScriptBlock>, <No file>: line 162

fatal: [win2019-local-096]: FAILED! => {
    "changed": false,
    "msg": "Unhandled exception while executing module: The property 'removed' cannot be found on this object. Verify that the property exists."
}

A: Turns out this was an issue because I was running my playbook with debug -vvvv so that I could debug the output. As soon as I ran that without the verbosity it succeeded.


text:
Q: Authentication failed for uid=wpadmin I got below exception when I tried to login into websphere console

SECJ0055E: Authentication failed for
  uid=wpadmin,cn=users,dc=te-data,dc=core. The user id or password might
  have been entered incorrectly or misspelled.  The user id might not
  exist, the account could have expired or disabled.  The password might
  have expired. [6/5/18 6:00:00:613 EET] 0000003a J2EEContext   E
  ASYN9999E: Unexpected Exception Occurred:
  com.ibm.websphere.asynchbeans.SerialDeserialException: Exception while
  deserializing a saved service.  Service=security. Unable to
  deserialize the Subjects in this Context, cause: The user is from a
  foreign realm, defaultWIMFileBasedRealm, and this foreign realm is not
  trusted. Current realm is ssptds.te-data.core:389

A: The error is a big hint

The user is from a foreign realm, defaultWIMFileBasedRealm, and this foreign realm is not trusted.

I found the answer in the IBM docs:

Go to the Websphere Application Server administration console and
  under Security > Global security > Federated repositories make sure
  that both the realms mentioned in the error are listed as trusted.

This is either a configuration error, or you are not supposed to login the way you are. If you have access to the administration console, the fix is just to add defaultWIMFileBasedRealm to the trusted realms. Otherwise you may need to log on some other way.


text:
Q: decltype of member function pointer as template argument in c++11 I am trying to write a wrapper function which links to a function pointer at compile time, thus I wrote the following code which works perfectly fine in C++11:
#include <iostream>

template<typename Fn, Fn func, typename... Args>
typename std::result_of<Fn(Args...)>::type callfunc(Args&&... args){
  //do something else here
  return (*func)(args...);
}

double add(double a, double b){
  return a+b;
}

int main(){
  std::cout << callfunc<decltype(&add), &add>(2.0, 3.0) << "\n";
}

However if I try to do the same thing with a member function like this
#include <iostream>

template<typename Fn, Fn func, typename... Args>
typename std::result_of<Fn(Args...)>::type callfunc(Args&&... args){
  //do something else here
  return (*func)(args...);
}
class testclass {
public:
  double testadd(double a, double b);
  void run();
};

double testclass::testadd(double a, double b){
  return a+b;
}

void testclass::run(){
  std::cout <<
  callfunc<decltype(&testclass::testadd), &testclass::testadd>(2.0, 3.0)
  // ^^^^^ this won't compile! ^^^^
  << "\n";
}

int main(){
  testclass obj;
  obj.run()
}

I get the following compiler error:
error: indirection requires pointer operand ('double (testclass::*)(double,double)' invalid) return (*func)(args...);

What am I doing wrong?

A: To invoke a non-static member function you need a valid instance pointer. Here is a modified version of your code that works:
#include <iostream>

template<typename Fn, Fn func, typename Class, typename... Args>
typename std::result_of<Fn(Args...)>::type callfunc(Class* instance, Args&&... args){
    return (instance->*func)(args...);
}
class testclass {
public:
    double testadd(double a, double b);
    void run();
};

double testclass::testadd(double a, double b){
    return a + b;
}

void testclass::run(){
    std::cout <<
        callfunc<decltype(&testclass::testadd), &testclass::testadd>(this, 2.0, 3.0)
        << "\n";
}

int main(){
    testclass obj;
    obj.run();
}


text:
Q: What is an index and type(index type) in Elastic Search? In the context of elastic search, am I right understanding that:
-> An index is equivalent to a database
-> An index_type is equivalent to a NoSQL collection or a SQL table

A: Yes you understand it right.
Index is something like database.
type is more like sql table than like NOSql collection. Because in NoSql you can mix fields types while in Elasticsearch you must keep field within same type.
In Es there is also some recommendation how you should store types inside of index
From document
Good: kitchen and lawn-care types inside the products index, because the two types are essentially the same schema.
Bad: products and logs types inside the data index, because the two types are mutually exclusive. Separate these into their own indices.


text:
Q: htaccess - Redirecting php files I am writing my .htaccess file for my website. It contains 30+ php files that have act as front-end for the courses.
I have tried the code below but whenever you access my website: www.conuplugs.com, it redirects to COMP248 for some reason
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ class/comp232.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/comp248.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/engr201.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/engr213.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/comp249.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen228.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen287.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/engr233.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/comp348.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/comp352.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/encs282.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/engr202.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/comp346.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen331.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen341.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/engr371.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/elec275.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/comp335.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen342.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen343.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen344.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen345.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen384.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/engr391.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen357.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen390.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/engr301.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen321.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen490.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/engr392.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/soen385.php?path=$1 [NC,L,QSA]
RewriteRule ^(.*)$ class/comp354.php?path=$1 [NC,L,QSA]

As mentioned earlier, this redirects to COMP248.php, how can I fix this?