Q: How to make a tab control with bootstrap in asp.net Here I am implementing bootstrap tab control in asp.net application.
1) On click on next i want to go to next tab.
I want to make tab control working by clicking on tabs of tab control to go to next tab or by clicking on next button.
<form id="form1" runat="server">

Personal Information

Professional Information

User Account Infromation

                                *First Name :

                                <asp:TextBox ID="txtName" runat="server" placeholder="First Name"</asp:TextBox>

                                <asp:Button ID="btnNext" Width="150" runat="server" Text="NEXT" />

</form>

Image of Tab control:

A: Create a button after your content divs and call function on this button
<input type="button" value="Next" onclick="ShowNextTab();" />

function ShowNextTab() {
  if ($('.nav-tabs > .active').next('li').length == 0) //If you want to select first tab when last tab is reached
        $('.nav-tabs > li').first().find('a').trigger('click');
    else
        $('.nav-tabs > .active').next('li').find('a').trigger('click');
}

Below is a complete solution
HTML
<form id="form1" runat="server">

Personal Information

Professional Information

User Account Infromation

                                *First Name :

                                <asp:TextBox ID="txtName" runat="server" placeholder="First Name"></asp:TextBox>//close tag is missing

                                <asp:Button ID="btnNext" Width="150" runat="server"  Text="NEXT" />

            <input type="button" value="Next" onclick="ShowNextTab();" />
            <input type="button" value="Prev" onclick="ShowPrevTab();" />

</form>

JavaScript
function ShowNextTab() {
        $('.nav-tabs > .active').next('li').find('a').trigger('click');
    }
    function ShowPrevTab() {
        $('.nav-tabs > .active').prev('li').find('a').trigger('click');
    }


Q: How can Amazon S3 bucket permissions be set so every time I save a file read permissions stay public? I'm using the Coda app at add, edit, and save files on my S3 bucket.
The bucket has static web hosting enabled.
Every time I upload or save a file, the permissions automatically change to restrict the "world" from reading the file.
How can Amazon S3 bucket permissions be set so every time I save a file read permissions stay public?

A: Add a bucket wide policy rather than on each file:
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "AllowPublicRead",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": [
        "s3:GetObject"
      ],
      "Resource": [
        "arn:aws:s3:::my-brand-new-bucket/*"
      ]
    }
  ]
}

http://s3browser.com/working-with-amazon-s3-bucket-policies.php

A: Instead of adding a new bucket policy, I fixed my problem by aliasing a domain name to my bucket. When I access bucket files through the alias, I'm seeing no permission errors.


Q: Operator overloading adding two objects error I have no idea why this code should work, but tell me what to do if i want to add two objects
together. please. while you are trying to answer please be more noob specific
sorry for my bad english, I am an Indian, here is my code.
#include<iostream>

using namespace std;

class time
{
private:
    int sec;
    int mint;
    int hours;
public:
    int Inputsec;
    int Inputmint;
    int Inputhours;
time(int Inputsec, int Inputmint, int Inputhours):sec(Inputsec), mint(Inputmint), hours(Inputhours){};
time operator+(time Inputobj)
{
    time blah (sec+Inputsec,mint+Inputmint,hours+Inputhours);
    return blah;
}

void DisplayCurrentTime()
{
    cout << "The Current Time Is"<<endl<< hours<<" hours"<<endl<<mint<<"minutes"<<endl<<sec<<"seconds"<<endl;
}
};

int main()
{
time now(11,13,3);
time after(13,31,11);
time then(now+after);
then.DisplayCurrentTime();
}

code is working fine but it is giving me horrible output.
Where is my mistake?

A: Your addition operator is using unitinitialized member Inputsec, Inputmint and Inputhours variables. It should look like this:
time operator+(time Inputobj)
{
    return time(sec+InputObj.sec, mint+InputObj.mint, hours+InputObj.hours);
}

or
time operator+(time Inputobj)
{
    InputObj.sec += sec;
    InputObj.mint += mint;
    InputObj.hours += hours;
    return InputObj;
}

Or, even better, implement time& operator+=(const time& rhs); and use it in a non-member addition operator:
time operator+(time lhs, const time& rhs)
{
  return lhs += rhs;
}

You have two sets of member variables representing the same thing. You do not need this duplication.
One final remark: there is something called std::time in header<ctime>. Having a class called time, and using namespace std is asking for trouble. You should avoid both if possible (avoiding the second is definitely possible).

A: You should rewrite your operator+ at least as follows:
time operator+(time Inputobj)
{
    time blah time(sec+InputObj.sec, mint+InputObj.mint, hours+InputObj.hours);
    return blah;
}

also I think you should use the % operator for getting the correct time results:
time operator+(time Inputobj){
    int s = (sec+InputObj.sec) % 60;
    int m = (sec+InputObj.sec) / 60 + (mint+InputObj.mint) % 60;
    int h = (mint+InputObj.mint) / 60 + (hours+InputObj.hours) % 24;
    return time(s,m,h);
}

A: Your operator overloading function is using uninitialized variables. Initialize variables inputsec, inputmint, Inputhours in your constructor.
Moreover, try this:
time operator+ (time Inputobj)
{
   time blah (sec+Inputobj.sec, mint+Inputobj.mint, hours+Inputobj.hours);
   return blah;
}

A: Your error is your publics members with the same name as the parameter constructor, which are unitialized.
Try this :
#include <iostream>
using namespace std;

class time
{
private:
    int sec;
    int mint;
    int hours;
public:
time(int Inputsec, int Inputmint, int Inputhours):sec(Inputsec), mint(Inputmint), hours(Inputhours)
{
};

time operator+(time Inputobj)
{
    time blah (sec+Inputobj.sec, mint+Inputobj.mint, hours+Inputobj.hours);
    return blah;
}

void DisplayCurrentTime()
{
    cout << "The Current Time Is"<<endl<< hours<<" hours"<<endl<<mint<<"minutes"<<endl<<sec<<"seconds"<<endl;
}
};

int main()
{
time now(11,13,3);
time after(13,31,11);
time then(now+after);
then.DisplayCurrentTime();
}


Q: Concatenate backslash on python I'm new to python so forgive me if this sounds simple. I want to join a few variables to produce a path. Like this:
AAAABBBBCCCC\2\2014_04\2014_04_01.csv

Id + '\' + TypeOfMachine + '\' + year + '_' + month + '\' + year + '_' + month + '_' + day + '.csv'

How do I concatenate this? I putted single quotes around underline or backslash, but stackoverflow omits/modifies them.

A: Normally, you'd double the backslash:
'\\'

Use os.path.join() to join directory and filename elements, and use string formatting for the rest:
os.path.join(Id, TypeOfMachine, '{}_{}'.format(year, month),
             '{}_{}_{}.csv'.format(year, month, day))

and let Python take care of using the correct directory separator for your platform for you. This has the advantage that your code becomes portable; it'll work on an OS other than Windows as well.
By using string formatting, you also take care of any non-string arguments; if year, month and day are integers, for example.

