text:
Q: How can I remap the multimedia keys for function keys on this bluetooth keyboard? I got a Logitech Bluetooth Multi-Device Keyboard K480 and after installing it just by following the bluetooth pairing, the default settings will leave the function keys mapped as multimedia keys, so I have to hold fn to access F1,F2,F3, etc.
That is very counter-intuitive for me, and I'd like to remap it so I can access Functions directly and access the multimedia keys with fn

This is F1 without holding fn and then holding it.
KeyPress event, serial 37, synthetic NO, window 0x4e00001,
root 0xd6, subw 0x0, time 63445847, (-438,408), root:(284,460),
state 0x10, keycode 180 (keysym 0x1008ff18, XF86HomePage), same_screen YES,
XLookupString gives 0 bytes:
XmbLookupString gives 0 bytes:
XFilterEvent returns: False

KeyRelease event, serial 37, synthetic NO, window 0x4e00001,
root 0xd6, subw 0x0, time 63445922, (-438,408), root:(284,460),
state 0x10, keycode 180 (keysym 0x1008ff18, XF86HomePage), same_screen YES,
XLookupString gives 0 bytes:
XFilterEvent returns: False

KeyPress event, serial 37, synthetic NO, window 0x4e00001,
root 0xd6, subw 0x0, time 63446510, (-438,408), root:(284,460),
state 0x10, keycode 67 (keysym 0xffbe, F1), same_screen YES,
XLookupString gives 0 bytes:
XmbLookupString gives 0 bytes:
XFilterEvent returns: False

KeyRelease event, serial 37, synthetic NO, window 0x4e00001,
root 0xd6, subw 0x0, time 63446597, (-438,408), root:(284,460),
state 0x10, keycode 67 (keysym 0xffbe, F1), same_screen YES,
XLookupString gives 0 bytes:
XFilterEvent returns: False

A: It seems that logitech provides a special driver on various OS's other than Linux that does exactly this swap by sending an undocumented magic command to the keyboard.
Some people have monitored the communication to find the codes sent to some other similar logitech keyboards such as the
760
and the
810. You might try one of those.
Failing that, you can use xmodmap to swap the key assignments. We see that your keyboard sends 2 different keycodes depending on whether Fn is pressed or not. Use xmodmap -pke to list all the key mappings in a file, then keep just the ones referring to the wanted keycodes. For example you would have
keycode  67 = F1 F1 F1 F1 F1 F1 XF86Switch_VT_1
keycode 180 = XF86HomePage NoSymbol XF86HomePage

and so on. Simply invert the numbers:
keycode 180 = F1 F1 F1 F1 F1 F1 XF86Switch_VT_1
keycode  67 = XF86HomePage NoSymbol XF86HomePage

Then pass this filename as argument to xmodmap to have it update the mapping.

A: You can put this code into a script named: "/home/youruser/k480" and run it. Will remap your logitech keys.
xmodmap -e "keycode 180 = F1 F1 F1 F1 F1 F1"
xmodmap -e "keycode  23 = F2 F2 F2 F2 F2 F2"
xmodmap -e "keycode 135 = F3 F3 F3 F3 F3 F3"
xmodmap -e "keycode 166 = F4 F4 F4 F4 F4 F4"
xmodmap -e "keycode 225 = F5 F5 F5 F5 F5 F5"
xmodmap -e "keycode 173 = F6 F6 F6 F6 F6 F6"
xmodmap -e "keycode 172 = F7 F7 F7 F7 F7 F7"
xmodmap -e "keycode 171 = F8 F8 F8 F8 F8 F8"
xmodmap -e "keycode 121 = F9 F9 F9 F9 F9 F9"
xmodmap -e "keycode 122 = F10 F10 F10 F10 F10 F10"
xmodmap -e "keycode 123 = F11 F11 F11 F11 F11 F11"
xmodmap -e "keycode 118 = F12 F12 F12 F12 F12 F12"

A: I found this blog, Logitech K480 on Ubuntu and 'fn buttons' default behaviour, which appears to solve the same issue as you describe:

By default this keyboard (and as of my understanding similar keyboards
from logitech) have 'media buttons' enabled by default i.e. f1-f12
will act as media buttons and function buttons are accessed by
pressing fn buttons + f1-f12. For work this is really not acceptable.
I made this fix for Logitech K480 based on work of Mario Scholz for
K810. Source code is here:
K480 fix on github
What I did was to re-trace his step, in a virtual machine running win7
I installed SetPoint software from logitech and debugged the output to
the bluetooth device. For K480 I got:
on (bingo!)
> to keyboard
ffff8801d2173000 2960870190 S Bo:2:013:2 -115 16 = 0c200c00 08004200 a210ff08 1c000000
< from keyboard ffff8801ed13b000
1204929370 C Bi:2:013:2 0 29 = 0c201900 15004200 a111ff08 1b000100 00000000 00000000 00000000 00

off
> to keyboard
ffff88062b7db0c0 3001832891 S Bo:2:013:2 -115 16 = 0c200c00 08004200 a210ff08 1c010000
< from keyboard ffff8801ed368b40
1227979618 C Bi:2:013:2 0 29 = 0c201900 15004200 a111ff08 1b010100 00000000 00000000 00000000 00

Note that messages to keyboard start with hex: 'a2' and from keyboard
with 'a1' bytes. All in all, it works fine, I updated device ID as
well to 0xb330 while K810 is 0x319. On a personal note, I like this
keyboard, it has nice 'drop' for keys and spacing is just right –
works really well for fast code writing :).


text:
Q: Return parent data with child document from Elasticsearch Is is possible to return parent data with a search for child documents within an Elasticsearch query?
I have two document types, e.g. Book and Chapter, that are related as Parent/Child (not nested).
I want to run a search on the child document and return the child document, with some of the fields from the parent document. I'm trying to avoid executing a separate query on the parent.
Update
The only way possible I can find is to use the has_child query and then a series of aggregations to drill back to the children and apply the query/filter again. However, this seems overly complicated and inefficient.
GET index/_search
{
  "size": 10,
  "query": {
    "has_child": {
      "type": "chapter",
  "query": {
    "term": {
      "field": "value"
        }
      }
    }
  },
  "aggs": {
"name1": {
  "terms": {
    "size": 50,
    "field": "id"
  },
  "aggs": {
    "name2": {
      "top_hits": {
        "size": 50
      }
    },
    "name3": {
      "children": {
        "type": "type2"
      },
      "aggs": {
        "docFilter": {
          "filter": {
            "query": {
              "match": {
                "_all": "value"
              }
            }
          },
          "aggs": {
            "docs": {
              "top_hits": {
                "size": 50
              }
            }
          }
        }
      }
    }
  }
}
  }
}

A: It is possible do a has_child query to return the parent docs with a top hits aggregation to return the child docs, but it is a bit cumbersome.
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-top-hits-aggregation.html
The Inner Hits feature that is due to be released in 1.5.0 will do what you want.
http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-request-inner-hits.html
You could build the source from master and try it out.

A: This can be now be done with ElasticSearch. Just use 'has_parent' in the search query:
'has_parent': {
    'parent_type': 'book',
    'query': {
        'match_all': {}
    },
    'inner_hits': {}
}

The results will appear in the inner_hits of the response.

A: As Dan Tuffery say in his comment, currently, this can be achieve with Inner Hits, in Java you can understand it more easy with the next snippet of code.
SearchResponse searchResponse = this.transportClient.prepareSearch("your_index")
                .setTypes("your_type")
                .setQuery(QueryBuilders.filteredQuery(
                                null,
                                FilterBuilders.hasParentFilter(
                                        "parent_type_name",
                                        FilterBuilders.termFilter("foo", "foo"))
                                .innerHit(new QueryInnerHitBuilder()))
                )
                .execute().actionGet();

List<YourObject> list = new ArrayList<>();

for (SearchHit searchHit : searchHits.getHits()) {

    YourObject yourObject = this.objectMapper.readValue(searchHit.getSourceAsString(), YourObject.class);
    yourObject.setYourParentObject(this.objectMapper.readValue(searchHit.getInnerHits().get("parent_type_name").getAt(0).getSourceAsString(), YourParentObject.class));

    list.add(yourObject);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: In this Gridview show error java.lang.NullPointerException I am trying the set the image and text from the jsonwebservice in the gridview but show the this error
LogCate

AudioCategoty.Java
public class AudioCategory extends AppCompatActivity {
Toolbar toolbar_home;
//  ImageView imgarrorback,imghomeicon;

static final String TAG = AudioCategory.class.getSimpleName();
static String URL = "http://eonion.in/vimalsagarji/audio/getallcategory";
static String ImgURL="http://eonion.in/vimalsagarji/static/audiocategory/";
ArrayList<String> listName;
ArrayList<String> listIcon;
ProgressDialog pd;
String strImageUrl="";
static Bitmap bitmap=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_audio_category);
    toolbar_home = (Toolbar) findViewById(R.id.toolbar_audio);
    setSupportActionBar(toolbar_home);

    JsonTask jsonTask = new JsonTask();
    jsonTask.execute(URL,ImgURL);

}

private class JsonTask extends AsyncTask<String,String,String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd=new ProgressDialog(AudioCategory.this);
        pd.setMessage("Please Wait");
        pd.setCancelable(false);
        pd.setIndeterminate(false);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
    }

    @Override
    protected String doInBackground(String... params) {
        String strUrl=params[0];
        String ImageURL=params[1];
        try{
            JSONObject jsonObject=JSONParser.getJsonFromUrl(strUrl);
            for (int i=0; i<jsonObject.length()  ;i++){
                JSONArray array=jsonObject.getJSONArray("data");
                for (int j=0;j<array.length();j++){
                    JSONObject object=array.getJSONObject(j);
                    String strName=object.getString("Name");
                    String strCategoryIcon=object.getString("CategoryIcon");
                    strImageUrl=ImageURL+strCategoryIcon;
                    String strImagename=strImageUrl.substring(strImageUrl.lastIndexOf("/")+1);
                    downloadIcon(strImageUrl,strImagename);
                    listName.add(strName);
                    listIcon.add(strCategoryIcon);
                    Log.d(TAG, "list Id data:" + listName);
                    Log.d(TAG, "list Id data:" + listIcon);
                }

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

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (pd != null) {
            pd.dismiss();
        }
         GridView gridView = (GridView)findViewById(R.id.grid_audio);
        if (gridView != null) {
            CustomAdpter adpter = new CustomAdpter(getApplicationContext(), R.layout.custom_audio_gridview, listName);
            gridView.setAdapter(adpter);

        }
        /*gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               *//* String strlitemTitle=listTitle.toString();
                String strlistDescription=listDescription.toString();
                String strlistAddress=listAdrees.toString();
                String strlistDate=listDate.toString();*//*

                String strlitemTitle = (String) ((TextView) view.findViewById(R.id.txtTitle)).getText();
                String strlistDescription = (String) ((TextView) view.findViewById(R.id.txtDescription)).getText();
                String strlistDate = (String) ((TextView) view.findViewById(R.id.txtDate)).getText();
                Intent intent = new Intent(getApplicationContext(), ThisMonthInformation_SubActivity.class);
                intent.putExtra("listTitle", strlitemTitle);
                intent.putExtra("listDescription", strlistDescription);
                intent.putExtra("listDate", strlistDate);
                startActivity(intent);
            }
        });*/
    }
}

private void downloadIcon(String strImageUrl, String strImagename) {
    File fileWithMyDir = getApplicationContext().getFilesDir();
    try {
        java.net.URL url = new URL(strImageUrl);
        File file = new File(fileWithMyDir.getAbsolutePath() + "/" + strImagename);
        System.out.println("image path from service" + fileWithMyDir.getAbsolutePath() + "/" + strImagename);
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);

        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();

    }
}