A: You can simply call the character by its ASCII code.
(I'm using Python 3.7).
Example:
In this case, the ASCII code is 92, you can use Python's chr() function to call the character

In this website you can find a list of ASCII codes for more printable characters.
The code used above:
delimiter = chr(92)

FileName = 'Id' + delimiter + 'TypeOfMachine' + delimiter + 'year' + '_' + 'month' + delimiter + 'year' + '_' + 'month' + '_' + 'day' + '.csv'

print(FileName)

Hope it helps.

A: A backslash is commonly used to escape special strings. For example:
>>> print "hi\nbye"
hi
bye

Telling Python not to count slashes as special is usually as easy as using a "raw" string, which can be written as a string literal by preceding the string with the letter 'r'.
>>> print r"hi\nbye"
hi\nbye

Even a raw string, however, cannot end with an odd number of backslashes. This makes string concatenation tough.
>>> print "hi" + r"\" + "bye"
File "<stdin>", line 1
print "hi" + r"\" + "bye"
                       ^
SyntaxError: invalid syntax

There are several ways to work around this. The easiest is using string formatting:
>>> print r'{}\{}'.format('hi', 'bye')
hi\bye

Another way is to use a double-backslash in a regular string to escape the second backslash with the first:
>>> print 'hi' + '\\' + 'bye'
hi\bye

But all of this assumes you're facing a legitimate need to use backslashes. If all you're trying to do is construct Windows path expressions, just use os.path.join.

A: You should use os.path.join to construct the path.
e.g:
import os
path = os.path.join(Id, TypeOfMachine, year + '_' + month, year + '_' + month + '_' + day + '.csv')

or if you insist on using backslashes, you need to escape them: as, so '\\'

A: Without importing os.path module you could simply do:
 my_path = '\\'.join([Id,TypeOfMachine, year + '_' + month, year + '_' + month + '_' + day + '.csv'])

A: You can also use normal strings like:
Id + '/' + TypeOfMachine + '/' + year + '_' + month + '/' + year + '_' + month + '_' + day + '.csv'


Q: Undef values from CSV file giving undesirable result I am having a CSV file Sample.csv like below named
    Name,Memory,Encoding,Extra 1,Extra 2
    ,d,,h,b
    FUSE_1,36,30,37,15
    FUSE_1,36,28,36,31
    Name1,1TB,00000001,30,010
    Name1,1TB,00000010,52,001

I am parsing this file and want to retrieve some values from the file. What I want is Only those names from the first row for which corresponding value is present in 2nd row. Means I want to get Memory,Extra 1 and Extra 2 as corresponding value is present in 2nd row (d,h and b). For which What I am doing is I am storing the values of both the rows in separate arrays and then I am traversing the array for 2nd row and the indexes corresponding to which value is present in this that corresponding index value I am taking from 1st array and storing it in second array.The code which I am using is-
my $iniFilename = "Sample.csv";
open(my $fi,'<',$iniFilename) or die "Can't open $iniFilename";
while(my $row=<$fi>){
if($row_no == 0)
{
    chomp($row);
    $row=~ s/\A\s+//g;
    $row=~s/\R//g;
    if(length($row))
    {
        @fuse_name_initial = split(/,/,$row);
    }
}
    elsif($row_no == 1)
    {
        chomp($row);
        $row=~ s/\A\s+//g;
        $row=~s/\R//g;
        if(length($row)){
        @fuse_data_type_initial =split(/,/,$row);
        }
    }
    $row_no++;
}
my $trace=0;
foreach (@fuse_data_type_initial)
{
    if($_)
    {
        if($fuse_name_initial[$trace] !~ /Extra Fuse/){
            push @column_no_for_fuse_value,($trace+1);
            push @fuse_names , $fuse_name_initial[$trace];
            push @fuse_data_type ,$_ ;
            $trace++;
        }
        else{
            push @extra_fuse_data_type ,$_ ;
            $trace++;
        }
    }
 }

Now I am expecting the @fuse_names array to reflect names "Memory" as "Extra Fuse1" and "Extra Fuse2" is filtered out using regex but instead I am getting very bad result. I am getting three elements in the @fuse_names- Name,Memory,Encoding . Can Somebody please tell me What I am doing wrong in the code??

EDIT : When I am changing 2nd row to ",d,,," and following @Dada method then it should only take "Memory" from 1st row but instead it is taking everything after memory i.e Memory,Encoding,Extra Fuse1,Extra Fuse2

And then I printed the length of @filter array.It should ideally be 5 with 1 defined value and 4 other undef value but strangely the length of @filter came out to be 2. It is really Confusing.

A: Your code is pretty bad for several reasons. Instead of trying to fix them, which would leave you with a bad-but-working code, I'm going to point them out, and suggest a better way.

*

*You first while(my $row = <$fi>) iterates over the whole file when you are only interested in the first two rows. You should just use <$fi> twice to read the first two lines:
my $headers = <$fi>;
my $filters = <$fi>;

*You shouldn't duplicate code. In particular, you wrote twice
chomp($row);
$row=~ s/\A\s+//g;
$row=~s/\R//g;

Whereas you could have put that only once at the beginning of the while.

*Same thing for $trace++: you want it done at every iteration of your foreach loop; there is no reason to put it in at the end of the if and at the end of the else.

*always use strict and use warnings.

Here is what I suggest instead:
use strict;  # Always use strict and warnings!
use warnings;

my $iniFilename = "Sample.csv";
open(my $fi,'<',$iniFilename) or die "Can't open $iniFilename";

my @headers = split ',', <$fi> =~ s/\A\s+|\s+\Z//gr, -1;
my @filter  = split ',', <$fi> =~ s/\A\s+|\s+\Z//gr, -1;
for my $i (0 .. $#filter) {
    $headers[$i] = undef if !$filter[$i] || $filter[$i] eq "" ;
}
# @headers now contains (undef, "Memory", undef, "Extra 1", "Extra 2")

If you need the index of @headers that are not undef:
my @headers_indices = grep { defined $headers[$_] } 0 .. $#headers;

If you need just the names of the non-undef headers:
my @non_undef_headers = grep { defined $_ } @headers;

Finally, since you are parsing CSV files, you might want to use a CSV parser (Text::CSV_XS for example), rather than split /,/. (the latter will misbehave with quoted fields containing commas or newlines (and probably has other issues that I'm not thinking about right now))


Q: Canvas Responsive - Fabricjs I trying let the responsive canvas following this topic1 and topic2
I'm trying to let the responsive canvas for all devices.
I know it's possible but I'm having a tough time finding the solution.
Following the two topics above I tried to set the width and height for the max canvas size in javascript. And in the css for each device a different size to canvas view, even changing the CSS display size actual size defined in javascript must remain
I´m using fabric.js

SOLUTION
Note: stack Overflow view considering width 360px because of the preview in the post

  var canvas = this.__canvas = new fabric.StaticCanvas ('c');
  canvas.setHeight(600);
canvas.setWidth(800);

  canvas.setBackgroundImage('http://lorempixel.com/500/500/animals', canvas.renderAll.bind(canvas), { width: 800,height: 600 });

  var text = new fabric.Text('Hello', { left: 100, top: 100, fill: 'blue', });
canvas.add(text);
 #c{
     border:1px solid red;
     top:22px;
     left:0px;
     height: 100%;
     width: 99%;
 }

 @media screen and (min-width: 360px) {
  #c {   -webkit-transform : scale(0.4);
-webkit-transform-origin : 0 0; }
}

@media screen and (min-width: 768px) {
  #c {   -webkit-transform : scale(0.45);
-webkit-transform-origin : 0 0; }
}

@media screen and (min-width: 992px) {
  #c {   -webkit-transform : scale(0.5);
-webkit-transform-origin : 0 0;}
}

@media screen and (min-width: 1200px) {
  #c {   -webkit-transform : scale(0.5);
-webkit-transform-origin : 0 0;}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.js"></script>
<canvas id="c"></canvas>

A: Solution in my question. In topic1 I found it:

X4V1 answered Jun 16 '15 at 20:24
I have found a trick to do that without having to copy the canvas.
  This solution is really close to css zoom property but events are
  handle correctly.
This is an example to display the canvas half its size:
-webkit-transform : scale(0.5);
  -webkit-transform-origin : 0 0;


Q: AngularJS: How to toggle element from controller How can I use the following controller to toggle the content inside li tag?
Right now the content is rendered only after that span is clicked, but it won't hide if I click again the span.
Here's my code:

  {{ folder.name }}

        <input type="checkbox" name="file_map[]" value="{{ file.id }}"  ng-model="file_map[file.id]" ng-click="update_selection(file.id)"/>

        {{ file.name }}

Controller:
scope.get_menu_items = function(folder){
    http.get("/api/folders/" + folder.id).success(function(data){
        folder.folders = data.data.folders;
        folder.files= data.data.files;
    })
}

A: You can simply create a boolean for show/hide and toggle it on your click method like.
scope.get_menu_items = function(folder){
   //if folder.folder exist means we don't need to make $http req again
   if(folder.folders){
      $scope.showFolder = !$scope.showFolder
   }
   else{
      http.get("/api/folders/" + folder.id).success(function(data){
       folder.folders = data.data.folders;
       folder.files= data.data.files;
       $scope.showFolder = true;
      })
   }
}

and add ng-if on your view like.

  {{ folder.name }}

        <input type="checkbox" name="file_map[]" value="{{ file.id }}"  ng-model="file_map[file.id]" ng-click="update_selection(file.id)"/>

        {{ file.name }}

Hope it helps.

A: Add a global variable in controller as scope.
Outside controller, add a variable (for example called: toggleVariable) and assign it to false.
Inside controller put this:
scope.toggleVariable = !scope.toggleVariable;
In HTML, add to ul tag: ng-show="toggleVariable".
Give it a try


Q: Is there a way to run tests prerequisite once and clean up in the end in whole unit test run I'm running series of testcases in multiple files, but I want to run the prereq and cleanup only once through out the run, please let me know is there a way to do it?

A: py.test -> session scoped fixtures and their finalization should help you
You can use conftest.py to code your fixture.


Q: Elasticsearch Geo_point query not returning results I am trying to fetch all the documents within a radius of a particular location (lat,long).
Here's the mapping with location as the geo_point:
{
  "mappings": {
    "_doc": {
      "properties": {
        "color": {
          "type": "long"
        },
        "createdTime": {
          "type": "date"
        },
        "location": {
          "properties": {
            "lat": {
              "type": "float"
            },
            "lon": {
              "type": "float"
            }
          }
        }
      }
    }
  }
}

And here's my query
{
  "aggregations": {
    "weather_agg": {
      "geo_distance": {
        "field": "location",
        "origin": "41.12,-100.77",
        "unit": "km",
        "distance_type": "plane",
        "ranges": [
          {
            "from": 0,
            "to": 100
          }
        ]
      },
      "aggregations": {
        "timerange": {
          "filter": {
            "range": {
              "createdTime": {
                "gte": "now-40h",
                "lte": "now"
              }
            }
          },
          "aggregations": {
            "weather_stats": {
              "stats": {
                "field": "color"
              }
            }
          }
        }
      }
    }
  }
}

I am getting 0 hits for this. My question is whether there's something wrong with the mapping or the query ? We recently migrated to a newer cloud version and there's a possibility that something broke because of that.

A: Instead of mapping lat and long as float you should geo-point mapping


Q: Deserialize from SqlXml to object I have an int value stored in SQL Server as xml type, which is SqlXml when retrieved in C#
The value in database:
<int>1234</int>

How can I deserialize this value to an int with value 1234?

A: Assuming the SqlXml object contains exactly what was mentioned in the question, you might want to use the following helper method. Should work for any type that has been serialized this way, even complex objects.
static T GetValue<T>(SqlXml sqlXml)
{
    T value;

    // using System.Xml;
    using (XmlReader xmlReader = sqlXml.CreateReader())
    {
        // using System.Xml.Serialization;
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        value = (T) xmlSerializer.Deserialize(xmlReader);
    }

    return value;
}

Example case:
using (MemoryStream stream = new MemoryStream())
using (XmlWriter writer = new XmlTextWriter(stream, Encoding.ASCII))
{
    writer.WriteRaw("<int>123</int>");
    writer.Flush();

    stream.Seek(0, SeekOrigin.Begin);

    using (XmlReader reader = new XmlTextReader(stream))
    {
        SqlXml sqlXml = new SqlXml(reader);

        int value = GetValue<Int32>(sqlXml);

        Debug.Assert(123 == value);
    }
}


Q: How to improve the performance and customize the listview to avoid OMM error in Android I am absolute beginner to Android and now I start using volley HTTP library with Listview. So I created a test project and trying on volley and Android. I am creating a newfeeds viewing app. Example , facebook newfeeds. Data are just dummy for learning purpose. My project is working as I expected. It loads new data when the scoll reach at the bottom of the listview. But after it loads the data for multiple times frequently, my App is throwing out of memory error.

My activity class

public class VolleyActivity extends Activity{
    private int defaultLastLoadedItem=0;
    private int lastSawFirstListItem;
    private int itemLoadedOn;
    private ArrayAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.volley_main);

        Button getBtn = (Button)findViewById(R.id.btn_get_request);
        getBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        ListView listView = (ListView)findViewById(R.id.volleyListView);
        adapter = new CustomAdapter(this,new ArrayList<Entity>());
        listView.setAdapter(adapter);
        updateListView();
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if(lastSawFirstListItem<firstVisibleItem)
                {
                    int currentLastItem = firstVisibleItem+visibleItemCount;
                    if(currentLastItem!=itemLoadedOn)
                    {
                        updateListView();
                        Toast.makeText(getBaseContext(),"More item loaded",Toast.LENGTH_SHORT).show();
                        itemLoadedOn = currentLastItem;
                    }
                }
                lastSawFirstListItem = firstVisibleItem;
            }
        });
    }
    public void updatedListView(int lastloadedItem)
    {
        defaultLastLoadedItem = lastloadedItem;
        //"http://api.androidhive.info/feed/feed.json";
        String url = "http://192.168.43.82:8888/simple_json/index.json";//"http://api.androidhive.info/feed/feed.json";

        JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                List<Entity> items = new ArrayList<Entity>();
                try{
                    JSONArray jsonArray = jsonObject.getJSONArray("feed");
                    for(int i=0;i<jsonArray.length();i++)
                    {
                        JSONObject item = jsonArray.getJSONObject(i);
                        Entity en = new Entity();
                        en.setId(item.getInt("id"));
                        en.setName(item.getString("name"));
                        en.setUrl(item.getString("url"));
                        items.add(en);
                    }
                    adapter.addAll(items);

                }
                catch (JSONException e)
                {
                    Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getBaseContext(),"Error listener",Toast.LENGTH_SHORT).show();
            }
        });

        Volley.newRequestQueue(getBaseContext()).add(jsonRequest);
    }
    public void updateListView()
    {
        updatedListView(defaultLastLoadedItem);
    }

}

What I want to know are:

*

*Will my application will throws that kind of error(omm) when it reaches to production ?

*If it will does, how  can I fix that issue ?

*How should I customize listview for this kind of newfeeds app for better performance if my current code is not suitable?

A: I think your http request getting called all time while you are scrolling
you just have to add following code in your onScroll of setOnScrollListener
final int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem == totalItemCount) {
    //your http request
}

I hope this will work for you.


Q: std::chrono::duration passed as a method parameter I have this method:
string tpToString(const system_clock::time_point &tp)
{
    string formatStr { "%Y-%m-%d %H:%M:%S" };
    return date::format(formatStr, date::floor<microseconds>(tp) );
}

This method produces a string such as:
2021-02-09 20:53:10.123456

That's great. It uses Howard Hinnant's date library. I just found myself hitting an instance where an API is returning an error if I offer a time out to microseconds. It wants milliseconds. So I can do that with a second method:
string tpToStringInMillis(const system_clock::time_point &tp)
{
    string formatStr { "%Y-%m-%d %H:%M:%S" };
    return date::format(formatStr, date::floor<milliseconds>(tp) );
}

That works. But what I'd prefer to do is pass (as an optional parameter) the duration, something like this:
string tpToString(const system_clock::time_point &tp, chrono::duration dur = milliseconds)
{
    string formatStr { "%Y-%m-%d %H:%M:%S" };
    return date::format(formatStr, date::floor<dur>(tp) );
}

However, this produces an error "no matching function for call to 'floor'". I'm actually surprised that it doesn't complain about the function definition, as milliseconds is a typedef.
Suggestions?
I suppose I could pass a lambda, but that's starting to get ugly.

A: If you make tpToString a template you can allow the caller to choose the accuracy at compile time.
template <typename FloorType = microseconds>
string tpToString(const system_clock::time_point& tp)
{
    string formatStr{ "%Y-%m-%d %H:%M:%S" };
    return date::format(formatStr, date::floor<FloorType>(tp));
}

int main()
{
    std::cout << tpToString(system_clock::now()) << "\n";
    std::cout << tpToString<milliseconds>(system_clock::now()) << "\n";
    std::cout << tpToString<seconds>(system_clock::now()) << "\n";
    std::cout << tpToString<minutes>(system_clock::now()) << "\n";
}


Q: iCal Eventstore - successful function on completion I have the following function to add a dynamic date to Ical -
-(void)AddToIcal{
    EKEventStore *store = [[EKEventStore alloc] init];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        EKEvent *event = [EKEvent eventWithEventStore:store];

        event.title = self.booked.bookingTitle;
        event.startDate = self.booked.bookingDate;

        event.endDate = [event.startDate dateByAddingTimeInterval:60*60];  //set 1 hour meeting
        [event setCalendar:[store defaultCalendarForNewEvents]];
        NSError *err = nil;
        [store saveEvent:event span:EKSpanThisEvent  commit:YES error:&err];
        NSString *savedEventId = event.eventIdentifier;  //this is so you can access this event later
    }];

}

Does anyone know how I could show a stored / not stored message when the ad event function is complete?

A: what about changing
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];

to
if (![store saveEvent:event span:EKSpanThisEvent commit:YES error:&err]) {
  NSLog([NSString stringWithFormat:@"Error saving event: %@", error.localizedDescription]);
} else {
  NSLog(@"Successfully saved event.");
}

You could as well do something different than writing to NSLog, like use an UIAlertView or such.
Also you may have a look a the Return Value section of the saveEvent:span:commit:error  Apple documentation.
It says:

Return Value
If successful, YES; otherwise, NO. Also returns NO if event does not need to be saved because it has not been modified.


Q: Visual Studio never hits break point in Controller Action In troubleshooting AddTagsCollection Action behavior in a controller, I have a strange scenario which I have not encountered before, its not even a multi threaded section. The Visual Studio Debugger enters the function till the first line string alert = ""; and even stops at the debugger but never goes on to the other lines!!
 public JsonResult AddTagsCollection(int collectionID, string Name, string Description, string Order, bool IsActive, bool RootUseOnly)
    {

      // Yes hits this break point only then bails out - whats going on??
        string Alert = "";

        // NEVER hits this break point
        if (ProfileTagCollection.GetByName(Name.Trim()).ProfileTagCollectionID > 0)
            Alert = "The collection \"" + Name + "\" already exists.";

         // NEVER hits this break point!!!
        var testme = "test";

        // NEVER hits this break point - you get the idea, it just return back to the HTML view??
        if (Name.Trim().ToLower().Length == 0)
            Alert = "The collection name should not be empty.";

        if (Alert != "")
        {
            RequestResultModel _model = new RequestResultModel();
            _model.InfoType = RequestResultInfoType.ErrorOrDanger;
            _model.Alert = Alert;

            AuditEvent.AppEventWarning(Profile.Member.Email, Alert);

            return Json(new
            {
                NotifyType = NotifyType.DialogInline,
                Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model),

            }, JsonRequestBehavior.AllowGet);
        }

        ProfileProfileTagCollection ProfileTagCollection = new ProfileProfileTagCollection();

        tagCollection.OrderID = 0;
        tagCollection.tagCollectionName = Name;
        tagCollection.tagCollectionDescription = Description;
        tagCollection.IsActive = IsActive ? 1 : 0;
        tagCollection.RootUseOnly = RootUseOnly ? 1 : 0;
        tagCollection.Save();

        if (collectionID > 0)
            AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("The \"{0}\" profile collection has been updated.", Name));
        else
            AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("The \"{0}\" profile collection has been added.",Name));

        if (Order != "")
        {
            Order = Order.Replace("this", tagCollection.tagCollectionID.ToString());
            ProfiletagCollections.UpdateOrder(Order);
        }

        // I have tried passing other combinations to reach here, but why does it not get here
        return Json(new {
            NotifyType = -1,
            Html = "",
        }, JsonRequestBehavior.AllowGet);

    }

I also tried to lookup the debug windows module, in 2013 its not listed, has it moved... In debug mode, select debug->windows->modules (modules is missing for me)
Can you help me with why the debugger does not hit the break point and what steps I can take to resolve or investigate this?

A: I think you could use this

You probably are after something like this:
if(System.Diagnostics.Debugger.IsAttached)
  System.Diagnostics.Debugger.Break(); Of course that will still get
  compiled in a Release build. If you want it to behave more like the
  Debug object where the code simply doesn't exist in a Release build,
  then you could do something like this:
[Conditional("DEBUG")] void DebugBreak() {
  if(System.Diagnostics.Debugger.IsAttached)
      System.Diagnostics.Debugger.Break(); } Then add a call to it in your code.


Q: FOSRestBundle parse headers I am using FOSRestBundle in order to implement an API. I would like to parse HTTP headers that are sent to me from the client.
How can I access them ?

A: You can get headers from Request object in your controller methods.
use Symfony\Component\HttpFoundation\Request;

public function someAction(Request $request){
   $request->headers //get headers
}


Q: Are sub-selects in a where-clauses executed multiple times or just once? I have a separate table (with no PK, only one row) to store the row count of a certain result. Now, this count is used in a query, like this (just an example):
SELECT * FROM `car`
WHERE `car`.`featured` = 1
AND ( SELECT `count` FROM `carfeaturedcounter` ) > 5;

Will SELECT count FROM carfeaturedcounter be executed multiple times (once for every row), or only once per query?