public class CustomAdpter extends ArrayAdapter<String> {

    List<String> items;
    Context context;
    int resource;

    public CustomAdpter(Context context, int resource, List<String> items) {
        super(context, resource, items);
        this.context = context;
        this.resource = resource;
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(resource, null, false);

            //holder.txt_ID = (TextView) convertView.findViewById(R.id.txtID);
            holder.grid_txtTitle = (TextView) convertView.findViewById(R.id.grid_txtTitle);
            holder.grid_img = (ImageView) convertView.findViewById(R.id.grid_img);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        // holder.txt_ID.setText(items.get(position));
        holder.grid_txtTitle.setText(items.get(position));
        String path=getFinalFilePath(listIcon.get(position));
        bitmap= BitmapFactory.decodeFile(path);
        holder.grid_img.setImageBitmap(bitmap);

        return convertView;

    }

    private String getFinalFilePath(String urlpath) {
        try {
            File fileWithinMyDir = getApplicationContext().getFilesDir();
            String path = fileWithinMyDir.getAbsolutePath();
            String ImageName = urlpath.substring(urlpath.lastIndexOf("/") + 1);
            String FinalPath = path + "/" + ImageName;
            return FinalPath;

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

        return "";
    }

    private class ViewHolder {
        TextView grid_txtTitle;
        ImageView grid_img;

    }
}
}

activity.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorTabBackground"
tools:context="com.vimalsagarji.vimalsagarjiapp.AudioCategory">

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

    <include
        android:id="@+id/toolbar_audio"
        layout="@layout/toolbar_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <EditText
        android:id="@+id/etAudioCategory"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@+id/toolbar_audio"
        android:hint="Audio Category"
        android:padding="10dp"
        android:textColorHint="@color/colorPrimary"/>

    <ImageView
        android:id="@+id/imgSerch"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/toolbar_audio"
        android:layout_marginTop="7dp"
        android:src="@drawable/search"/>

    <View
        android:id="@+id/viewline"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@id/etAudioCategory"
        android:layout_marginTop="-7dp"
        android:background="@color/colorPrimary"/>

    <GridView
        android:id="@+id/grid_audio"
        android:layout_below="@id/viewline"
        android:layout_width="match_parent"
        android:numColumns="3"
        android:layout_height="match_parent"></GridView>
</RelativeLayout>

custom_grid_item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="120dp"
    android:background="@drawable/corner_event"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/grid_img"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:src="@android:drawable/ic_menu_gallery"/>
</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center">

    <TextView
        android:id="@+id/grid_txtTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="170dp"
        android:textSize="14sp"
        android:textColor="@color/colorTabColor"
        android:text="Title"/>

</RelativeLayout>

This above code is implemented in my app but when try the run application that time show the error show pls help me for the output.

A: You haven't initialize the listName. It's null.
Your CustomAdapter calls super(context, resource, items);. It's not allow to pass null as items. Because ArrayAdapter.getCount() doesn't check null for items.
source code from ArrayAdapter:
public int getCount() {
    return mObjects.size();
}

A:   CustomAdpter adpter = new CustomAdpter(getApplicationContext(), R.layout.custom_audio_gridview, listName);

Instead use :
  CustomAdpter adpter = new CustomAdpter(AudioCategory.this, R.layout.custom_audio_gridview, listName);

Also implement:
getCount method inside adapter.

A: Try this...   ArrayList<String> listName=new ArrayList<String>();
inside of AsyncTask method.
     private class JsonTask extends AsyncTask<String,String,String> {
       ArrayList<String> listName=new ArrayList<String>();

            @Override
            protected void onPreExecute() {}
         @Override
            protected String doInBackground(String... params) {}
           @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
    }
}


text:
Q: How to add BlueMix Monitoring and Analytics to a docker-hosted app? Our app (Meteor/NodeJS) is deployed in a docker container in Bluemix, and I'd like to add the Monitoring and Analytics service to the app. The documentation lists how to integrate it with a NodeJS app deployed directly to Bluemix, and also mentions how to integrate with a Ruby-based app. Seems like there should just be an npm package to install, but I see nothing in the docs on how to do this.

A: The Monitoring and Analytics Service is only for Cloud Foundry based Application in IBM Bluemix based on Java Liberty, Node.js SDK or Ruby. The buildpacks have additional configuration and components inside to enable integration with the M&A Service.
https://console.ng.bluemix.net/docs/services/monana/index.html#monana_oview
For IBM Bluemix Container Service with Docker you need to use the built-in Monitoring and Logging for Containers
https://www.ibm.com/blogs/bluemix/2015/11/built-in-monitoring-and-logging-for-bluemix-containers/


text:
Q: 85% Bonferroni family-wide (simultaneous) CI for lm in R The code
confint(model, level = 1 -0.15/length(coef(model)))

was recommended by https://stat.ethz.ch/pipermail/r-help/2005-March/067570.html
However, I have two questions:

*

*How do I avoid including the intercept? For example, here is my output:
> confint(ACFL.m1, level = 1 -0.15/length(coef(ACFL.m1)))
               1.87 %    98.12 %
(Intercept)   1.5838374  3.2846837
PDCD          8.6257799 12.3346769
PMIX        -17.6815440  6.8408247
RTCL          0.2888126  0.6987631

I only want 85% CI for my predictors and not the intercept?

*In the above example, level = 1-0.15/4 = 0.9625.  I know, to get 85% CI for each predictor, the individual CI has to be > 85%, but how do I understand 0.9625% for each summing to as an 85% simultaneous CI?

A: The answer to question 1:
I learned that the package multcomp allows calculation of simultaneous CIs without the intercept. Details about the package are in https://cran.r-project.org/web/packages/multcomp/multcomp.pdf
Its' default is the single-step method and is considered to be more powerful than the Bonferroni method (Bretz et al. 2011). The results of the default method is shown below:
> K <- cbind(0, diag(length(coef(ACFL.m1))-1))
> rownames(K) <- names(coef(ACFL.m1)) [-1]
> ACLF.mc <- glht(ACFL.m1, linfct = K)
> confint(ACLF.mc, level = 0.85)

Simultaneous Confidence Intervals

Fit: lm(formula = PINDX ~ PDCD + PMIX + RTCL, data = ACFL)

Quantile = 1.9021
85% family-wise confidence level

Linear Hypotheses:
           Estimate   lwr      upr
PDCD == 0  10.4802   8.7910  12.1695
PMIX == 0  -5.4204 -16.5895   5.7488
RTCL == 0   0.4938   0.3071   0.6805

To get the Bonferroni 85% CI, I had to first run the Bonferroni Test
ACFL.bf <- summary(ACLF.mc, test= adjusted(type = "bonferroni"))

Then calculate the confidence interval
confint(ACFL.bf, level = 0.85)

I got the following output:
 Simultaneous Confidence Intervals

Fit: lm(formula = PINDX ~ PDCD + PMIX + RTCL, data = ACFL)

Quantile = 1.9021
85% family-wise confidence level

Linear Hypotheses:
           Estimate   lwr      upr
PDCD == 0  10.4802   8.7909  12.1696
PMIX == 0  -5.4204 -16.5898   5.7491
RTCL == 0   0.4938   0.3071   0.6805

Good reference for the multcomp package:
Bretz F, Hothorn T, Westfall PH (2011) Multiple comparisons using R. CRC Press, Boca Raton, FL
Hothorn T (2017) Additional multcomp examples. Accessed online form the R project website https://cran.r-project.org/web/packages/multcomp/vignettes/multcomp-examples.pdf
Hothorn T, Bretz F, Westfall P (2008) Simultaneous inference in general parametric models. Biom J 50:346–363
The answer to question 2:
Based on the formula above, my 85% family-wise CI = 1-0.15/4 = 0.9625% for each variable. I now understand how the lower (1.87 =(1-0.9625)/2) and upper bound values (98.12= ((1-0.9625)/2)+0.9625) came about. I had made a fundamental error in assuming that the 96.25% was a sum of CIs for each variable. I should not have been confused between the 'Bonferroni' and the 'sequential Bonferroni' (Holm, 1979).  Now I understand that each variable is tested at 96.25% so that the family-wise error is 85%. I have left the question as it is so others with similar questions can benefit.


text:
Q: Stop focus on EditText when keyboard is hidden I'm from iOS development and new in Android app making, something looks really strange to me in Android, why EditText stay focused when keyboard is hidden ??
I've tried to set a OnFocusChangeListener on my EditText but this is not working when the keyboard hide, the listener isn't called.
I've also tried to detect keyboard hiding with a onChangeListener but it doesn't work.. (only with hard keyboard apparently).
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // not called when keyboard hides
        }
    });

I've been looking for a while and I only found answer for stopping focus at first launch but that's not what I'm looking for..
Thanks

A: Okay, kind of this
  private void setUpEtxFocusListener() {
    etx.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if (hasFocus) {
                if ((LOG_DEBUG)) Log.d(TAG, "etx : GOT Focus");

            } else {
                if ((LOG_DEBUG)) Log.d(TAG, "etx : LOST Focus");

            }
        }
    });

and when clicked outside, etx will lose focus and you hide the keyboard
 //this will trigger etx  setOnFocusChangeListener -  onFocus change() - NO FOCUS clause
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if (v instanceof EditText) {
            Rect outRect = new Rect();
            v.getGlobalVisibleRect(outRect);
            if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) {
                v.clearFocus();
               // just an utility class to hide.
                UtilExtra.hideKeyboard(this);
            }
        }
    }
    return super.dispatchTouchEvent(event);
}

A: Try this:
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

A: you can simply use this code and your focus will be gone
editText.clearFocus();