A: I think it depends on the version of MySQL.  You might as well move the condition to the from clause, where it will only be executed once:
SELECT c.*
FROM car c.CROSS JOIN
     (SELECT `count` FROM carfeaturedcounter) x
WHERE c.featured = 1 AND x.`count` > 5;


Q: Can no longer get response from web request when 400 returned I am having trouble making web service calls in an iOS application built with Xamarin.  This EXACT same code, that builds a request and uses HTTPWebRequest GetResponse() to get the response, used to work but now it is crashing when trying to get the response.  It crashes on ReadToEnd, saying that the argument cannot be null.  This code has remained unchanged since it worked.  I know that there IS a response with the 400 because PostMan works and I can also see a log from the backend when I'm making the call from my Xamarin app.  Searching stackoverflow is revealing that some people have resolved this issue by upgrading Xamarin and that it has something to do with the mono runtime it uses.  But the latest version of Xamarin is doing the same thing for me.
...
            } catch(WebException ex) {
                try {
                  if(ex.Response == null || ex.Status != WebExceptionStatus.ProtocolError) throw;
...
                    Stream data = ex.Response.GetResponseStream(); if(data==null) return "ERR";
                    StreamReader reader = new StreamReader(data); if(reader==null) return "ERR";
                    string responseFromServer = reader.ReadToEnd();

Expected results should be that my GetResponse does generate a WebException in the event of an HTTP 400, however there should still be a response body to read.
Here is a stacktrace of the exception:
    2019-04-02 09:15:17.367099-0400 ******.iOS[41201:4512789] *****> System.Net.WebException: Value cannot be null.
    Parameter name: src ---> System.ArgumentNullException: Value cannot be null.
    Parameter name: src
      at System.Buffer.BlockCopy (System.Array src, System.Int32 srcOffset, System.Array dst, System.Int32 dstOffset, System.Int32 count) [0x00003] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/corlib/ReferenceSources/Buffer.cs:39
      at System.Net.WebResponseStream+<ProcessRead>d__49.MoveNext () [0x00082] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/System/System.Net/WebResponseStream.cs:203
       --- End of inner exception stack trace ---
      at System.Net.HttpWebRequest+<RunWithTimeoutWorker>d__241`1[T].MoveNext () [0x000e8] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/System/System.Net/HttpWebRequest.cs:956
    --- End of stack trace from previous location where exception was thrown ---
      at System.Net.WebConnectionStream.Read (System.Byte[] buffer, System.Int32 offset, System.Int32 count) [0x00070] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/System/System.Net/WebConnectionStream.cs:136
      at System.IO.Stream.ReadByte () [0x00007] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/io/stream.cs:758
      at *****.API.callService (System.String endpt, System.String parm, System.Boolean isGet) [0x003e9] in /Users/****/Projects/*****/*****/API.cs:80


Q: ion-footer not showing when ion-content contains elements The ion-footer is not showing when my ion-content has elements
In this code the footer doesn't appear :
<ion-content>

{{user.name}}

{{user['custom:role']}}

  <ion-button expand="block" color="primary">logout</ion-button>
</ion-content>

<ion-footer>
  <ion-toolbar>
    <ion-title>Footer</ion-title>
  </ion-toolbar>
</ion-footer>

And that works :
<ion-content>
  <ion-button expand="block" color="primary" (click)="cognito.logout()">logout</ion-button>
</ion-content>

<ion-footer>
  <ion-toolbar>
    <ion-title>Footer</ion-title>
  </ion-toolbar>
</ion-footer>

I have tried to remove div and p tags using ion-text or to remove the button and keep only the p / ion-text
But I cannot make the footer show up with content (except the ion-button) in my ion-content.
I for the moment use some css, without ion-footer. I'd rather find a non-hacky solution.


Q: How to improve performance using multithreading in spring Mvc I am using spring MVC model in my project. In which controller get request from some some thired party application.
Controller get 20 request per sec. Code look like this
@Controller
@RequestMapping("/action")
public class FrontController{

@AutoWired
private CommonService commonService;

(First Code)
@RequestMappint("/save")
public String saveData(@PathParam("id")String did){

    List<String, Object> map = commonService.getVmn(did);
    CallReporting callReporting = new CallReporting();
    callReporting.setName(map.get("name"));
    so---on (have 15 field)
    commonService.save(callReporting);
    }

    return "1";
}

This code is working fine but some time if mysql is busy then it takes time to return the value to calling application.
So I droped the idea and start Async communication.
(Second Code)
@RequestMappint("/save")
public String saveData(@PathParam("id")String did){

    Thread thread = new Thread(new Runnable(){
        List<String, Object> map = commonService.getVmn(did);
        CallReporting callReporting = new CallReporting();
        callReporting.setName(map.get("name"));
        so---on (have 15 field)
        commonService.save(callReporting);
    });
    }

    return "1";
}

I started using the code something like this. So that calling party can get the response immediately(reduce the response time) and later on my application continue to work. But in First code i test the load with JMeter(20 req/sec ) and found it is working fine with cpu load(3%). But in second code  with same load cpu load is going to more than 100%.Than i started using the ThreadPoolTaskExecutor with below configuration.
@AutoWired
private ThreadPoolTaskExecutor executor;

@RequestMappint("/save")
public String saveData(@PathParam("id")String did){

//Assume this code is in MyRunnableWorker Class
        List<String, Object> map = commonService.getVmn(did);
        CallReporting callReporting = new CallReporting();
        callReporting.setName(map.get("name"));
        so---on (have 15 field)
        commonService.save(callReporting);

    MyRunnableWorker worker = new MyRunnableWorker();
    executor.execute(worker)

    return "1";
}

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="50" />
    <property name="maxPoolSize" value="100" />
    <property name="keep-alive" value="10" />
    <property name="queueCapacity" value="200" />
</bean>

but found the same result. Whats wrong with code can somebody suggest me. One important thing when i test with Jmeter in stage envorment then load is moving between 30% to 70%.. But in production server it is always around 100%. It is java consuming 100% other process is quite low.
Production machine haveing linux OS. hexacore processer having 128 GB RAM.
Can some one tell me what to do.

A: Your ThreadPoolTaskExecutor has too many threads. CPU spend lot of time to switch context between threds. On test you run just your controller so there are no other threads (calls) that exist on production. Core problem is waiting for DB, because it is blocking thread
Solutions

*

*set pool size smaller (make some experiment)

*remove executor and use actor system like Akka for save operation.

*Most important use batch to save objects in DB. There will be only one call per e.g. 1000 objects not 1k calls for 1k objects > JPA/Hibernate improve batch insert performance

A: It looks like you are turning the wrong knob.
In your first version you had up to  N threads banging your database. With N being configured somewhere in your servlet container. And also doing the servlet thingy, accepting connections and stuff.
Now you created 200 additional threads, which do basically nothing but hitting the database. While the previous threads do their connection handling, request parsing thing. So you increased the load on the database and you added the load do to context switching (except when you have multiple hundred cores).
And for some weird reason, your database didn't get any faster.
In order to improve, reduce the number of threads in your thread pool which hits the database. Measure how many threads the database can handle before performance degrades.
Make the queueCapacity large enough to cover the request spikes you need to handle.
Implement something that gets a meaningfull answer to the user when this isn't sufficient. Something like "Sorry ..."
And then take care of the real issue: How to make your database handle the requests fast enough.
It might be that some db tuning is in place, or you need to switch to a different database system, or maybe the implementation of the save method needs some tuning ...
But all this is for a different question.

A: the bottle neck in your case are transactions (DB)
here's some proposals :

*

*if it's not necessary that data has to be instantly saved just use an asynchronous job to do it (JMS, In Memory Queue, etc)

*You may consider to load DB into RAM


Q: How to extend validation of a subitem of my viewmodel? My model class Animal implements INotifyDataErrorInfo to add validation. My view is bound to a viewmodel with a property SelectedAnimal of type Animal like that:
View
<TextBox Text="{Binding SelectedAnimal.Epc, UpdateSourceTrigger=PropertyChanged,
                   ValidatesOnNotifyDataErrors=True}" />

ViewModel
public Animal SelectedAnimal
{
    get
    {
        return _animal;
    }
    set
    {
        Set(() => Animal, ref _animal, value);
    }
}

Error visualization works fine:

Question
I want to add additional validation, of the field EPC that is done in my viewmodel not in the Animal class. So I want to add another validation rule (e.g. check if EPC is unique), that is visualized with the EPC TextBox.
How can I achieve this? Validation errors of that viewmodel rule should also be shown on the EPC TextBox.
I tried manipulating the list of validation errors of class Animal without success.

Additional info
validation based on class ValidatableModel

A: This is one way to solve your problem:

*

*Wrap the property whose validation you want to extend in your viewmodel
public string Epc
{
    get
    {
       return _epc;
    }
    set
    {
       Animal.Epc = value;
       Set(() => Epc, ref _epc, value, false);
    }
}

*Add two custom validation rules to that property
[CustomValidation(typeof(ViewModel), "AnimalEpcValidate")]
[CustomValidation(typeof(ViewModel), "ExtendedEpcValidate")]

*Add your extended validation code, that is not done by Animal itself, to ExtendedEpcValidate

*Call the Animal.Epc validation and add the results to the Epc validation results in your viewmodel
public static ValidationResult AnimalEpcValidate(object obj, ValidationContext context)
{
    var aevm = context.ObjectInstance as ViewModel;

    // get errors from Animal validation
    var animalErrors = aevm.Animal.GetErrors("Epc")?.Cast<string>();

    // add errors from Animal validation to your Epc validation results
    var error = animalErrors?.Aggregate(string.Empty, (current, animalError) => current + animalError);

    // return aggregated errors of Epc property
    return string.IsNullOrEmpty(error)
               ? ValidationResult.Success
               : new ValidationResult(error, new List<string> { "Epc" });
}


Q: Sending POJO containing XML Document via Spring MVC i try to post a POJO from one Spring Boot&MVC app to another.
This all works fine except for one case, in which the POJO contains a w3c.dom.Document XML attribute.
The POJO is quite simple, all getters and setters are managed by project lombok:
@Data
public class SmartContractFile {
    private final UUID id;
    private Document file;
    private int copies;

    public SmartContractFile(UUID id, Document scFile, int copies) {
        this.id = id;
        this.file = scFile;
        this.copies = copies;
    }
}

The POSTing happens via Spring RestTemplate and contains only the POJO.
I expect a simple true or false response.
    public boolean saveFile(SmartContractFile smartContract) {
        RestTemplate template = new RestTemplate();
        URI methodURI;
        try {
            methodURI = new URI(this.address + DNWebConstants.REST_ADDSC);
            ResponseEntity<Boolean> response = template.postForEntity(methodURI, smartContract, Boolean.class);

            return (response.hasBody() && response.getBody());
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

The server-side webservice is bound via @RequestMapping and a constant to the target address. I already tried @PostMapping, but the behavior did not change. The POJO should be extracted by Spring via @RequestBody.
@RequestMapping(DNWebConstants.REST_ADDSC)
    public ResponseEntity<Boolean> addSmartContract(@RequestBody SmartContractFile smartContract) {
        try {
            smartContractHandler.validateScDocument(smartContract.getFile());
        } catch (ContractException | IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(false);
        }
        if (this.thisNode.saveRequestedScStorage(smartContract))
            return ResponseEntity.ok(true);
        else
            System.out.println("Wrong storage location.");
        return ResponseEntity.badRequest().body(false);
    }

In case of any error in my application, i would always expect a 400 bad request with "false" in the response body, as well as an output on the servers console (either via printStackTrace() or System.out.println()).
However, all i get is a 400 with empty body:
org.springframework.web.client.HttpClientErrorException: 400 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:766) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:724) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:698) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:484) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at model.Node.saveFile(Node.java:80) ~[classes/:na]
    at model.Topology.saveFile(Topology.java:50) ~[classes/:na]
    at mgmt.web.DNWebservice.saveSmartContract(DNWebservice.java:111) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_201]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_201]

With this being my application:
at model.Node.saveFile(Node.java:80) ~[classes/:na]
    at model.Topology.saveFile(Topology.java:50) ~[classes/:na]
    at mgmt.web.DNWebservice.saveSmartContract(DNWebservice.java:111) ~[classes/:na]

Where model.Node.saveFile(Node.java:80) is the client method shown above.
I basically tried every way i know to pack that request and switched wildly through al Spring Annotations, but nothing worked.
So i hope there's somebody here to help me.
Thanks in advance!

A: I now found my error, it had nothing to do with the resttemplate.
The bootstrap had an error which caused the app to send the request to itself.
The client denied its' own request and Spring did all the errorhandling automatically, so it did not show in the console output as logged by my application, which is why i overlooked it.
After fixing this, the request in the OP worked just fine.
Sorry.


Q: How to use debugger in android or Java? I am trying to create a simple android application. This is the first time I am coding for android and Java. I have installed android sdk on win 7 machine. I have never used a debugger. I want a resource to learn use of debugger in android from basic. If it is same as Java, Kindly provide me a link to learn java debugger from basic. Thanks in advance.

A: I hope you are using eclipse to develop an Android app. If not the please do that.
Here is a information to debug an Android app.

A: Have you tried just playing around with the Eclipse debugger?
Try:

*

*Click on the left-hand margin next to code you want to investigate, setting a "breakpoint"

*Click on the bug icon to run your application in Debug mode.

*When your application arrives at that line of code, Eclipse will pop up a dialog confirming a change to the debug perspective.

*Play with the step-next/step-out buttons in the debugger.


Q: How to make first dropdown not render in reactjs and ant design I need to make my current draggable component's dropdown to not render on specific cell (specifically the first Row). However, it will still show the cell just without the dropdown. I tried to search for a way however could not find any. Appreciate any help / directions given. Thanks! I also also attached the screenshot of current and expected. (Just take note of the dropdown being empty)
*Current Interface - all dropdown rendered

*Expected New Interface - first dropdown not rendered

Main code with ant design component Row/Col and Select/Option for the dropdown:
render() {
    return (

        <Modal
          destroyOnClose={true}
          width={'80%'}
          title='Approval Sequence'
          visible={this.state.isVisible}
          onOk={() => {

            updateFlowType(this.state.currentItem.id, {
              name: this.state.currentItem.name,
              sites: this.state.initTags.map((x) => ({
                idSite: x.id,
                returnToStep: x.returnToStep,
              })),
            })
              .then((r) => {
                notification['sucess']({
                  message: 'Success',
                  description: 'Save data success',
                });
                this.setState({ isVisible: false });
                this.getData();
              })
              .catch(() => {
                notification['failed']({
                  message: 'Failed',
                  description: 'Failed to save',
                });
              });
          }}
          onCancel={() => {
            this.setState({ isVisible: false });
          }}
        >

          <Row gutter={[2, 2]}>
            <Col style={{ textAlign: 'center' }} span={8}>
              <Text strong>Role</Text>
            </Col>
            <Col style={{ textAlign: 'center' }} span={8}>
              <Text strong> Return to Department: </Text>
            </Col>
          </Row>

              <DraggableArea
                onChange={(initTags) => this.setState({ initTags })}
                isList
                tags={this.state.initTags}
                render={({ tag }) => (
                  <Row>
                    <Col span={8}>
                      <Button style={{ width: '100%' }}>{tag.name}</Button>
                    </Col>

                    <Col span={16}>
                      <Select
                        onChange={(e) => {
                          //create clone
                          let clone = [...this.state.initTags];

                          let item = clone.find((x) => x.id === tag.id);

                          let itemReject = clone.find((x) => x.name === e);

                          console.log('itemReject', itemReject);
                          //create returnToStep in item
                          item.returnToStep = itemReject.id;
                          this.setState({
                            initTags: clone,
                          });
                        }}
                        //placeholder = 'Select return step'
                        style={{ width: '100%' }}
                      >
                        {this.getReject(tag.name).map((newTag) => (
                        //getReject function will slice to get only items before the current iteration object (e.g. if current is index 3, only get index 0~2)
                          <Option key={newTag.name} value={newTag.name}>
                            {newTag.name}
                          </Option>
                        ))}
                      </Select>
                    </Col>
                  </Row>
                )}
              ></DraggableArea>

        </Modal>

    );
  }

A: You can do "conditional render" using a condition and a component like this:
const someBoolean = true;
retrun (
    { someBoolean && <SomeComponent /> }
)

if someBoolean is true, then <SomeComponent/>  will show.
if someBoolean is false, then <SomeComponent/> will not show.
So, just use that to conditionally render your dropdown column or any other component.
If, the table rows are based upon content and dynamically rendered, then I would modify the content accordingly. (i.e. don't provide the rows you don't want to render).


Q: Can't pass array value into Invoke-RestMethod URL String I have the below code snippet that saves a array of ~90 devices to my string $report
$report = Get-ADComputer -Filter * -SearchBase 'OU=Boston, DC=someCompany, DC=com' | Select -ExpandProperty name

Now my issue is when I try to pass this array to my Invoke-RestMethod command
$headers=@{}
$headers.Add("Content-Type", "application/json")
$headers.Add("Authorization", "Bearer mykeyhere")
$response = Invoke-RestMethod -Uri "https://app.ninjarmm.com/v2/devices/search?q=$report[0]" -Method GET -Headers $headers

When I run the above code snippet, I would think that $response returns the result of my first array of $report, but what actually happens is that it returns back $response in the attached photo.
Help appreciated, thanks yall


Q: Which algorithm should be used to find the point? You need to find some unknown, predetermined point in three-dimensional space, in the smallest number of attempts, using only a function that can return the distance from
any point you pass to it to the desired unknown point.
To solve the problem, first implement a function f that, by taking the coordinates of any point s(x, y, z), return the distance between that point and a conditionally unknown, randomly generated point
point you arbitrarily generate r(x, y, z), where x, y, z can be integers between
0 и 100.
For example, for an arbitrarily generated point r(0, 0, 10) and a point passed to the function
s(0, 0, 0), the result of the function would be as follows:
f(s) = 10 // the distance between s(0, 0, 0) and r(0, 0, 10) is 10
Next, implement the algorithm itself for the assignment. The algorithm should find the coordinates of
of an arbitrarily generated point with the least number of calls to the function f.
I have a randomizer instead of an algorithm, that's all I got. Help.
const pointToFound = {
  x: 12,
  y: 9,
  z: 76,
};

let attemts = 0;
let isXFound = false;
let isYFound = false;
let isZFound = false;

const pointHistory = [];

const getRandomPoint = () => {
  return {
    x: isXFound ? isXFound : Math.floor(Math.random() * 101),
    y: isYFound ? isYFound : Math.floor(Math.random() * 101),
    z: isZFound ? isZFound : Math.floor(Math.random() * 101),
  };
};

const getDifference = (point, pointToCompare) => {
  return {
    x:
      Math.max(point.x, pointToCompare.x) - Math.min(point.x, pointToCompare.x),
    y:
      Math.max(point.y, pointToCompare.y) - Math.min(point.y, pointToCompare.y),
    z:
      Math.max(point.z, pointToCompare.z) - Math.min(point.z, pointToCompare.z),
  };
};

const condition = !isXFound && !isYFound && !isZFound;

while (condition) {
  const point = getRandomPoint();

  const difference = getDifference(point, pointToFound);
  pointHistory.push(point);

  attemts += 1;

  if (isXFound && isYFound && isZFound) {
    console.log("Total attempts: ", attemts);
    console.log(point);
    break;
  }

  if (difference.x === 0 && !isXFound) {
    isXFound = point.x;
  }

  if (difference.y === 0 && !isYFound) {
    isYFound = point.y;
  }

  if (difference.z === 0 && !isZFound) {
    isZFound = point.z;
  }
}

console.log(pointHistory);

I have a randomizer instead of an algorithm, that's all I got. Help.

A: One idea is as follows:
You pick an initial random point, and for each dimension, find the exact value. How? For the sake of symmetry, suppose that you desire to find x of the target point. Increase by one the x, and compute the distance of the new point from the target point. If it goes further, it means that you should move in the opposite direction. Hence, you can run a binary search and get the distance to find the exact x of the target point. Otherwise, it means that you are going in the right direction along X-axis. So, do a binary search between all points with the same y and z such that their x values can change from x+1 to 100. A more formal solution comes in the following (just a pseudo-code).
You should also ask about the complexity of this solution. As the dimension of the point is constant (3) and checking these conditions take a constant time, the complexity of number of calling getDifference function is O(log(n)). What is n here? the length of valid range for coordinates (here is 100).
1. p: (x,y,z) <- Pick a random coordinate
2. dist: (dist_x, dist_y, dist_z) <- getDifference(p, TargetPoint)
3. For each dimension, do the following (i can be 0 (x), 1 (y), 2 (3)):
4.       if(dist == 0):
5.           isFound[i] <- p[i]
6.           continue

7.     new_i <- p[i] + 1
8.     new_point <- p
9.     new_point[i] <- new_i
10.    new_dist <- getDifference(new_point, pointToFound)
11.    if(new_dist == 0):
12.        isFound[i] <- new_point[i];
13.        continue

14.    if(new_dist[i] > dist[i]):
15.        isFound[i] <- binary_search for range [0, p[i]-1] to find the exact value of the pointToFound in dimension i
15.        continue
16.    else:
17.        isFound[i] <- binary_search for range [p[i] + 1, 100] to find the exact value of the pointToFound in dimension i
18.        continue

A: Following method will work for coordinates with positive or negative real values as well.
Let's say you are searching for the coordinates of point P. As the first query point, use origin O. Let the distance to the origin O be |PO|. At this point, you know that P is on the surface of sphere
(P.x)^2 + (P.y)^2 + (P.z)^2 = |PO|^2  (1)

As the second query point, use Q = (|PO|, 0, 0). Not likely but if you find the distance |PQ| zero, Q is the point you are looking for. Otherwise, you get another sphere equation, and you know that P is on the surface of this sphere as well:
(P.x - |PO|)^2 + (P.y)^2 + (P.z)^2 = |PQ|^2   (2)

Now, if you subtract (1) from (2), you get
(P.x - |PO|)^2 - (P.x)^2 = |PQ|^2 - |PO|^2  (3)

Since the only unknown in this equation is P.x you can get its value:
P.x = (((-|PQ|^2 + |PO|^2) / |PO|) + |PO|)/2)

Following similar steps, you can get P.y with R = (0, |PO|, 0) and P.z with S = (0, 0, |PO|). So, by using four query points O, Q, R, and S you can get the coordinates of P.

A: This can be done with at most 3 guesses and often with 2 guesses:

*

*Let the first guess be [0, 0, 0], and ask for the distance

*Find in the 100x100x100 cube all points that have that distance to [0, 0, 0]. There might be around 100-200 points that have that distance: consider all of these candidates.

*Take the first candidate as the second guess and ask for the distance

*Find among the other candidates the ones that have exactly that distance to the first candidate. Often there will be only one point that satisfies this condition. In that case we can return that candidate and only 2 guesses were necessary.

*Otherwise (when there is more than one candidate remaining) repeat the previous step which will now certainly lead to a single point.

Here is an implementation that provides a blackbox function which chooses the secret point in a local variable, and which returns two functions: f for the caller to submit a guess, and report for the caller to verify the result of the algorithm and report on the number of guesses. This is not part of the algorithm itself, which is provided in the findPoint function.

const rnd = () => Math.floor(Math.random() * 101);

const distance = (a, b) =>
    a.reduce((acc, x, i) => acc + (x - b[i]) ** 2, 0) ** 0.5;

function findPoint(f) {
    // First guess is always the zero-point
    let guess = [0, 0, 0];
    let dist = f(guess);
    if (dist === 0) return guess; // Extremely lucky!
    // Find the points in the cube that have this distance to [0,0,0]
    let candidates = [];
    const limit = Math.min(100, Math.round(dist));
    for (let x = 0; x <= limit; x++) {
        const p = [x, limit, 0];
        // Follow circle in X=x plane
        while (p[1] >= 0 && p[2] <= limit) {
            const d = distance(p, guess);
            const diff = d - dist;
            if (Math.abs(diff) < 1e-7) candidates.push([...p]);
            if (diff >= 0) p[1]--;
            else p[2]++;
        }
    }
    // As long there are multiple candidates, continue with a guess
    while (candidates.length > 1) {
        const candidates2 = [];
        // These guesses are taking the first candidate as guess
        guess = candidates[0];
        dist = f(guess);
        if (dist === 0) return guess; // lucky!
        for (const p of candidates) {
            let d = distance(p, guess);
            let diff = d - dist;
            if (Math.abs(diff) < 1e-7) candidates2.push(p);
        }
        candidates = candidates2;
    }
    return candidates[0]; // Don't call f as we are sure!
}

function blackbox() {
    const secret = [rnd(), rnd(), rnd()];
    console.log("Secret", JSON.stringify(secret));
    let guessCount = 0;
    const f = guess => {
        guessCount++;
        const dist = distance(secret, guess);
        console.log("Submitted guess " + JSON.stringify(guess) + " is at distance " + dist);
        return dist;
    };
    const report = (result) => {
        console.log("Number of guesses: " + guessCount);
        console.log("The provided result is " + (distance(secret, result) ? "not" : "") + "correct");
    }
    return {f, report};
}

// Example run
const {f, report} = blackbox();
const result = findPoint(f);
console.log("Algorithm says the secret point is: " + JSON.stringify(result));
report(result);

Each run will generate a new secret point. When running this thousands of times it turns out that there is 1/9 probability that the algorithm needs a third guess. In the other 8/9 cases, the algorithm needs two guesses.


Q: Search for sentence that may containing different words in Python In python, I have a string sentence as follows:
Change setting to value 50.

I essentially want to search for the sentence in a list of strings and extract the "setting" and "50" values, as they may be different.
I'm not terribly great with regular expressions, so any help would be greatly appreciated.

A: Try this:
"Change (.*?) to value (.*?)\."

https://regex101.com/r/gG5sK3/2
Where the first and the second group are your desired values!


Q: Decimal arithmetic in shell shows as command not found My intention is to reduce or increase brightness levels using code
The following is my code
BRIGHTNESS=`xrandr --verbose | grep -m 1 -i brightness | cut -f2 -d ' '`
z=$($BRIGHTNESS-0.1)
echo "$z"

I get the error adjust_brightness.sh: line 4: 1.0-0.1: command not found

A: $(...) is a command substitution. Command substitution executes the commands inside it. Here it tries to execute 1.0-0.1 as a command.
The $((...)) does arithmetic expansion, note the double braces.
While the following will trigger arithmetic expansion:
z=$(($brightness-0.1))

No, shell does not support floating point arithmetic, only whole numbers. Research other questions on this site how to do floating point arithmetic in shell. Because arithmetic expansion expands also variables, you can remove the $ from inside. For example pipe the string to be calculated to bc (<<< is a here string):
z=$(bc <<<"$brightness - 0.1")

Notes:

*

*And while were at it, do not use backticks `...` at all. Use $(...) instead. brightness=$(xrandr --verbose | grep -m 1 -i brightness | cut -f2 -d ' ')

*UPPER CASE VARIABLES are by convention reserved for exported variables, like IFS, LINES, COLUMNS etc. Use lower case variables in your scripts.


Q: is there a way to check if the email and password edit text are filled before excecuting the login button intent? I am new to android. i have created a login page with email and password editTexts and a login button. how can i check if the email and password is filled before executing the login button intent? and how is the login button conditional intent declared?
here is my xml code
    <EditText
        android:id="@+id/emailEt"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/emailEt"
        android:inputType="textEmailAddress"

        android:paddingStart="8dp"
        android:paddingEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.025"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="parent" />

    <EditText
        android:id="@+id/passwordEt"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/passwordEt"
        android:inputType="textPassword"
        android:paddingStart="8dp"
        android:paddingEnd="8dp"

        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="@+id/parent"
        app:layout_constraintTop_toBottomOf="@+id/parent" />

    <Button
        android:id="@+id/loginBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="@string/loginBtn"
        android:textAllCaps="false"
        android:textSize="15sp"
        android:onClick="login"

        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/passwordEt" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: Yes, there are lot of ways that this can be handled. A simple google search could have helped you out.
The most simple way is to set OnClickListener() for the Login Button. The listener method will be called when the button is clicked.
Inside the method, you can check if the Edittext field is empty using the TextUtils.isEmpty("TEXT INSIDE EDITEXT") method.
The text inside the edit text can be read using the getText() method.
Please have a look at the below code for reference.
    public OnClickListener onLoginClick = new OnClickListener()
{

    @Override
    public void onClick(DialogInterface dialog, int which)
    {
        EditText emailField = (EditText)layout.findViewById(R.id. emailEt);
        String email = emailField.getText().toString()

        if(TextUtils.isEmpty(email))
        {
           // Show error here
        }
        else
        {
          // Do the necessary action here.
        }

    }
};

Similarly, add a check for the password field.
In the XML file, set the listener to the Login button like this.
android:onClick="onLoginClick"

A: yourEditext.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //Here you can store email into variable before clicking button
        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {

        // TODO Auto-generated method stub
    }
});

A: Yes you can user myEditText.addTextChangedListener() when user is Typing you will get the the email and password
emailEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //Here you can store email into variable before clicking button
        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {

        // TODO Auto-generated method stub
    }
});


Q: Query Builder with join and condition in Many to many relation I have a many to many relation with Employee and MembreFamille. And i want to get all MembreFamilles that have an Employee.
This is my query  :
class MembreFamilleRepository extends EntityRepository
{
    public function getMembres($emp)
    {
        $qb = $this->createQueryBuilder('a');
        $qb
            ->leftJoin('a.employees', 'employees');
        $qb
            ->where('employees.id = :id')
            ->setParameter('id', $emp);
        return $qb
            ->getQuery()
            ->getResult()
            ;
    }
}

When I test this function in the controller , the function return 0 result.
The mapping in Employee Entity:
 /**
     * @ORM\ManyToMany(targetEntity="PFE\EmployeesBundle\Entity\MembreFamille", cascade={"persist"})
     */
    private $membreFamilles;

The Mapping in MembreFamille Entity :
 /**
     * @ORM\ManyToMany(targetEntity="PFE\UserBundle\Entity\Employee", cascade={"persist"})
     */
    private $employees;

The use in the Controller ($employee is an instance of Employee Entity ) :
$list = $em->getRepository('PFEEmployeesBundle:MembreFamille')->getMembres($employee->getId());

A: You can use a construction called "MEMBER OF".
class MembreFamilleRepository extends EntityRepository
{
    public function getMembres($emp)
    {
        return $this->createQueryBuilder('a');
            ->where(':employee MEMBER OF a.employees')
            ->setParameter('employee', $emp)
            ->getQuery()
            ->getResult()
        ;
    }
}

You can use a construction called "MEMBER OF"

A: You need to add a JoinTable for your ManyToMany association and set the owning and inverse sides:
/**
 * @ORM\ManyToMany(targetEntity="PFE\EmployeesBundle\Entity\MembreFamille",
 *   cascade={"persist"}, mapped="employees")
 */
private $membreFamilles;

.................................

/**
 * @ORM\ManyToMany(targetEntity="PFE\UserBundle\Entity\Employee", cascade={"persist"}, inversedBy="membreFamilles")
 * @ORM\JoinTable(name="membre_familles_employees")
 */
private $employees;


Q: Insert "Select" in dropdown with LInq I have loaded the drop down box from LINQ,

CustomerDataContext customer = new
  CustomerDataContext();
    ddlCust.DataSource = from cust in customerDC.Customers
                             orderby cust.CustId ascending
                             select new {cust.CustId,

cust.CustName} ;
    ddlCust.DataTextField = "CustName";
    ddlCust.DataValueField = "CustId";
    ddlCust.DataBind();

it is working fine but I want item of drop down list as :
Text: Select
Value: 0
How can I do that?

A: ....
....
ddlCust.DataBind();
ddlCust.Items.Insert(0, new ListItem("Select Value:", "0"));


Q: How to match dataframe by match column I'm new to pandas. I'm trying to join two datasets as below:
df1:
df1 = pd.DataFrame({'id': [1121, 1122, 1123, 1124, 1125], 'name': ['F.01', 'F.01', 'F.02', 'F.02', 'F.02'], 'description': ['r1', 'r2', 'l1', 'l2', 'l3']})

Looks like:
  id  name description
1121  F.01 r1
1122  F.01 r2
1123  F.02 l1
1124  F.02 l2
1125  F.02 l3

df2:
df2 = pd.DataFrame({'code': ['F.01', 'F.02'], 'r1': [1, 0], 'r2': [2, 0], 'l1': [0, 3], 'l2': [0, 4], 'l3': [0, 5]})

df2 looks like:
code  r1  r2  l1  l2  l3
F.01   1   2   0   0   0
F.02   0   0   3   4   5

The result I would like them match by
df1.name = df2.code
df1.description = df2.(column name)

The result I prefer is like:
  id  name description value
1121  F.01 r1          1
1122  F.01 r2          2
1123  F.02 l1          3
1124  F.02 l2          4
1125  F.02 l3          5

Thanks!

A: The general guidance by Henry is right, but it lacks some necessary details.
To get your expected result the following steps are required:

*

*rename code in df2 to name,

*melt df2 on name, setting var_name to description,

*merge df1 with the above melt result on name and description.

The code to do it is:
result = pd.merge(df1, df2.rename(columns={'code': 'name'}).melt(
    'name', var_name='description'), on=['name', 'description'])

The result is:
     id  name description  value
0  1121  F.01          r1      1
1  1122  F.01          r2      2
2  1123  F.02          l1      3
3  1124  F.02          l2      4
4  1125  F.02          l3      5


Q: WordPress permalinks rewrite on iis7 I spend a lot of time in looking for solution, so you are my last hope before giving up :)
On my localhost iis7 i set custom permalinks http://sitename/%sample-post%/ with rewrite mode installed.
<configuration>
  <system.webServer>
    <defaultDocument>
      <files>
        <add value="index.php"/>
      </files>
    </defaultDocument>
    <rewrite>
      <rules>
            <rule name="WordPress: http://tip4u03" patternSyntax="Wildcard">
                <match url="*"/>
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
                    </conditions>
                <action type="Rewrite" url="index.php"/>
            </rule></rules>
    </rewrite>
  </system.webServer>
</configuration>

Its work only in wwwroot directory. Outside of wwwroot directory, its return 404 template page. Same issue on my shared iis7 server (VPS)

A: I solved the issue !!!
The problem was't with site location, it was because the permalinks are in Hebrew language. I added the following condition to wp-config file
if (isset($_SERVER['UNENCODED_URL'])) {
    $_SERVER['REQUEST_URI'] = $_SERVER['UNENCODED_URL'];
}

according to this link: Wordpress Hebrew permalinks
Finally its work !


Q: Mouse Down Event not firing (Bubbling events) I am a novice to WPF. I started learning about RoutedEvents in WPF. I tried a sample and i met up with a problem
    <Grid Margin="5" Name="Grid" MouseDown="Window_MouseUp">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Label BorderBrush="Black" BorderThickness="1" Grid.Row="0" Margin="5"        Name="FancyLabel" MouseDown="Window_MouseUp" >
        <StackPanel Name="Stack" MouseDown="Window_MouseUp">
            <TextBlock Margin="3" Name="txtBlock1">
                Click Any Where
            </TextBlock>
            <TextBlock Margin="50" Name="txtBlock2" >
                Click me also
            </TextBlock>
        </StackPanel>
    </Label>
    <ListBox Grid.Row="1" Margin="5" Name="ListMessages"/>
    <Button Grid.Row="3" Margin="5" Name="cmd_Clear" MouseDown="Cmd_Clear_MouseDown"  >Clear</Button>
</Grid>

The handler for the mouseDown event of the button is different from others int the tree hierarchy. The event is not firing..
But if i add in the .cs file the following code
 Grid.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp),true);
 Stack.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 FancyLabel.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 txtBlock1.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 txtBlock2.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 Img1.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 cmd_Clear.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Cmd_Clear_MouseDown), true);

the Cmd_Clear_MouseDown event is fired and the event is bubbled up to the grid and the grid fires Window_MouseUp.

A: Two points:
1) Is MouseDown="Window_MouseUp" everywhere intended?
2) Why not register to Click event with ClickMode="Press" instead of MouseDown. I don't think Button provides/raises MouseDown unless may be with a custom template.
Example:
<Button Grid.Row="3"
        Margin="5"
        Name="cmd_Clear"
        ClickMode="Press"
        Click="Cmd_Clear_MouseDown">Clear</Button>


Q: Vertically bottom align a linear gradient I have made a jsfiddle = https://jsfiddle.net/wLomyf65/
HTML:

CSS:
.skeleton-6euk0cm7tfi:empty {height: 100px; background-color: #ffffff; border-radius: 0px 0px 0px 0px; background-image: linear-gradient( #676b6f 6px, transparent 0 );background-repeat: repeat-y;background-size: 88px 100px;background-position: left 0px bottom 0px;}

I wish to vertically bottom align the linear gradient (so that its in the bottom left corner).
I have used: background-position: left 0px bottom 0px; but this hasn't done it.

A: A slight problem with the way you are setting things up is that the height of the element itself and the height of the background image (before you have sized it) are the same, and its drawing the gray for 6px from the top (the default direction for a linear-gradient) and the rest is transparent.
This snippet slightly simplifies what is going on.
It 'draws'a background image in the gray color, setting its width to 88% and its height to 6px and its position to bottom left. It sets it to not repeat on either axis.

body {
  background: red;
}

.skeleton-6euk0cm7tfi:empty {
  height: 100px;
  background-color: #ffffff;
  border-radius: 0px 0px 0px 0px;
  background-image: linear-gradient( #676b6f, #676b6f);
  background-repeat: no-repeat;
  background-size: 88px 6px;
  background-position: left bottom;
}

<


Q: MYSQL - MAX() returns wrong date I have a mysql table like this
+----------+----------+-------------------+
| entrykey | user_key |     validfrom      |
+----------+----------+-------------------+
|        1 |        3 | 2016-4-1 0:0:0.0  |
|        2 |        3 | 2016-12-1 0:0:0.0 |
|        3 |        2 | 2016-12-1 0:0:0.0 |
|        4 |        2 | 2016-3-1 0:0:0.0  |
+----------+----------+-------------------+

now I am trying to get only the row for each user where the validfrom is the newest. So I am doing a query like this:
SELECT entrykey, user_key, max(validfrom)
FROM table
Group by user_key;

It is working fine for almost all of my data, just this two examples I posted here in the table select the wrong row which is older. So for user_key 3 it selects entrykey 1 and for the user_key 2 it selects entrykey 4.
What am I doing wrong?

A: I guess the validform should be 2016-03-01 instead of 2016-3-01 because it is not converted into date before compare.

A: I am totally agree with the point made in the accepted answer (+1 for that). But, even if op somehow convert validfrom from string to DateTime, his attempt won't give him the desired result.
Let's examine the query given in question:
SELECT entrykey, user_key, MAX(STR_TO_DATE(validfrom, '%Y-%c-%e')) as date1
FROM table
Group by user_key;

Now, this query will return user_key with maximum value of validfrom for that particular user_key. But the entrykey won't be the entrykey with max validfrom. (Check the first result in demo link)
In order to achieve above task, following query will work just fine!
SELECT t1.entrykey, t1.user_key, t2.maxdate as MaxDate
FROM t t1
inner join (select user_key,MAX(STR_TO_DATE(validfrom, '%Y-%c-%e')) as maxdate
            from t
            Group by user_key
            ) t2
on t1.user_key = t2.user_key and t1.validfrom = t2.maxdate;

Click here for Demo with DateTime as datatype of validfrom
Click here for Demo with STR_TO_DATE() function
Hope it helps!


Q: .htaccess Php rewrite url I try to realize a system of rewriting URLs in .htaccess.
Then here is my goal:
If I have an url of this form: http://localhost/view.php?Id=456
Then I want to transform it to: http://localhost/456
I use this rule in htaccess:
RewriteRule ^ ([a-zA-Z0-9] +) $ view.php? Id = $ 1
Now this works very well!
But my problem I want to add points to id ie instead of 456 I can put: my.book
That is to say: http://localhost/my.book

A: Try this:
RewriteRule ^([a-zA-Z0-9\.]+)$ view.php?Id=$1

Basically what I did is I added \. with your pattern. This will make sure your regex matches any letter (small/caps), decimal numbers and periods (.). Hope this helps :)

A: RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-zA-Z0-9\.]+)$ view.php?id=$1 [QSA,L]

You need RewriteCond %{REQUEST_FILENAME} !-f before the RewriteRule line to tell the server that the RewriteRule written below to be executed if the input passed in the URL is not an actual file. Because server searches for a file matching the input you pass in the URL and also it won't work in case you pass my.book in the URL since web server recognizes . as prefix for extension like .php or .html or like so and thereby it results in Not Found error if there is no file named my.book exists. So, you also need to escape . in the URL.
To allow .'s in the input, you need to add . with escape sequence \ in the character class group like ^([a-zA-Z0-9\.]+)$. Note, allowing this can result in escaping the extension in the URL, that is, passing view.php in the URL won't navigate to the actual file. Rather, it will be considered as a value in the query string.


Q: Google code downloading source This might be an extremely stupid question, but for the life of me, I cannot figure out how to download this:
http://code.google.com/p/xmppframework/source/browse/#hg%253Fstate%253Dclosed
There is nothing under the "downloads" tab. And when I try to "clone" it using my terminal it says "HG command not found".
Any ideas??

A: hg is the executable for Mercurial, you're going to need to download and install Mercurial.
Once you have it installed you can use it to clone the project:
hg clone https://xmppframework.googlecode.com/hg/ xmppframework


Q: How To classify Read and Unread news in Feed Reader? I am working on a RSS Feed module in WPF Application. I am getting news items in xml document from the httpWebResponse. I want to calssify the unread feeds. How can we identify the user read or Unread the news article ?

A: It depends on how the web pages linked by RSS feed are opened.
If they are opened within your app using a WebBrowser control, then you must track history of read feeds yourself within your app. See WPF WebBrowser Recent Pages.
You can use the Navigated event of the WebBrowser control.
If they are opened using a particular web browser, then you can eventually read somehow the history of that particular browser. But when the history gets deleted, your read/unread status gets deleted as well.


Q: How to invert the green channel of an image in Python? How do I invert one channel of an RGB image? In this case my image is a normal map for a 3D engine, saved in an image format like JPEG or TIFF, and I want to invert the green channel — that is, completely reverse the highs and lows in the green band.

A: You can accomplish this by installing and using Pillow, which can work with most image formats (JPEG, PNG, TIFF, etc.).
from PIL import Image
from PIL.ImageChops import invert

image = Image.open('test.tif')
red, green, blue = image.split()
image_with_inverted_green = Image.merge('RGB', (red, invert(green), blue))
image_with_inverted_green.save('test_inverted_green.tif')

After loading the image from your file, split into its channels with Image.split, invert the green channel/image with ImageChops.invert, and then join it together with the original red and blue bands into a new image with Image.merge.
If using a format that's encoded in something other than RGB (such as PNG, which has an additional transparency channel), the image-opening line can be amended to:
image = Image.open('test.png').convert('RGB')

Testing with this image:

Produces this:

(ImageChops, by the way, looks like a very odd term, but it's short for "image channel operations".)

A: I assume you have a numpy (or torch tensor) image - you can index on the green channel (assuming channels are your last dimension)
img[:, :, 1] = 255 - img[:, :, 1]

I am assuming by invert you want 0 -> 255 and 255 -> 0

A: T(r) = L – 1 – r

L=256

L-1=255(Max)

r=Each pixel of the image

s=255-r

s= T(r) =255-r


Q: PHP is ignoring code like var_dump(), die(), etc This is a very weird situation like I've never seen in my life.
For some reason PHP is ignoring a lot of code inside a static function.
Here is the example:
static function describe($tableName, $columns = '*') {
    var_dump($tableName);
    die();
    $md5 = ...code...
    if (!empty($content = Cache::get($md5))) {
        return unserialize($content);
    }

I keep getting the error
Parse error: syntax error, unexpected '=', expecting ')'

in
if (!empty($content = Cache::get($md5))) {

And yes it recognises the class Cache and its function.
Can anyone guide me?

A: Prior to PHP 5.5, empty() function can only support strings.
Any other input provided to it like: a function call e.g.
if (empty(myfunction()) {
 // ...
}

would result parse error.
As per documentation:

Note: Prior to PHP 5.5, empty() only supports variables; anything else
  will result in a parse error. In other words, the following will not
  work: empty(trim($name)). Instead, use trim($name) == false.

Better way, get your $content variable first and then check if it is not empty.
Rather than initialising it and checking its emptiness simultaneously.
You can separate the if statement in two parts like this:
if ($content = Cache::get($md5) && !empty($content)) {
 return unserialize($content);
}

A: Try this,
if (!empty($content) && $content = Cache::get($md5)) {
        return unserialize($content);
}

OR : To get easy readability
if (!empty($content){
   if($content = Cache::get($md5)){
       return unserialize($content);
   }
}


Q: Using graphql-codegen adds query to query? I'm trying to use graphql-codegen to add types to my graphql queries
I have this in my package.json
"@graphql-codegen/add": "^3.1.0",
"@graphql-codegen/cli": "^2.3.0",
"@graphql-codegen/typescript-operations": "^2.2.1",
"@graphql-codegen/typescript-react-apollo": "^3.2.2",

I have a codegen.yml
overwrite: true
schema: http://localhost:3000/api/graphql
documents: 'queries/*.ts'

generates:
  generated/index.tsx:

    config:
      reactApolloVersion: 3
      withHooks: false
    plugins:
      - "typescript"
      - "typescript-operations"
      - "typescript-react-apollo"

I'm using keystonejs which has a graphql api
My query is like
export const ALL_PRODUCTS_QUERY = gql`
    query ALL_PRODUCTS_QUERY{
    allProducts{
        id
        price
        description
        name
        photo{
        id
        image{
            publicUrlTransformed
        }
        }
    }
    }
`

And in my package.json I have
"codegen": "graphql-codegen --config codegen.yml"

If I run yarn codegen I get the types generated in generated/index.tsx
For ALL_PRODUCTS_QUERY I get
export type All_Products_QueryQuery = { __typename?: 'Query', allProducts?: Array<{ __typename?: 'Product', id: string, price?: number | null | undefined, description?: string | null | undefined, name?: string | null | undefined, photo?: { __typename?: 'ProductImage', id: string, image?: { __typename?: 'CloudinaryImage_File', publicUrlTransformed?: string | null | undefined } | null | undefined } | null | undefined } | null | undefined> | null | undefined };

Why does the Query get added to the name so its now All_Products_QueryQuery and why is it not an interface
I thought it would be an interface to describe the query


Q: Auto Align of button Hi
On our website I have a page where there are Buy Now buttons
https://www.nutricentre.com/m-300-herbs-hands-healing.aspx
The styling that controls this is
.item .price {
    color:#8c9c54;
    font-size:14px;
    font-weight: bold;
    /*
        position: absolute;
        bottom: 48px;
        left: 0px;
        width: 150px;
    */
    text-align: center;
    margin-bottom: 45px;
}

.item a.blue_btn {
    position: absolute;
    bottom: 10px;
    left: 15px;
    cursor: pointer;
}

Any idea how I can get this aligned in a straight line regardless of the text above?

A: You don't have to change the css of the button, but from the whole item:
just add:
.item{
    height: 380px;
}

Of course, you have to care about the maximum item-height: your value must not be less, or the price won't be visible anymore.
In this case, min-height would be the better alternative.

A: I would recommend setting a min-height: 370px; for the easiest solution.
You do not want to set a static height for this because if you have an item with a longer description it will not automatically add space but just cram everything in.

A: Add a static height to .item
height:375px;

The height:auto; declaration tells .item to expand as big as it needs to be to fit everything in, so the tops of the divs line up, but since they are different heights, the bottoms are staggered.
As some of my co-responders have noted, min-height is also an acceptable option, until you have an item with enough text that item expands past the min-height value, at which point they will begin to expand and stagger again.

A: This should point you in the right direction: http://jsfiddle.net/v9grm/
Create a grid and with the help of display: table make the columns the same height. Then place the button at the bottom of the column with position: absolute.