A: To catch keyboard's open/close event use this code:
    //...
    private int layoutSize = 0;
    private boolean isKeyboardVisible = false;
    //...
    @Override
    public void onCreate(Bundle savedInstanceState) {
        setKeyboardOpenListener();
    }
    //...
    private void setKeyboardOpenListener() {
            View activityRootView = findViewById(android.R.id.content);
            activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
                if (activityRootView.getHeight() + Util.getStatusBarHeight(this) >= layoutSize) {
                    layoutSize = activityRootView.getHeight();
                    if (isKeyboardVisible) {
                        isKeyboardVisible = false;
                        onKeyboardClose();
                    }
                } else {
                    if (!isKeyboardVisible) {
                        isKeyboardVisible = true;
                        onKeyboardOpen();
                    }
                }
            });
        }
    //...
    public static int getStatusBarHeight(Context context) {
            int result = 0;
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = context.getResources().getDimensionPixelSize(resourceId);
            }
            return result;
        }

A: Use editText.clearFocus() and editText.setCursorVisible(false) both methods, It may helps you.


text:
Q: How to hide/show selectOneMenu in JSF? I have an inputText and a selectOneRadio component, when form load selectOneRadio should be hidden. When user select inputText, I want to show the selectOneRadio component. I have made the selectOneRadio hidden in @PostConstruct, which should be display on select inputText.
<h:panelGrid id="panelgrid">
    <p:panel id="panel" >
        <h:outputLabel value="Name: " for="name" />
        <p:inputText id="name" value="#{userBean.name}" immediate="true">
        <p:ajax event="onselect" update="city" listener="#{userBean.showName}" />
        </p:inputText>
        <p:selectOneRadio  id="city" value="#{userBean.city}" layout="grid" columns="3" rendered="#{userBean.displayName}" >
            <f:selectItems value="#{userBean.cities}" var="c" itemLabel="#{city}" itemValue="#{city}" />
        </p:selectOneRadio>
    </p:panel>
</h:panelGrid>

The bean code is like:
@PostConstruct
public void init() {
    displayName = false;
}

public boolean isShowName() {
    return true;
}

...

But some how this is not working. I'm using JSF2.0 with primefaces 5.2.

A: I found the solution.
<h:form id="frm">
    <h:panelGrid id="panelgrid">
        <p:panel id="panel" >
        <h:outputLabel value="Name: " for="name" />
            <p:inputText id="name" value="#{userBean.name}" immediate="true" onkeypress="#{userBean.showName}">

                <p:ajax event="change" update="frm:panelgrid" listener="#{userBean.inputcangeeListener}" />
            </p:inputText>
        </p:panel>

            <p:panel id="p2" rendered="#{userBean.displayName}">
                <p:selectOneRadio id="city" value="#{userBean.city}" layout="grid" columns="3">
                    <f:selectItems value="#{userBean.cities}" var="c" itemLabel="#{city}" itemValue="#{city}" />
                </p:selectOneRadio>
            </p:panel>

        </h:panelGrid>
    </h:form>

And my managed bean looks like-
    @PostConstruct
    public void init() {
        displayName = false;
    }

    public boolean isShowName(){
        return displayName;
    }

    public void inputcangeeListener(javax.faces.event.AjaxBehaviorEvent changeEvent){
        setDisplayName(true);
        cities = new ArrayList<>();
        cities.add("pune");
        cities.add("KOL");

    }

Thanks for your response.


text:
Q: How to make bot not stop after error? Discord.js I have script which have to kick user with reason.
Syntax:
$kick @user Reason
but when I type:
$kick sometext nexttext
I got error in console:
TypeError: Cannot read property 'kick' of undefined
and bot stop...
How can I edit this script so that after entering an incorrect value, an error will not pop up turning off the bot and bot will send message to channel eg. "Incorrect value"?
Script:
const discord = require('discord.js');
const client = new discord.Client;
const prefix = "$";
 client.on('message', function(message) {
const args = message.content.slice(prefix.length).trim().split(/ +/g);

const command = args.shift().toLowerCase();

if(command === "kick") {

 let member = message.mentions.members.first();
 let reason = args.slice(1).join(" ");
  member.kick(reason);
  message.delete();
  client.channels.cache.get('737341022782357566').send("User <@" + member.id + "> with id " + member.id + " has been kicked by <@" + message.author.id + "> with reason " + reason)

}})
client.login('token');

A: in javascript to execute a code that have chances to chrash, you can use the statment
try {
//code to test
} catch(err) {
//code if it crash
}

A: add a if (member) to test if there was a mention.
In the else, you can send your "bad command" message
you should also only trigger the bot if the message starts with your prefix
const discord = require('discord.js');
const client = new discord.Client;
const prefix = "$";

client.on('message', function(message) {
  if (!message.content.startsWith(prefix)) { return }
  //this line prevents the bot to execute every message
  const args = message.content.slice(prefix.length).trim().split(/ +/g);

  const command = args.shift().toLowerCase();

  if(command === "kick") {

    let member = message.mentions.members.first();
    let reason = args.slice(1).join(" ");
    if (member) { // add this
      member.kick(reason);
      client.channels.cache.get('737341022782357566').send(`User ${member.user} with id: ${member.id} has been kicked by ${message.author} with reason: ${reason}`);
    } else {
      message.reply("invalid parameters for $kick")
    }

    message.delete();
  }
})

client.login('token');


text:
Q: Why iptables mangle table does not catch packets? I'm trying to setup a proxy server in docker container in order to route some packets out of VPN (some sites does not respond to the VPN's ip, they are country locked). In order to do that, I try to mark packets which are send to and from docker container interface.
I use proxy server container connected to user-defined bridge docker network (172.18.0.0/16) with virtual interface named br-43cb854b8af8. Name of the physical network interface on my PC is enp3s0. There is also standard docker bridge interface docker0 with net 172.17.0.0/16, so while it is included in the iptables rules it is not used.
On the start of the PC tables raw and mangle are empty,
filter table:
-P INPUT ACCEPT
-P FORWARD DROP
-P OUTPUT ACCEPT
-N DOCKER
-N DOCKER-ISOLATION-STAGE-1
-N DOCKER-ISOLATION-STAGE-2
-N DOCKER-USER
-A FORWARD -j DOCKER-USER
-A FORWARD -j DOCKER-ISOLATION-STAGE-1
-A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -o docker0 -j DOCKER
-A FORWARD -i docker0 ! -o docker0 -j ACCEPT
-A FORWARD -i docker0 -o docker0 -j ACCEPT
-A FORWARD -o br-43cb854b8af8 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -o br-43cb854b8af8 -j DOCKER
-A FORWARD -i br-43cb854b8af8 ! -o br-43cb854b8af8 -j ACCEPT
-A FORWARD -i br-43cb854b8af8 -o br-43cb854b8af8 -j ACCEPT
-A DOCKER -d 172.18.0.2/32 ! -i br-43cb854b8af8 -o br-43cb854b8af8 -p tcp -m tcp --dport 3128 -j ACCEPT
-A DOCKER-ISOLATION-STAGE-1 -i docker0 ! -o docker0 -j DOCKER-ISOLATION-STAGE-2
-A DOCKER-ISOLATION-STAGE-1 -i br-43cb854b8af8 ! -o br-43cb854b8af8 -j DOCKER-ISOLATION-STAGE-2
-A DOCKER-ISOLATION-STAGE-1 -j RETURN
-A DOCKER-ISOLATION-STAGE-2 -o docker0 -j DROP
-A DOCKER-ISOLATION-STAGE-2 -o br-43cb854b8af8 -j DROP
-A DOCKER-ISOLATION-STAGE-2 -j RETURN
-A DOCKER-USER -j RETURN

nat table:
-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT
-N DOCKER
-A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER
-A OUTPUT ! -d 127.0.0.0/8 -m addrtype --dst-type LOCAL -j DOCKER
-A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
-A POSTROUTING -s 172.18.0.0/16 ! -o br-43cb854b8af8 -j MASQUERADE
-A POSTROUTING -s 172.18.0.2/32 -d 172.18.0.2/32 -p tcp -m tcp --dport 3128 -j MASQUERADE
-A DOCKER -i docker0 -j RETURN
-A DOCKER -i br-43cb854b8af8 -j RETURN
-A DOCKER ! -i br-43cb854b8af8 -p tcp -m tcp --dport 3128 -j DNAT --to-destination 172.18.0.2:3128

The problem is that if I add
iptables -t mangle -A PREROUTING -i br-43cb854b8af8 -j MARK --set-mark 1
iptables -t mangle -A PREROUTING -i enp3s0 -s 172.18.0.0/16 -j MARK --set-mark 1

to mark outgoing packets from proxy server, the second rule does not applies to any packets, while first one does and while masquerading through enp3s0 also works. In other words, packets go as they should, but rule
iptables -t mangle -A PREROUTING -i enp3s0 -s 172.18.0.0/16 -j MARK --set-mark 1
for some reason is not applied. Also there is not turned on VPN or any applied ip routes or rules aside from the default ones.

A: First of all as it has been answered in a comment to the question, 2nd rule is not applicable because -i means that the packet was received from interface enp3s0. So in order to mark all the outgoing packets from proxy first rule would suffice.
In order to do the same for the incoming packets we need to add
iptables -t mangle -A FORWARD -i enp3s0 -d 172.18.0.0/16 -j MARK --set-mark 1

So, now then all packets for and from br-43cb854b8af8 are marked (but the one which are sent from browser to proxy), it is time set routes.
First group of commands is
ip rule add to 172.18.0.0/16 pref 100 table 1
ip rule add fwmark 0x0001 pref 101 table 1
ip route add table 1 to 172.18.0.0/16 dev br-43cb854b8af8

They allow to traffic from browser and incoming traffic for proxy go straight to the docker network. Options pref are used, because VPN also sets its rules, which we want to be checked only if the rules above are not applicable to packets.
The second group of commands is
ip rule add fwmark 0x0001 pref 102 table main

It sets it so that if packet has a mark and not going to docker's net (which means that it is outgoing from docker's net) it would avoid rules of VPN and move by his standard route without VPN.
Final script
#!/bin/sh

iptables -t mangle -A PREROUTING -i br-43cb854b8af8 -j MARK --set-mark 1
iptables -t mangle -A FORWARD -i enp3s0 -d 172.18.0.0/16 -j MARK --set-mark 1

ip rule add to 172.18.0.0/16 pref 100 table 1
ip rule add fwmark 0x0001 pref 101 table 1
ip route add table 1 to 172.18.0.0/16 dev br-43cb854b8af8

ip rule add fwmark 0x0001 pref 102 table main

ip route flush cache


text:
Q: "Can't open display" when using `scp` When I type scp file1 user@host.com:file2 into the command prompt, I get the message
Can't open display
Can't open display
Can't open display
Can't open display
Can't open display
file1                          100%  589KB 589.0KB/s  00:00

And then I wait for about 10 seconds, before the scp returns to the command line.  This does not happen with ssh, only with scp.  I am using Fedora 18.

A: Your profile scripts probably have some commands that expect an interactive session with a terminal emulation. And they fail when executed in a non-interactive scp session.
For example, if you are using bash, such commands should be moved from .bashrc script to .bash_profile.
Or use TERM or PS1 environment variable or similar trick to skip those commands for a non-interactive session.
# If running interactively, then:
if [ "$PS1" ]; then

#### Alex's funky commands might go here                          <------
    /usr/bin/ssh-agent &

    # If this is an xterm set the title to user@host:dir
    case $TERM in
    xterm*)
        PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'
#### Alex's funky commands might also go here if they apply to xterm sessions  <------
        ;;
    *)
        ;;
    esac

fi

This will not evaluate if you use scp to copy a file, but will if you start an interactive session.
(The sample code is by @Criggie)


text:
Q: Anchor tag onclick event in aspx page works in IE (11) but fails to respond in Chrome and Firefox Anchor tag onclick event in aspx page works in IE but fails to respond in Chrome and Firefox
Code:

    Sample

works perfectly fine in IE(version 11) but fails to do any action in Chrome and Firefox. What am I missing? Any help.

A: I don't know why I didn't realize this a while ago, but why don't you just remove the quotes from the FrameRightPanel...
onclick = 'parent.window.frames[FrameRightPanel].location=this.href;return false;' >

The browser should interpret that as JS code and the value of FrameRightPanel would be substituted.

A: Found the solution. The IFrame was missing the name attribute!!
Earlier code was

added Name

Now it works in IE, Chrome & FireFox.


text:
Q: Backup a VM while it is running I have several virtual machines created with VMware Workstation 11 which must run 24/7. I'm not allowed to shutdown/suspend it temporarily.

*

*What options do I have to backup this VM while it is running? (hot clone)

*Can I restore a VM on another machine when I just copy its entire folder while the VM is running?

*How can I automate this backup process assuming the host system is Windows 7.
So PowerShell, Command Line, Task Scheduler are available.

My research found this method which works from a ESXi service console which I believe is not available under Windows 7 and VMware Workstation 11, or?

A: You need to implement a standard supported infrastructure to achieve what you want, otherwise you are going to create a bundle of hacks.
If your VM needs to run 24/7, what have you done to cater for hardware failure? This isn't just a situation of "I need to make a backup copy", it should also be "I need to cater for maximum uptime".
A full VMware kit, two hosts, shared storage, HA etc will cater for all of this. Hell, you might even be able to use VMware's Fault Tolerance feature which would permit hardware failure without skipping a beat.
If you were to implement a correct infrastructure, you could then utilise products such as Veeam Backup. This and similar products backup from the outside while the VM is running with no interruption.
If you want to just ensure you have backup copies (which you could restore elsewhere) and have a tight budget, might I recommend Veeam Endpoint Backup which is free. Install this into the VM and backup to an external device like a NAS. You could restore back onto another machine. This isn't as elegant, but there is obviously a significant difference in price here.
Last note - if you are going to design and implement a redundant infrastructure, PLEASE use a certified VMware Reseller who has certified VMware Engineers. Don't use someone who hasn't been trained as they (in my experience) will implement single points of failure (ie: two servers, shared storage and ONE SWITCH).


text:
Q: Manually managed dependencies with Visual Studio I am reading through 'Dependency Injection in .Net' and would like to being implementing some of the ideas presented.  To be absolutely upfront, I would like to attempt a 'Poor Mans DI'/No DI Container -- manually managing Dependencies -- to better understand the concepts before jumping into a DI Container.
There is an example illustrated in Chapter 2 that demonstrates a Composition Root and creating the dependencies (and constructor injection).  The basic idea was similar to this:
Web Project (has CompositionRoot.cs) --> Domain Project <-- DataAccess Project

The Composition root creates a DataAccess instance and passes it to the constructor of the Domain project's classes -- all of the dependencies are read from the web.config.
I am completely on board with the above idea and agree the Web Project shouldn't reference the DataAccess project.  My understanding at this point is that the Web Project really does need a reference to the DataAccess project in order to create an instance via Reflection.
My questions:

*

*My understanding would be that I would need to copy over the DataAccess.dll to the Web Project's Bin folder for everything to build.  This seems very labor intensive so I would be interested in setting Visual Studio to do this for me? This was all I found thus far.

*How does a DI Container resolve what I have described?  ** I haven't looked into any containers yet so I am unaware if they would require a hard reference to the dependency project.

A:
My understanding would be that I would need to copy over the DataAccess.dll to the Web Project's Bin folder for everything to build.

Since you have a separate DataAccess.dll, then yes.

I would be interested in setting Visual Studio to do this for me

You can use pre build events to do so (in the Build tab of the project property pages).
Consider that you may not need to if you still do DI but in the same project. Projects should be deployment units, when you physically need to deploy classes separately. Use namespaces/directories for logical separation and you will not have this issue.

How does a DI Container resolve what I have described?

You tell it. Either explicitly when configuring it, or using conventions.


text:
Q: Set id to newly created elements This is mine first question, I'm glad to be part of this community.
Like I said in the title. I want to set ID to newly created elements. I don't know what I'm doing incorrectly.
This is mine code sample:
function DataBack(response) {
var ci_output = document.getElementById('ci_output');
data = JSON.parse(response);
for (i = 0; i < data.result.length; i++) {
    var li = document.createElement("p");
    li.setAttribute("id",'cmdbitem' + i);
    li.setAttribute('onclick', 'displayDetails(data.result[' + i + '])');
    document.getElementById('cmdbitem' + i).onclick = changeColor; //this function is throwing error "Uncaught TypeError: document.getElementById(...) is null"
    li.innerHTML = data.result[i].name;
    ci_output.appendChild(li);
    }
 }

What i want to achieve is to change color for newly created item which user click on. For this i need ID.
I made test and ID is set because e.g. this specific element is behave like it should
#cmdbitem2 {
cursor : pointer;

}
Why this document.getElementById('cmdbitem' + i).onclick = changeColor; is throwing an error ?
Thanks from advance.

A: because the new element li is not inserted to document yet (which happends at ci_output.appendChild(li);).
but you can simply use li here, no need to get it though getElementById

Here is a complete example from your code.
for (let i = 0; i < data.result.length; i++) {
   let li = document.createElement("p")
   li.id = 'cmdbitem' + i
   li.addEventListener('click', ()=>displayDetails(data.result[i]))
   li.addEventListener('click', changeColor)
   li.innerHTML = data.result[i].name
   ci_output.appendChild(li)
}

some reference:

*

*arrow function (you can also use normal function)

*let (Always use let instead of var)

A: Your function is throwing an error because it couldnt find your element.
So lets go through your code:

*

*You create an element

*You search in the document for your element

*You add your element to the document
Notice how you searched the document for your element before you added it to the document?
document.getElementById searches through your document and not through all elements. Hope this helps! :D
EDIT: You can also just do li.onclick, this would be the best solution.


text:
Q: Can we play .swf file in webview Can we play .swf file in webview?
It works with 4.0 and lower version. But unable to play in higher version.
Is there any way to play .swf file?

A: so far i come to know that we can play swf  on 4.0+ using Firefox. You just need to download

*

*Mozilla Firefox for android

*Adobe Flash Player 11
Now go to Firefox Settings/Customize/Display/Plugins and choose enabled.Start Flash Player and choose Firefox as default browser. Enter your flash file url in browser.
And if we want to make it work in app we have to use GeckoView link


text:
Q: samba does not work when offline I have recently set up a virtual machine and I want to share files between the host and the guest. Samba seems to be a perfect solution, and indeed it does all that I expect it to. However, if the host machine is not connected to the internet, the Samba server appears offline too. Can somebody show me how to make it work?
Note: ps -ef | grep smb shows that smbd -F is running, so I think the process is started properly.
EDIT: I'm using VirtualBox for the virtualization. Below is my config in /etc/samba/smb.conf (I have never changed it, comments removed for simplicity). Sharing is enabled through the GUI in nautilus.
[global]
workgroup = WORKGROUP
server string = %h server (Samba, Ubuntu)
dns proxy = no
log file = /var/log/samba/log.%m
max log size = 1000
syslog = 0
panic action = /usr/share/samba/panic-action %d
encrypt passwords = true
passdb backend = tdbsam
obey pam restrictions = yes
unix password sync = yes
passwd program = /usr/bin/passwd %u
passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
pam password change = yes
map to guest = bad user
usershare allow guests = yes

A: Have you checked if changing the type of the VirtualBox network adapter makes a difference? Shut down the virtual machine, got to Settings->Network and try to change the value of "Attached to". The default is NAT, which should be fine, however if you have NAT and it doesn't work for you, you might try bridged. If you already have bridged there, try NAT.
Before doing this, you should read the information found in VirtualBox Help, Chapter 6.2. Introduction to networking modes.

A: I had a similar problem too: here what I did:
Looks like in
/etc/resolv.conf
I had no ip set for the local DNS nameserver, wich in my case is the rooter itself.
I had a few ips of internet DNS nameservers, that point out of my network, but not to my router, so ai just added:
nameserver 192.168.1.2
where 192.168.1.2 is my router ip. and SAMBA works just great even when my internet conexion is down!!


text:
Q: How to check if a oracle database is compatible with REGEXP_LIKE? I'm trying to use the Regexp_like function in my oracle SQL queries, but no matter what I'm am trying I get the "ORA-00920: invalid relational operator" error. I have tried with regexp_like arguments from samples that should work, and simply changed the referenced field, and still it fails. The version is:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
PL/SQL Release 11.2.0.3.0 - Production
CORE    11.2.0.3.0  Production
TNS for Solaris: Version 11.2.0.3.0 - Production
NLSRTL Version 11.2.0.3.0 - Production

However I suspect that some compatibility level is set so that the regexp_like function isn't supported. How can I check this?

A: As I said in a comment, regexp_like is a condition not a function, so you can't compare it with a field. You should be doing:
SELECT *
FROM GLOBALDB.CUSTOMERS C
WHERE REGEXP_LIKE(C.SHORT_NAME,'^CHRH$');

That is what is shown in the documentation.
Of course, since you're comparing the whole field, in this case you might as well do:
WHERE C.SHORT_NAME = 'CHRH';


text:
Q: Nodejs browser-sync install issue I am using Windows Ubuntu bash terminal
Trying to install browser-sync for nodejs and after the command
npm install -g browser-sync.
I am getting an error message:

: not foundram Files/nodejs/npm: 3: /mnt/c/Program Files/nodejs/npm: :
  not foundram Files/nodejs/npm: 5: /mnt/c/Program Files/nodejs/npm:
  /mnt/c/Program Files/nodejs/npm: 6: /mnt/c/Program Files/nodejs/npm:
  Syntax error: word unexpected (expecting "in")

Path is set C:\Users\vladi\AppData\Roaming\npm;C:\Program Files\nodejs\ and that path is correct
Do you have any ideas?

A: Solution :
$ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
$ sudo apt-get install -y nodejs
then i made some changes to my PATH in my ~/.profile
PATH="$HOME/bin:$HOME/.local/bin:/usr/bin:$PATH"
Close the bash, re-open it and run the command again npm install -g browser-sync
It worked like a charm


text:
Q: Cordial Ratios - per litre compared to as is This has got us stuffed but I feel there has to be a simple explanation.
Q: concentrate:water are 2L:1L, 3L:2L, 1.25L:750mL, 2L:1.5L, 1.5L:800mL.
If you mix all together what is the ratio?
Leaving quantities as they are you get a different ratio to converting each to x:1 first.
Shouldn't they be identical for both methods?
Why is there a difference?
I have a math degree and I feel like an idiot!

A: I would approach it like this. Consider that you're mixing substance A and substance B in different ratios in different bottles. In bottle number $i$ you have amount $A_i$ of substance A and amount $B_i$ of substance B. Then, when you add them up together, surely the amount of substance A in the final product is the sum over $i$ of $A_i$, right?
$$
\sum_i A_i
$$
And the amount of substance B is then $\sum_i B_i$. Therefore, the final ratio A/B of the final product is
$$
\frac{  \sum_i A_i  }{\sum_i A_i + \sum_i B_i}
$$
I think from this on you should already know what to do.


text:
Q: JS Filter through exceptions I've written like that code and it works.
Could you help to make it dynamic?

function compact(arr) {
  const consts = [false, null, 0, "", undefined, NaN]
  let result = arr.filter(state => state != consts[0] && state != consts[1] && state != consts[2] && state != consts[3] && state != consts[4] && state != consts[5])
  return result
}

console.log( compact([0, 1, false, 2, "", 3]) ); // => [1, 2, 3]

A: You can use Array#includes in the filter callback.

function compact(arr) {
  const consts = [false, null, 0, "", undefined, NaN]
  let result = arr.filter(state => !consts.includes(state))
  return result;
}
console.log(compact([0, 1, false, 2, "", 3]));

If you just want to remove the falsy values, you can directly return the current element in the callback, which will remove the element if it is not truthy. arr.filter(Boolean) works as well, as mentioned by nick zoum.

function compact(arr) {
  return arr.filter(x => x);
}
console.log(compact([0, 1, false, 2, "", 3]));


text:
Q: Проблема "требуется идентификатор" элемента max() Столкнулся с проблемой перекрывания друг друга одноимёнными программными элементами (если это так можно назвать). То есть, используя max вместе с библиотекой windows.h, в которой содержится директива:
#define max(a, b) (((a) > (b)) ? (a) : (b))

В данном коде возникает ошибка "требуется идентификатор" на элементах max:
#include <iostream>
#include <windows.h>

short safeInput() {

short val = 0;

while (!(std::cin >> val)) {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Wrong input, only integers are expected!" << std::endl;
}

std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

return val;

}
p.s Если не подключать библиотеку windows.h, то всё нормально.
Как решить её и вообще в будущем разграничивать подобные одноимённые элементы, предотвращать подобные ошибки, если пространство имён не помогает (ну или помогает, однако я пока что не знаю как)?

A: Используется хак - заключение в скобки. Например, закрывающая скобка (да и любой символ, не эквивалентный пробелу) после имени макроса перед скобками с параметрами (std::max)(a,b) не даёт расширять макросы с параметрами.
Ваш пример:
#include <iostream>
#include <windows.h>

short safeInput() {

short val = 0;

while (!(std::cin >> val)) {
    std::cin.clear();
    std::cin.ignore((std::numeric_limits<std::streamsize>::max)(), '\n');
    std::cout << "Wrong input, only integers are expected!" << std::endl;
}

std::cin.clear();
std::cin.ignore((std::numeric_limits<std::streamsize>::max)(), '\n');

return val;

Не забудьте, что ещё и abs часто определяют макросами.

A: Либо сразу после включения windows.h сделайте
#undef min
#undef max

Либо еще до включения windows.h определите макро NOMINMAX (лучше - глобально в настройках проекта).


text:
Q: Modified files in a git branch are spilling over into another branch I am working on a git repository with a master branch and another the topic branch. I have switched to topic branch and modified a file. Now, if I switched to the master branch, that same file is shown as modified.
For example:
git status in git-build branch:
# On branch git-build
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       modified:   cvsup_current
#

Switch to master branch
[root@redbull builder_scripts (git-build)]# git co master
M       builder_scripts/cvsup_current
Switched to branch "master"

git status in master branch
[root@redbull builder_scripts (master)]# git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       modified:   cvsup_current
#

Why is that the file is shown as modified in the master branch even though it was modified in git-build branch?
My understanding was that the branches are independent of each other and when I change from one branch to another the changes do not "spill over" from one branch to another. So I am obviously missing something here.
Has anyone got a clue stick?

A:
Why is that the file is shown as modified in master branch even though it was modified in git-build branch?

The key to remember is that the file was not modified in the git-build branch. It was only modified in your working copy.
Only when you commit are the changes put back into whichever branch you have checked out

A: If you want to temporarily store your changes to one branch while you go off to do work on another, you can use the git stash command.  It's one of the amazing little unsung perks of using git. Example workflow:
git stash #work saved
git checkout master
#edit files
git commit
git checkout git-build
git stash apply #restore earlier work

git stash stores a stack of changes, so you can safely store multiple checkpoints.  You can also give them names/descriptions.  Full usage info here.

A: *

*It is not like git branches are dependent on each other but also they
do not have a complete code base separately for each branch either.

*For each commit, Git stores an object that contains a pointer to the
changes. So each branch points to its own latest commit and HEAD points to the branch currently you are in.

*When you switch the branch, the HEAD pointer points to that
particular commit of the branch. So if there are modified files, the
default behavior is to copy over them.

You can do the following things to overcome this issue.

*

*Use -f option to ignore the changes.

If you want to save the changes:

*Commit the changes locally in the same branch and then switch the
branch.

*Use git stash, switch the branch, do your work, switch back to the
original branch and do git stash apply.

A: This is the default behaviour of git.
You can use -f flag to checkout to do "clean checkout" if you like.

A: The modified files are not put in the repository until you add and commit them. If you switch back to your topic branch and commit the file, then it won't appear on the master branch.

A: In my experience this "spillover" problem arises because git does not protect "untracked" files from git checkout (only tracked but uncommitted files would be protected, i.e. user would be forced to git commit them before a git checkout is allowed to another branch).
If you switch back to the original branch that created these files (and "untracks" them), these files become "untracked" again and can be git add'ed or git rm'ed.
For me it looks like a bug: even "untracked" files should be protected from git checkout.


text:
Q: Substituting service url is arm template I have an ARM template that deploys API's to an API Management instance
Here is an example of one API
{
  "properties": {
    "authenticationSettings": {
      "subscriptionKeyRequired": false
    },
    "subscriptionKeyParameterNames": {
      "header": "Ocp-Apim-Subscription-Key",
      "query": "subscription-key"
    },
    "apiRevision": "1",
    "isCurrent": true,
    "subscriptionRequired": true,
    "displayName": "DDD.CRM.PostLeadRequest",
    "serviceUrl": "https://test1/api/FuncCreateLead?code=XXXXXXXXXX",
    "path": "CRMAPI/PostLeadRequest",
    "protocols": [
      "https"
    ]
  },
  "name": "[concat(variables('ApimServiceName'), '/mms-crm-postleadrequest')]",
  "type": "Microsoft.ApiManagement/service/apis",
  "apiVersion": "2019-01-01",
  "dependsOn": []
}

When I am deploying this to different environments I would like to be able to substitute the service url depending on the environment.  I'm wondering the best approach?
Can I read in a config file or something like that?
At the time of deployment I have a variable that tells me the environment so I can base decisions on that.  Just not sure the best way to do it

A: See about ARM template parameters: https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authoring-templates#parameters They can be specified in a separate file. So you will have single template, but environment specific parameter files.


text:
Q: Can I export an Access form to Excel with the same exact formatting? I have a continuous access form where all controls are snapped into the grid. When I try the Excel export tool in the ribbon, it exports it as a traditional table, but I want to keep the formatting I have on the form (number of columns/rows per record, location of controls, colors, etc.). Is this possible with VBA? I don't mind if I even have to re-create the format in code.
Thanks!

A: You can try the command:
DoCmd.OutputTo acOutputForm, Me.Name, acFormatXLSX, ..etc.

It seems to preserve some formatting.


text:
Q: Почему i[array] подобен array[i]? Не совсем понятно:
int i;

int array[anySize];

Почему запись arr[i] эквивалентна i[arr]?

A: arr это просто указатель на первый элемент массива (arr == &arr[0]) То есть arr[i] == *(&arr[0] + i). Это просто синтаксический сахар, который и так работает. Я думаю вы поторопились, в книге по которой вы изучаете язык просто обязано быть об этом.

A: Потому как все равно "за сценой" все это преобразуется в указатель с помощью арифметики arr+i, а как известно, a+b == b+a :)

A: Потому что стандарт. Смотрите пункт 5.2.1:

A postfix expression followed by an expression in square brackets is a
  postfix expression. One of the expressions shall have the type "array
  of T" or "pointer to T" and the other shall have unscoped enumeration
  or integral type. The result is of type "T." The type "T" shall be a
  completely-defined object type.64 The expression E1[E2] is identical
  (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of
  * and
  + and 8.3.4 for details of arrays. — end note ], except that in the case of an array operand, the result is an lvalue if that operand is
  an lvalue and an xvalue otherwise.

Гугл-переводчик:

Постфиксное выражение, за которым следует выражение в квадратных
  скобках, является постфиксным выражением. Одно из выражений должно
  иметь тип «массив Т» или «указатель на Т», а другой должен иметь
  неперечисленное перечисление или интегральный тип. Результат имеет тип
  «T». Тип «T» должен быть полностью определенным типом объекта.
  Выражение E1 [E2] идентично (по определению) к * ((E1) + (E2))
  [Примечание: См. 5.3 и 5.7 для деталей * и + и 8.3.4 для получения
  подробной информации о массивах. - end note], за исключением того, что
  в случае операнда массива результат равен lvalue, если этот операнд
  является lvalue и xvalue в противном случае.


text:
Q: Enable disable button based on WPF datagrid selected rows following MVVM c# In my WPF app I have a datagrid
<DataGrid SelectedItem="{Binding SelItm ,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          ItemsSource="{Binding Bills}"
          SelectionMode="Extended"
          Name="myGrid"...

Now I want to enable a button if any rows of the datagrid are selected, if no rows are selected the button should be disabled, pretty simple stuff.
My button xaml is like
<Button
    Command="{Binding PreviewButtonClicked}"
    CommandParameter="{Binding SelItm, ElementName=myGrid}"

I've create a standard RelayCommand class
public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Predicate<object> _canExecute;

        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
        }

        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }

and my viewmodel class contains:
public class myVM()
{
    private string _SelItm;
    public string SelItm
    {
        get { return _SelItm; }
        set
        {
            SetValue(ref _SelItm, value);
        }
    }
  public RelayCommand PreviewButtonClicked { get; set; }

  public myVM()
  {
    PreviewButtonClicked = new RelayCommand(ShowPDF, CanShowPDF);
  }

  public void ShowPDF(object param)
  {
    //do stuff
  }

  public bool CanShowPDF(object param)
  {
        if (SelItm.Any())
        {
            return true;
        }

        return false;
  }

}

But when I run the app I get the below error on line if (SelItm.Any())

System.ArgumentNullException: Value cannot be null.

What am I doing incorrectly ?

A: There are at least three options.
Option 1 - Codebehind
Add an event handler to the SelectionChanged event on the DataGrid.
<DataGrid SelectedItem="{Binding SelItm ,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          ItemsSource="{Binding Bills}"
          SelectionMode="Extended"
          SelectionChanged="DataGridSelectionChanged"
          Name="myGrid"...

The SelectionChanged event will be invoked when there's a full row selected. (You can set the SelectionUnit as "Rows" on the DataGrid explicitly) Otherwise use the SelectedCellsChanged event.
In the handler of the SelectionChanged event:
private void DataGridSelectionChanged(object sender, SelectionChangedEventArgs args)
{
    myButton.IsEnabled = myGrid.SelectedItems.Count > 0;
}

Option 2
You can bind the SelectedItem property on the DataGrid, to your viewmodel.
<DataGrid SelectedItem="{Binding SelItm ,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          ItemsSource="{Binding Bills}"
          SelectionMode="Extended"
          SelectedItem="{Binding SelectedItemInDataGrid}"
          Name="myGrid"...

In the viewmodel, simplified and also assuming your vm implements INotifyPropertyChanged:
private object _selectedItemInDg;

public object SelectedItemInDataGrid
{
    set {
        _selectedItemInDg = value;
        OnPropertyChanged(nameof(SelectedItemInDataGrid ));
        OnPropertyChanged(nameof(IsButtonEnabled));
        PreviewButtonClicked?.UpdateCanExecute();
    }
    get => _selectedItemInDg;
}

public bool IsButtonEnabled => _selectedItemInDg != null;

private void OnPropertyChanged(string name)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}

And your button:
<Button IsEnabled="{Binding IsButtonEnabled}" Command="..." CommandParameter="...">Content of button</Button>

Option 3 - In CanExecute
You've got a method in your viewmodel, CanShowPDF(object param), which determines for the RelayCommand wether the command can be executed or not. WPF enables/disables the button automatically based on the CanExecute method of an ICommand instance.
I'd add a method to the RelayCommand class:
public void UpdateCanExecute() {
    CanExecuteChanged?.Invoke();
}

Call the UpdateCanExecute method on your RelayCommand instance every time something changes that would affect the result of CanShowPDF.
The exception
You ask about an exception you get:
System.ArgumentNullException: Value cannot be null.

Probably you are calling a method on something that is null at that moment.
But it's hard to figure out the cause with the given information in the question and I don't actually know what SelItm is, although seen the name we could guess.


text:
Q: Angular, Share dynamic properties values between child components I am new in Angular and I am trying to learn about the best practices. I am struggling for two days with this problem, and finally I solved it, but I am not confortable with the solution I found, I will try to explain what I did, and maybe someone knows a better solution, thanks in advance.
1 I have 3 componentes: categoryComponente (parent) and 3 children (categoryCreate, categoryUpdate and categoryList).
2 categoriesList render all the categories in the backend (endpoint), using a service who shares all these components (this is working fine):
ngOnInit() {
    this.service.getCategories().subscribe( (categories): any => {
      this.categories = categories.data;
    });
  }

3 categoryList has a (click) event:
<button (click)="editCategory(category._id)" class="btn btn-outline-primary btn-block">Update</button>

4 serviceList has an editCategory method who receives the id of the category when a user clicks on the button.
 editCategory( id: string ) {

// I pass the action name to show or hide the child component in the parent component html
// Example:
// <app-serviceupdate *ngIf="action === 'update'" [category]="['category']"  [action]="action" // ></app-serviceupdate>

    this.action = 'update';

    for (let i = 0; i < this.categories.length; ++i) {
      if (this.categories[i]._id === id) {
            this.category = this.categories[i];
        }
    }

    this.service.setCurrentCategory( this.category );
    this.router.navigateByUrl(`/service/update`);
  }

5 Now the category is a property of the shared service component (        this.service.setCurrentCategory( this.category );), and this is working fine, when I run the update form I can see the information there if I call the this.service.getCurrentCategory() (not always working good), but is it not there any other better approach in order to pass a property value between sibling components?
For some reason, sometimes when I try to edit a category (when render the reactive form) I get this error (I think is something related with the "lifecicle":
categoryComponent.html:9 ERROR TypeError: Cannot read property 'name' of undefined
    at categoryupdateComponent.buildForm (serviceupdate.component.ts:72)
    at categoryupdateComponent.ngOnInit (serviceupdate.component.ts:39)
    at checkAndUpdateDirectiveInline (core.js:31910)
    at checkAndUpdateNodeInline (core.js:44367)
    at checkAndUpdateNode (core.js:44306)
    at debugCheckAndUpdateNode (core.js:45328)
    at debugCheckDirectivesFn (core.js:45271)

Many thanks

A: The problem with your approach is that the if user refreshes the page, the category set by this.service.setCurrentCategory or the current "action" will be lost.
A better approach is define your routes as:
{ path: 'service', component: CategoryComponent, children: [
    { path:'update/:id', component: EditCategoryComponent }
    { path:'create', component: CreateCategoryComponent },
    { path:'list', component: ListCategoriesComponent },
 ]}

In this case in your parent component you don't need to reference the child components in template HTML. Instead just put a router-outlet and Angular will take care of loading your child component in the outlet based on the current URL.
<router-outlet></router-outlet>

Also there is no need to set "action" variable. Since the current action is determined by your route (which as mentioned previously is handled by angular).
Your navigation code can simple become.
this.router.navigateByUrl(`/service/update/${id}`);

Note the :id part of the edit route, will be matched by your category id in your EditCategoryComponent. So the id becomes a part of the route/URL.
export class EditCategoryComponent implements OnInit {
    public category: Category;
    constructor(
        private readonly route: ActivatedRoute,
        private readonly service: CategoriesService,
    ) {
    }
    ngOnInit() {
        this.route.paramsMap.pipe(
            switchMap((params) => this.service.getCategoryById(params.get('id')))
        ).subscribe((category) => {
             this.category = category;
        });
    }
}


text:
Q: Как упаковать риг в base fk? У меня есть сложный риг.
И я хочу упаковать его в базовый fk риг
Примерно как здесь video
Как я могу это сделать? Может ли кто нибудь дать туториал по этой теме или просто объяснить мне сейчас?
Я еще не разу не работал с код в блендере поэтому можете объяснить как можно проще.
Или просто дайте аддон который упакует риг за меня.

A: На видео показывается аддон rigify. Он идет вместе с блендером, его нужно просто активировать в настройках на вкладке аддоны


text:
Q: hostgator - PHP - MYSQL cannot connect I have a comman problem with a non-comman situation.
When I try to connect to mysql server hosted in HOSTGATOR servers I am getting this error:
Could not connect to database. SQLSTATE[HY000] [2000] mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication. Please use an administration tool to reset your password with the command SET PASSWORD = PASSWORD('your_existing_password'). This will store a new, and more secure, hash value in mysql.user. If this user is used in other scripts executed by PHP 5.2 or earlier you might need to remove the old-passwords flag from your my.cnf file.

The sollution is very simple and detials in here :
http://www.phpro.org/articles/Database-Connection-Failed-Mysqlnd-Cannot-Connect-To-MySQL.html
But....
HostGator doen't want to change the "my.cnf" file!
And most of the queries on this tutorial are denied because of my privilages.
Is there any other solution out there I am missing?
Thank you!

A: See Hostgator  help
The following code uses PDO for connection .
$DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password);
  $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  //SELECT,INSERT queries here

}
catch(PDOException $e) {
    echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
    file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]'). $e->getMessage()."\r\n", FILE_APPEND);
}
// close the connection
$DBH = null;
?>


text:
Q: FAMES in case of Dynamic Time Warping I found this paper Using Pivots to Speed-Up k-Medoids Clustering in which authors explain how to use triangular geometry and cosine law to speed up search of new medoids in case of K-medoids.
My question is - can I use this approach if I'm using Dynamic Time Warping as distance measure? Or some similar measure (for example Euclidean distance that takes into count only features that exist in both vectors, when calculating distance between them)?
Or it can be used only in the case of Euclidean distance?
Short clarification about Dynamic Time Warping:

*

*Dynamic Time Warping finds optimal alignment between two signals that could be skewed, shifted, in certain manner

*Signals being compared may have different length

*It does that by creating a matrix that allows to repeat values from one of the signals certain number of times, to find the optimal alignment of signals

*When used as a distance measure you specify operation on two features of a signal (for example, distance of two components of vector could be (a[i] - b[i])^2)

This is explanation from top of my head, it should be more clearer from the link I specified.
So, if we have two vectors (signals) like
A = 1, 1, 1, 2, 2, 3
B = 1,2,3
D(A,B) = 0, because 1 will be repeated three times and 2 will be repeated two times in vector B.

A: The paper below does K-means for DTW. While non-trivial, medoids are defined under DTW.
However, if speed-up is important under DTW, you will get more speed-up by using constrained DTW, and with a careful (iterative, not recursive) implementation of DTW.
http://www.cs.ucr.edu/~eamonn/ICDM_2014_DTW_average.pdf


text:
Q: how the values gets passed in this nested function example Learning Javascript from here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
I understand these points

*

*You can nest a function within a function

*The inner function can be accessed only from statements in the outer
function. [ The nested (inner) function is private to its containing
(outer) function. It also forms a closure ]

*The inner function forms a closure: The inner function can use the
arguments and variables of the outer function, while the outer
function cannot use the arguments and variables of the inner
function.

However I couldn't understand how the second value actually goes in all the way to the inner function as-if it was passed as a parameter to inner function?
function outside(y) {
    console.log('y is ' + y);

    function inside(x) {
        console.log('x is ' + x);
        return x+y;
    }

    return inside;
}

var a = outside(3);
//console.log(a);  // this is easy to understand

/* output:

y is 3
ƒ inside(x) {
     console.log('x is ' + x);
     return x+y;
 }
*/

var b = a(2); // Not able to clearly understand how 2 is interpreted as parameter to nested function.
              // Is this bcoz a function was returned earlier and now we passed 2 to that function??
console.log(b);

/*  output
y is 3
x is 2
5
*/

console.log('--------------');
var c = outside(3)(2); // How is 3 passed as outer function paramter and 2 passed as inner function parameter?
console.log('---------');
console.log(c);

/* output
y is 3
x is 2
5
--------------
y is 3
x is 2
---------
5
*/

EDIT-1:
Thanks a lot all who helped, understood the concepts and wrote this which works as expected.
function outside(y) {
    console.log('y is ' + y);
    function inside(x) {
        console.log('x is ' + x);
        function innermost(z) {
            console.log('z is ' + z);
            return x+y+z;
        }
        return innermost;
    }
    return inside;
}
outside(3)(2)(1);

/* output
y is 3
x is 2
z is 1
6
*/

EDIT-2:
Another way of writing the function to meet the above objective mentioned in EDIT-1.
function A(x) {
  function B(y) {
    function C(z) {
      console.log(x + y + z);
    }
    C(3);
  }
  B(2);
}
A(1); // logs 6 (1 + 2 + 3)

In this example, C accesses B's y and A's x. This can be done because:

*

*B forms a closure including A, i.e. B can access A's arguments and
variables.

*C forms a closure including B.

*Because B's closure includes A, C's closure includes A, C can access
both B and A's arguments and variables. In other words, C chains the
scopes of B and A in that order.

The reverse, however, is not true.

*

*A cannot access C, because A cannot access any argument or variable
of B, which C is a variable of. Thus, C remains private to only B.

A: The result of outside(someValue) call is a function. So to call the result (inner) function you need to call outside function twice. One time to get the inner function outside(3) and once again to call it outside(3)(4).
let innerFunc = outside(3) // here you get the inside function as result
innerFunc(4) // call it

Wich is the same as:
outside(3)(4)

Some more info:
outside(3) // this calls the outside function and returns the inside function
outside(3)(4) // this calls the outside function returns the inside
//function as result of first call and calls the inside function with (4)

A: A lot like this, I'd assume.
function outside(y) {
    console.log('y is ' + y);
    function inside(x) {
        console.log('x is ' + x);
        function inide(z) {
            console.log('z is ' + z);
            return y+z;
        }
        return x+y, inide;
    }
    return inside;
}
outside(3)(2)(1);


text:
Q: Php conexao com SQL Server Como posso conectar o o php com sqlserver (pdo)? Parece simples, mas não estou conseguindo...
Já habilitei o driver tudo ok
Em anexo tem o nome do servidor, vou rodar no local ...

A: Você tem duas opções para tentar:
$pdo = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");

ou
$pdo = new PDO( "sqlsrv:server=$serverName ; Database=$dbname", "$username", "$pw");

Depende o driver que você instalou no PHP.
[Editado] Um exemplo de select com PDO
//retornar o resultset
$sql = 'Select * from products';
$result = $pdo->query($sql);

// imprimir resultados um a um
while ($campos = $result->fetch()){
    echo $campos['ProductID']. ' - '.$campos['ProductName'].'<br />';
}

A: Boa noite.
Caso não tenha as extensões sqlsrv e pdo_sqlsrv, o ideal é tentar com odbc.
Veja como fica:
$pdo = new \PDO ("odbc:Driver={SQL Server Native Client 11.0};Server=localhost;Database=catalogName;app=appName;WISD={$_SERVER['REMOTE_HOST']}",$sqlUser,$sqlPass);

Qual versão do PHP está utilizando?
Consegue enviar um print do phpinfo na área da PDO similiar à imagem abaixo?
Veja se na configuração do PHP está habilitado pdo_sqlsrv, pois me parece que este driver você já possui.


text:
Q: align left to the center box in css I got something like this:

 Product name

 some options

H3 is center aligned, is it possible to align item-options to left edge of h3?
So would like this: (product name and options have different lenght)

_____product name long (text align center)_____
     product options

if I put text align on both it will look like this:

_____product name long (text align center)_____
              product options

A: You could wrap the header and dl in a wrapper div and center it like this:

dl, dt, dd {
  margin: 0
  }

.wrap {

text-align: center;
  border: 1px solid #000;
}

.container {
  display: inline-block;
}
dl {

text-align: left;
}

Header with a long string

Title

Definition


text:
Q: How to make the lower value in bar graph visible? I am trying to read values from a spreadsheet and plot them via MATLAB. However, when the values of the first dataset get lower, it becomes hidden at the back, as seen for the values 80 and 100 below:

I am thinking maybe it's because I am plotting two different bar plots on the same points. How can I to bring the shorter bars to the front?
Below is my code:
%{
Data example:

Arrival_rate   per_A        per_B

30             46.361       44.892
60             30.585       25.602
80             20.674       23.352
100            16.209       18.597
%}

fig = figure('DefaultAxesFontSize',18);
set(0,'DefaultAxesFontName','Times New Roman');

arrival_rate = xlsread('Graph_data', 'Sheet2', 'H1:H6');
pe_a = xlsread('Graph_data', 'Sheet2', 'I1:I6');
pe_b = xlsread('Graph_data', 'Sheet2', 'J1:J6');
line = xlsread('Graph_data', 'Sheet2', 'K1:K6');

x1 = 30:1:100;
y1 = [46.361 44.892; 30.585 25.602; 16.209  18.597];
x2 = 30:1:100;
y2 = interp1(arrival_rate,line,x2,'pchip') ;

hold on

ylabel('% error in VM_A')

% bar(arrival_rate,y,  0.2, 'b', 'DisplayName', 'Error in A')
bar(arrival_rate,pe_a ,.1 , 'stacked','DisplayName', 'Error in A')
bar(arrival_rate,pe_b, .1 , 'stacked', 'DisplayName', 'Error in B')

% bar(arrival_rate, y1, 0.2, 'hist')

plot(x2,y2,'k.','HandleVisibility','off','LineWidth',1)
plot(arrival_rate,line,'k*', 'HandleVisibility','off','LineWidth',1)

hold off

xlabel('\lambda (Clients/Hour) ')
ylabel('Error (%)')
%  title('Effect of Probability of a VM Type on awt of Clients')
legend show
legend('Location','Northeast')
set(gca,'XTick',(0:10:110))
set(gca,'YTick',(0:5:50))

set(gcf, 'PaperUnits', 'normalized')
set(gcf, 'PaperOrientation', 'landscape')
set(gcf, 'PaperPosition', [0 0 1 1])

A: From what I understand, for the case where the blue bars are shorted than the red, they should appear in the front. Unfortunately, MATLAB does not make it easy for you to control each bar individually, which should hint that this is not something they intend for to do. (In other words - it would be a good idea to consider other ways of visualizing the data in a meaningful way.)
I'd suggest you to make the width of the bars slightly different, so that you could easily tell what's going on at a glance:
D = [...
30             46.361       44.892
60             30.585       25.602
80             20.674       23.352
100            16.209       18.597];

arrival_rate = D(:,1);
pe_a = D(:,2);
pe_b = D(:,3);

fig = figure('DefaultAxesFontSize',18);
bar(arrival_rate,pe_a ,.15 , 'stacked','DisplayName', 'Error in A'); hold on;
bar(arrival_rate,pe_b, .1 , 'stacked', 'DisplayName', 'Error in B');

which gives:

Now, if you insist on having it your way, I can think of asolution, but it would be increasingly difficult to extend to more than 2 groups. In short you make plots in this order and then they'll appear correctly:

*

*Blue (optionally: only where blue is taller).

*Red.

*Blue over red (when red is taller).

fig = figure('DefaultAxesFontSize',18);

bar(arrival_rate,pe_a, .1 , 'DisplayName', 'Error in A'); hold on;
bar(arrival_rate,pe_b, .1 , 'DisplayName', 'Error in B');
bar(arrival_rate(is_blue_smaller), pe_a(is_blue_smaller), .1 , ...
  'FaceColor', lines(1), 'HandleVisibility','off');

which yields:


text:
Q: Changing the Class of Multiple Elements OnResize using JQuery Ok I am entirely new to jQuery, and it looks like I should have been getting into this all much sooner coz it certainly offers a whole bunch of options that are truly awesome. Now.. I want to do the following:
When a user resizes a page, I want to be able to set the ClassName for a variety of elements at the same time. So if the width is between range A and B, set class 1, between B and C, set class 2, and so on. So far I have this:

<InPut Type='Text' ID='ZVal'>
<InPut Type='Text' ID='CVal'>

Name:
<InPut class='zahbib' Type='Text' Style='Width:100%'>

Email:
<InPut class='zahbib' Type='Text' Style='Width:100%'>

Phone:
<Select class='zahbib' Style='Width:100%'></Select>

I have gotten most of this (especially the jquery stuff) from other Stack Overflow posts, but changing the class only happens ONCE and then it does not change again depending on the width. It just seems to complete the task 1 time, and not for the text fields either, I think.
So what am I doing wrong? The sClass value works OK, updates the debug text field, as does the width readout. I know it can return slightly different values depending on browser but that's OK, it will not need it to be super-precise.
Many thanks and I am hoping to start getting into this jQuery thing more thoroughly :)
W
The CSS I am now using is:
@media screen and (min-width: 1px) and (max-width: 460px){
zeb{font-size:12px}
zah{font-size:12px}
input.text{font-size:12px}
}
@media screen and (min-width: 461px) and (max-width: 770px){
zeb{font-size:16px}
zah{font-size:16px}
input.text{font-size:12px}
}
@media screen and (min-width: 771px) and (max-width: 1920px){
zeb{font-size:22px}
zah{font-size:22px}
input{font-size:12px}
}

zeb and zah are where you normally put div. I just would prefer not to use DIV because there may be some divs that I do not want affected. This way, I can simply make my own tags at will, and this works perfectly fine. (so instead of

  I type <zah> and </zah>) They work. It's just the input fields that wont budge. Thank You :)
Ok this is the table:

<zeb>Name:</zeb>
<input Type='Text' Style='Width:100%'>

<zah>Email:</zah>
<input Type='Text' Style='Width:100%'>

<zah>Phone:</zah>
<Select Style='Width:100%'></Select>

And as I said, the font size is adjusted fine on the zeb and zah :) Just the input fields won't change as I resize the window. The zeb's and zah's do :)

A: I feel what you are trying to do can be accomplished much more easily using media queries. You can encase your rules in media queries that will ensure the style rules applied depend on the width of the viewport.
So for example, to set the style for all divs when the screen is between 1 and 460 pixels wide, you could use:
@media screen and (min-width: 1px) and (max-width: 460px){
  div {
      color: red;
  }
}

Additionally we could say we want the color to be green when the width is between 461 and 770 pixels:
@media screen and (min-width: 1px) and (max-width: 460px){
  div {
      color: red;
  }
}

@media screen and (min-width: 461px) and (max-width: 770px){
  div {
      color: green;
  }
}

You are using non standard HTML elements. Try using span elements and using IDs to isolate them in CSS:

         Name:

      <input Type="Text" Style="Width:100%" />

         Email:

      <input Type="Text" Style="Width:100%" />

         Phone:

      <Select Style="Width:100%"></Select>

Now you can apply your CSS to all elements with class zeb and zah:
@media screen and min-width 1px and max-width 460px {
    .zeb, .zah, input.text
    {
        font-size:12px;
    }
}

@media screen and min-width 461px and max-width 770px {
    input.text
    {
        font-size:12px;
    }

    .zeb, .zah
    {
        font-size:16px;
    }
}

@media screen and min-width 771px and max-width 1920px {
    input
    {
        font-size:12px;
    }

    .zeb, .zah
    {
        font-size:22px;
    }
}

Notice that I have condensed identical rules by separating selectors with commas.


text:
Q: Parabolas - Which values of $x$ will make it negative? I have always seen a question about parabolas asking: for which values of $x$ is the given function negative.
$$y= x^2-6x+5$$
What does that mean?

A: What it is asking you is, "What values of $x$ will make $y$ less than $0$?" All you need to do is to solve the inequality $x^2-6x+5<0$.
$$x^2-6x+5<0$$
$$(x-1)(x-5)<0$$
The roots of this function are $1$ and $5$. The values of $x$ less than $0$ will be between these two roots (not including them). Therefore:
$$1<x<5$$
So, any value of $x$ between $1$ and $5$, not including the two numbers, will make $y$ less than $0$, in other words, negative.

Here is what the function looks like when graphed:

As you can see, the values of $x$ that make the curve negative, or go below $0$, are between $1$ and $5$. This is written as $1<x<5$.
I hope I helped you.

A: A function is negative for those values of x for which the graph of the function is below the y-axis.
$$y<0$$
$$x^2 - 6x + 5 < 0$$
$$(x-5)(x-1)<0$$
$$\implies 1<x<5$$
So for $1<x<5$, the function will be negative.


text:
Q: DataGridView 'OnRowValidating(DataGridViewCellCancelEventArgs e)' method is not calling for the 1st row I am trying to disable row selection in DataGridView in winforms. I used below code and its working as expected other than 1st row.
        protected override void OnRowValidating(DataGridViewCellCancelEventArgs e)
        {
            e.Cancel = true;
        }

For 1st row, this method is not calling and I am able to select the row.
Can anyone have a solution for this issue
I would like to disable all kind of selections (Row, column or cell selection).
I cannot use IsEnabled = false because horizontal/vertical scrolling need to be retained.

A:
I would like to disable all kind of selections (Row, column or cell
selection). I cannot use Enabled = false because horizontal/vertical
scrolling need to be retained.

To completely disable any selection in a DataGridView, you can set CurrentCell = null when a user changes Row or Cell, interacting with the Control.
This of course also disables any editing of the Cells.
It's like an enforced read-only mode; the default ReadOnly Property doesn't prevent a visible selection.
The grid can scroll and also clicking the Columns' headers allows to order the data.
Setting CurrentCell = null prevents all selections except when dragging the Mouse Pointer, which highlight Rows.
This happens only when MultiSelect = true, when set to false, no selection can be performed dragging the Mouse.
Suggested edit 1 (no selection allowed, no edit allowed, sorting allowed):

*

*Added a SelectionEnabled public (modify as required) Property so you can toggle this state.

*OnSelectionChanged is overridden to apply the state (you must call base before you set CurrentCell = null).

public class DataGridViewEx : DataGridView {

    private bool m_SelectionEnabled = true;
    private bool multiSelectCachedState = false;

    public DataGridViewEx() { }

    public bool SelectionEnabled {
        get => m_SelectionEnabled;
        set {
            if (m_SelectionEnabled != value) {
                m_SelectionEnabled = value;
                if (!m_SelectionEnabled) {
                    multiSelectCachedState = MultiSelect;
                    MultiSelect = false;
                    ClearSelection();
                }
                else {
                    MultiSelect = multiSelectCachedState;
                }
            }
        }
    }

    protected override void OnHandleCreated(EventArgs e)
    {
        base.OnHandleCreated(e);
        multiSelectCachedState = MultiSelect;
    }

    protected override void OnSelectionChanged(EventArgs e)
    {
        base.OnSelectionChanged(e);
        // Prevents Cell edit
        if (!m_SelectionEnabled) CurrentCell = null;
    }
}

Suggested edit 2 (no selection allowed, Cell edit allowed, sorting allowed):
As you can see in the .Net Source Code about CurrentCell, setting this property to null causes a call to ClearSelection(), but based on some conditions.
Calling ClearSelection() directly, causes a call to SetSelectedCellCore() (suspends bulk paint, clears the selection and invalidates Columns and Rows in the end), which doesn't prevent editing.
The code is, give or take, the same:
public bool SelectionEnabled {
    get => m_SelectionEnabled;
    set {
        if (m_SelectionEnabled != value) {
            m_SelectionEnabled = value;
            if (!m_SelectionEnabled) ClearSelection();
        }
    }
}

protected override void OnSelectionChanged(EventArgs e)
{
    base.OnSelectionChanged(e);
    // Does not prevent Cell edit
    if (!m_SelectionEnabled) ClearSelection();
}


text:
Q: Python 3.7 logging problem not showing in output I know this question been asked twice now in StackOverflow, but nobody answers yet the question.
Here's my code:
logging.basicConfig(filename="logfile.log", filemode='w',
         format='%(asctime)s:%(levelname)s:%(message)s', datefmt='%m/%d/%Y %H:%M:%S')
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical error message')

Output console is EMPTY. Only the logfile.log has the log strings. But when I remove the filename attribute, it started showing the console. I want to show in console and write in my log file. What do I miss? Please answer with code. I read the documentation twice or thrice already. Thank you.

A: Just get a handle to the logger and add the StreamHandler and the FileHandler
import logging

logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")
logger = logging.getLogger()

fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)

consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)


text:
Q: Equivalence of two PDAs I want to show that if $P$ is a PDA, then there exists a PDA $P_2$ with only two stack symbols, such that $L(P) = L(P_2)$.
As I want only two stack symbols for $P_2$, it seems intuitive to encode in binary the stack symbols of $P$. However, I don't know how to formalize this proof, or write the proof altogether. Can anyone help me out?

A: A binary coding seems to be promising, however the method of encoding needs to be precise. When you use multiple places in the stack to represent a single stack move, your automaton needs to know when one symbol ends and another begins. There are two ways that come to mind to do this. They are fixed length codes and prefix codes. Basically they ensure there is no ambiguity in your encoding.
To actually prove this:
-Assume you have an encoding for your stack alphabet(G). For example, let's say G = {a,b,c,d} and G' = {0,1}. We'll encode G as follows: a = 00, b = 01, c = 10, d = 11.
-At each node in the graph representation of P, put in two intermediary nodes. One that takes a '0' off the stack, and one that takes a '1' off the stack. From these nodes take off the correct symbol of the stack to complete the transition. The first transition should consume epsilon as input from your word. You can do a similar thing to push symbols onto the stack.
There will be wrinkles when at a node q, you'd pop if you saw an 'a', but push a c if you saw a b, but you should be able to work that out because you know the latest relevant steps you've taken. (In this case, edge that pops a 0, if it sees a 1, push a zero, push a 0, push a 1). Also some stuff will be backwards so be careful.


text:
Q: converting numeric arrays into list and savig in CSV in R I am trying to store two numerical arrays in an unusal form, e.g. c('[1;2;3]','[4;5;6]','[24;25;26]')
I need them in a CSV in single cells, like here

So far I tried this:
DF
ID time Y
1  3    23
1  4    24
1  5    20
2  2    12
2  8    15
3  2    19
3  3    23
3  5    21
3  6    32

timeList = list()
yList = list()
for (i in 1:3) {
  timeList[i] = DF$time
  yList[i] = DF$Y
}

longTimeList = list(timeList)
longYList = list(yList)

DF <- data.frame(ID = c(1,2,3),
             P1 = longTimeList,
             P2 = longYList)

so the example DF woul read
 newDF <- data.frame(ID = c(1,2,3),
                 P1 = c('[3;4;5]','[2;8]','[2;3;5;6]'),
                 P2 = c('[23,24,20]','[12;15]','[19;23;21;32]'))

which should be stored in a CSV file to give something like that shown above.

A: I believe aggregate could help you
> aggregate(. ~ ID, DF, function(x) sprintf("[%s]", paste0(x, collapse = ";")))
  ID      time             Y
1  1   [3;4;5]    [23;24;20]
2  2     [2;8]       [12;15]
3  3 [2;3;5;6] [19;23;21;32]

A: using tidyverse
df <-
  structure(list(
    ID = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L),
    time = c(3L,
             4L, 5L, 2L, 8L, 2L, 3L, 5L, 6L),
    Y = c(23L, 24L, 20L, 12L, 15L,
          19L, 23L, 21L, 32L)
  ),
  class = "data.frame",
  row.names = c(NA,
                -9L))

library(tidyverse)
df %>%
  group_by(ID) %>%
  summarise(across(everything(), ~paste0(.x, collapse = ";"))) %>%
  mutate(across(c(time, Y), ~paste0("[", .x, "]")))
#> # A tibble: 3 x 3
#>      ID time      Y
#>   <int> <chr>     <chr>
#> 1     1 [3;4;5]   [23;24;20]
#> 2     2 [2;8]     [12;15]
#> 3     3 [2;3;5;6] [19;23;21;32]

Created on 2021-06-08 by the reprex package (v2.0.0)

A: An option with glue
library(dplyr)
library(glue)
library(stringr)
df %>%
    group_by(ID) %>%
    summarise(across(everything(), function(x)
      glue("[{str_c(x, collapse = ';')}]")))
# A tibble: 3 x 3
#     ID time      Y
#  <int> <glue>    <glue>
#1     1 [3;4;5]   [23;24;20]
#2     2 [2;8]     [12;15]
#3     3 [2;3;5;6] [19;23;21;32]