text:
Q: Broadcast Receiver in an IntentService I am trying to register the DownloadManager.ACTION_DOWNLOAD_COMPLETE receiver in onHandleIntent() method of my IntentService and unregistering the receiver in onDestroy() method of the IntentService. But I think its not getting registered, since the onReceive() method of the receiver is not getting triggered once the download is complete.
Can anyone help me with this?

A: Create service class,
public class ConnectionBroadReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        ConnectivityManager cm = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        IConnectionCallback callback = (IConnectionCallback) context;
        callback.finishDownload();
}

In Activity,
    ConnectionBroadReceiver broadReceiver = new ConnectionBroadReceiver();
    registerReceiver(broadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

Create Interface,and Implement in activity and define the function what you to do after downloading
    public interface IConnectionCallback {
     void finishDownload();

  }

And finaly register the service in manifest,
    <receiver android:name=".ConnectionBroadReceiver">

A: The code below is from here:
public class MyWebRequestService  extends IntentService{

public static final String REQUEST_STRING = "myRequest";
public static final String RESPONSE_STRING = "myResponse";
public static final String RESPONSE_MESSAGE = "myResponseMessage";

private String URL = null;
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;

public MyWebRequestService() {
    super("MyWebRequestService");
}

@Override
protected void onHandleIntent(Intent intent) {

    String requestString = intent.getStringExtra(REQUEST_STRING);
    String responseString = requestString + " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());
    String responseMessage = "";
    SystemClock.sleep(10000); // Wait 10 seconds
    Log.v("MyWebRequestService:",responseString );

    // Do some really cool here
    // I am making web request here as an example...
    try {

        URL = requestString;
        HttpClient httpclient = new DefaultHttpClient();
        HttpParams params = httpclient.getParams();

        HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
        ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);

        HttpGet httpGet = new HttpGet(URL);
        HttpResponse response = httpclient.execute(httpGet);

        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseMessage = out.toString();
        }

        else{
            //Closes the connection.
            Log.w("HTTP1:",statusLine.getReasonPhrase());
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }

    } catch (ClientProtocolException e) {
        Log.w("HTTP2:",e );
        responseMessage = e.getMessage();
    } catch (IOException e) {
        Log.w("HTTP3:",e );
        responseMessage = e.getMessage();
    }catch (Exception e) {
        Log.w("HTTP4:",e );
        responseMessage = e.getMessage();
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(MyWebRequestReceiver.PROCESS_RESPONSE);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra(RESPONSE_STRING, responseString);
    broadcastIntent.putExtra(RESPONSE_MESSAGE, responseMessage);
    sendBroadcast(broadcastIntent);

}

}
IntentFilter filter = new IntentFilter(MyWebRequestReceiver.PROCESS_RESPONSE);
    filter.addCategory(Intent.CATEGORY_DEFAULT);
    receiver = new MyWebRequestReceiver();
    registerReceiver(receiver, filter);

@Override
public void onDestroy() {
    this.unregisterReceiver(receiver);
    super.onDestroy();
}

public class MyWebRequestReceiver extends BroadcastReceiver{
    public static final String PROCESS_RESPONSE = "com.as400samplecode.intent.action.PROCESS_RESPONSE";
    @Override
    public void onReceive(Context context, Intent intent) {
        String responseString = intent.getStringExtra(MyWebRequestService.RESPONSE_STRING);
        String reponseMessage = intent.getStringExtra(MyWebRequestService.RESPONSE_MESSAGE);
        TextView myTextView = (TextView) findViewById(R.id.response);
        myTextView.setText(responseString);
        WebView myWebView = (WebView) findViewById(R.id.myWebView);
        myWebView.getSettings().setJavaScriptEnabled(true);
        try {
            myWebView.loadData(URLEncoder.encode(reponseMessage,"utf-8").replaceAll("\\+"," "), "text/html", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}

public class MyWebRequestService  extends IntentService{

public static final String REQUEST_STRING = "myRequest";
public static final String RESPONSE_STRING = "myResponse";
public static final String RESPONSE_MESSAGE = "myResponseMessage";

private String URL = null;
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;

public MyWebRequestService() {
    super("MyWebRequestService");
}

@Override
protected void onHandleIntent(Intent intent) {

    String requestString = intent.getStringExtra(REQUEST_STRING);
    String responseString = requestString + " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());
    String responseMessage = "";
    SystemClock.sleep(10000); // Wait 10 seconds
    Log.v("MyWebRequestService:",responseString );

    // Do some really cool here
    // I am making web request here as an example...
    try {

        URL = requestString;
        HttpClient httpclient = new DefaultHttpClient();
        HttpParams params = httpclient.getParams();

        HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
        ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);

        HttpGet httpGet = new HttpGet(URL);
        HttpResponse response = httpclient.execute(httpGet);

        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseMessage = out.toString();
        }

        else{
            //Closes the connection.
            Log.w("HTTP1:",statusLine.getReasonPhrase());
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }

    } catch (ClientProtocolException e) {
        Log.w("HTTP2:",e );
        responseMessage = e.getMessage();
    } catch (IOException e) {
        Log.w("HTTP3:",e );
        responseMessage = e.getMessage();
    }catch (Exception e) {
        Log.w("HTTP4:",e );
        responseMessage = e.getMessage();
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(MyWebRequestReceiver.PROCESS_RESPONSE);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra(RESPONSE_STRING, responseString);
    broadcastIntent.putExtra(RESPONSE_MESSAGE, responseMessage);
    sendBroadcast(broadcastIntent);

}

}
IntentFilter filter = new IntentFilter(MyWebRequestReceiver.PROCESS_RESPONSE);
    filter.addCategory(Intent.CATEGORY_DEFAULT);
    receiver = new MyWebRequestReceiver();
    registerReceiver(receiver, filter);

@Override
public void onDestroy() {
    this.unregisterReceiver(receiver);
    super.onDestroy();
}

public class MyWebRequestReceiver extends BroadcastReceiver{
    public static final String PROCESS_RESPONSE = "com.as400samplecode.intent.action.PROCESS_RESPONSE";
    @Override
    public void onReceive(Context context, Intent intent) {
        String responseString = intent.getStringExtra(MyWebRequestService.RESPONSE_STRING);
        String reponseMessage = intent.getStringExtra(MyWebRequestService.RESPONSE_MESSAGE);
        TextView myTextView = (TextView) findViewById(R.id.response);
        myTextView.setText(responseString);
        WebView myWebView = (WebView) findViewById(R.id.myWebView);
        myWebView.getSettings().setJavaScriptEnabled(true);
        try {
            myWebView.loadData(URLEncoder.encode(reponseMessage,"utf-8").replaceAll("\\+"," "), "text/html", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}

In Manifest Create service.


text:
Q: How to get the width of an svg:g element I am currently working with an svg element in JavaScript. And I am new to this.
My question is that I have an svg element in which I have multiple svg:g elements. And in my svg:g elements I have various other svg elements.
    <svg>
     <g class="my-class">
      <g class "c1">
         <text style="font-size: 9" x="0" y="-4"> john </text>
         <text style="font-size: 9" x="70" y="-4"> 13 </text>
      </g>
      <g class="c2">
         <text style="font-size: 9" x="0" y="-4"> john </text>
         <text style="font-size: 9" x="70" y="-4"> 13 </text>
      </g>
      <g class="c3">
         <text style="font-size: 9" x="0" y="-4"> john </text>
         <text style="font-size: 9" x="70" y="-4"> 13 </text>
      </g>
    </g>
   </svg>

g are dynamically appending in my

g "my_class"

Now I want to set my svg width equal to the width of g.my_class width.
var svgWidth  =   $('.my-class').width()
alert(svgWidth);

But its giving me zero. How ever I can see it on my browser in a yellow tool tip box
when I select this line.
Can anyone kindly guide me? Am I doing this right, or how can I achieve this?
Thanks

A: I'd recommend getBBox (which is part of SVG 1.1) over getBoundingClientRect (which isn't):
$('.my-class')[0].getBBox().width;

Demo http://jsfiddle.net/TAck4/

A: Try .getBoundingClientRect
$('.my-class')[0].getBoundingClientRect().width;

Demo http://jsfiddle.net/5DA45/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bind a combobox to another dataset than the datacontext in WPF Let me explain my challenge. I have a dataset with a datatable that is assigned to the datacontext. One of the fields is a category. All the category names are in another datatable (one to many relationship).
I want the combobox to display all the names in the categories datatable with the correct selected value from the datacontext datatable. So if I change category, datatable1 will be updated with the selectedValue from the combobox.
I read something about a ObjectDataProvider, but I didnt get it to work. How can I manage to get this to work?

A: Use like this
<UserControl x:Class="ButtonEffects.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300" Name="uc">
    <Grid>
                <ComboBox ItemsSource="{Binding ElementName=uc,Path=Categories}"
              DisplayMemberPath="CategoryName" SelectedValuePath="Id"
              SelectedValue="{Binding SelectedCategoryId}"/>
    </Grid>
</UserControl>

Categories being a property in you codebehind.The itemsouce will be populated from the categories table and your selectedvalue will be updated in your datacontext datatable.Hope this helps
EDIT
If your datacontext is a dataset then the selectedvalue should be like
SelectedValue="{Binding datatable1/SelectedCategoryId}"


text:
Q: How to retain the values of each element when each element of an array is object in json in java? I need to prepare a json file with this format:
    [{x: "0", y: a},{x: "1", y: b},{x: "2", y: c}]
I implemented the following technique with JSONObjects and JSONArray:
JSONArray ac=new JSONArray();
JSONObject acontent=new JSONObject();

acontent.put("x", "0");
acontent.put("y",a);
acontent.put("x", "1");
acontent.put("y",b);
acontent.put("x", "2");
acontent.put("y",c);

ac.add(acontent);

However I could only get this output,[{x: "2", y: c}]. How can I retain all the previous values of x and y?

A: There are far more elegant solutions than this, but the general idea is that you need 1 object for each element in the original array.
JSONArray ac=new JSONArray();
JSONObject acontent=new JSONObject();

acontent.put("x", "0");
acontent.put("y",a);
ac.add(acontent);
acontent = new JSONObject();

acontent.put("x", "1");
acontent.put("y",b);
ac.add(acontent);

acontent = new JSONObject();
acontent.put("x", "2");
acontent.put("y",c);

ac.add(acontent);


text:
Q: change textSize of each row on runtime while scrolling listview I have used a custom base adapter. I am trying to achieve telescopic view in list. I have an infinite listview.
 ArrayList<String> months=new ArrayList<>();
    months.add("January");
    months.add("February");
    months.add("March");
    months.add("April");
    months.add("May");
    months.add("June");
    months.add("July");
    months.add("August");
    months.add("September");
    months.add("October");
    months.add("November");
    months.add("December");

    CircularListAdapter circularListAdapter=new CircularListAdapter(new CircularBaseAdapterDatePickerMonth(getActivity(),months));

    monthList.setAdapter(circularListAdapter);

    monthList.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == 0) {

            }

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            int firstVisibleRow=monthList.getFirstVisiblePosition();
            int lastVisibleRow=monthList.getLastVisiblePosition();

        }
    });

    return view;

}

above is my main code
below is my adapter
/**
 * Created by user4 on 07-05-2016.
 */
public class CircularBaseAdapterDatePickerMonth extends BaseAdapter {

    Activity activity;
    ArrayList<String> items;

    public CircularBaseAdapterDatePickerMonth(Activity activity, ArrayList<String> items) {
        this.activity = activity;
        this.items = items;
    }

    @Override
    public int getCount() {

        return items.size();
    }

    @Override
    public String getItem(int position) {

        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        MyviewHolder myviewHolder;
        if (convertView != null) {
            myviewHolder = (MyviewHolder) convertView.getTag();
        } else {
            myviewHolder = new MyviewHolder();
            convertView = activity.getLayoutInflater().inflate(R.layout.custom_date_picker_dialog_list_text, parent, false);
            myviewHolder.textView = (TextView) convertView.findViewById(R.id.Onboarding_DateDialog_List_text);
            convertView.setTag(myviewHolder);
        }

        myviewHolder.textView.setText(items.get(position));

        return convertView;
    }

    static class MyviewHolder {
        TextView textView;
    }
}

I am not sure about the onScrollListener() too, whether it will help me or not.


text:
Q: how to deploy a MERN app on aws with different versions I was wondering how would i deploy different versions of my MERN app on aws.
For example lets say I have an initial deploy and want to deploy an updated version but still have access to the previous deployed version how would i do it?
I can deploy on AWS but want multiple versions of my deployed app incase there is an error in one version of my deployed app


text:
Q: WPF Change Background color of a Combobox In my WPF app I just want to change the background color of the Combo box. I don't mean the dropdown, I want is just whatever item is selected a background is set.
Like setting the background of a button - when the control is displayed on screen it should have LightYellow background. That's it.
 I searched a lot on net, but everywhere could find solutions for drop down background colors. I tried applying SolidColorBrush and Style.Triggers to the TextBlock of Combobox, but no success as wanted. By adding SolidColorBrush lines, I got my dropdown background set, but that's not what I am looking for. My code is :
<ComboBox ItemsSource="{Binding MtrCm}" SelectedValue="{Binding WellboreDiameter_Unit, Mode=TwoWay}" Grid.Row="1" Height="23" HorizontalAlignment="Right" Margin="0,26,249,0" x:Name="cboWellDiameter" VerticalAlignment="Top" Width="120"   Background="LightYellow"  >
    <ComboBox.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="Yellow" />
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Yellow" />
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Yellow" />
        <Style TargetType="TextBlock">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ComboBoxItem}}" Value="True">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Resources>
</ComboBox>

Can anyone help me set he background of the desired component that am looking for.
Thanks

A: Try this
 <Window.Resources>  //Put this resourse n Window.Resources or UserControl.Resources
   <LinearGradientBrush x:Key="NormalBrush" StartPoint="0,0" EndPoint="0,1">
      <GradientBrush.GradientStops>
         <GradientStopCollection>
            <GradientStop Color="#FFDC3939" Offset="0.0"/>
            <GradientStop Color="#FFE80E0E" Offset="1.0"/>
         </GradientStopCollection>
      </GradientBrush.GradientStops>
   </LinearGradientBrush>

    <SolidColorBrush x:Key="WindowBackgroundBrush" Color="#FFFBE618" />

    <ControlTemplate x:Key="ComboBoxToggleButton" TargetType="ToggleButton">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition Width="20" />
            </Grid.ColumnDefinitions>
            <Border x:Name="Border" Grid.ColumnSpan="2" CornerRadius="2"
  Background="{StaticResource NormalBrush}"
  BorderThickness="1" />
            <Border
  Grid.Column="0"
  CornerRadius="2,0,0,2"
  Margin="1"
  Background="{StaticResource WindowBackgroundBrush}"
  BorderThickness="0,0,1,0" />
            <Path
  x:Name="Arrow"
  Grid.Column="1"
  HorizontalAlignment="Center"
  VerticalAlignment="Center"
  Data="M 0 0 L 4 4 L 8 0 Z"/>
        </Grid>
    </ControlTemplate>

    <ControlTemplate x:Key="ComboBoxTextBox" TargetType="TextBox">
        <Border x:Name="PART_ContentHost" Focusable="False" Background="{TemplateBinding Background}" />
    </ControlTemplate>

<Style x:Key="{x:Type ComboBox}" TargetType="ComboBox">
  <Setter Property="Template">
   <Setter.Value>
     <ControlTemplate TargetType="ComboBox">
      <Grid>
       <ToggleButton
         Name="ToggleButton"
         Template="{StaticResource ComboBoxToggleButton}"
         Grid.Column="2"
         Focusable="false"
         IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"
         ClickMode="Press">
      </ToggleButton>
      <ContentPresenter
        Name="ContentSite"
        IsHitTestVisible="False"
        Margin="3,3,23,3"
        VerticalAlignment="Center"
        HorizontalAlignment="Left" />
       <TextBox x:Name="PART_EditableTextBox"
         Style="{x:Null}"
         Template="{StaticResource ComboBoxTextBox}"
         HorizontalAlignment="Left"
         VerticalAlignment="Center"
         Margin="3,3,23,3"
         Focusable="True"
         Background="Transparent"
         Visibility="Hidden"
         IsReadOnly="{TemplateBinding IsReadOnly}"/>
      <Popup
        Name="Popup"
        Placement="Bottom"
        IsOpen="{TemplateBinding IsDropDownOpen}"
        AllowsTransparency="True"
        Focusable="False"
        PopupAnimation="Slide">
        <Grid
          Name="DropDown"
          SnapsToDevicePixels="True"
          MinWidth="{TemplateBinding ActualWidth}"
          MaxHeight="{TemplateBinding MaxDropDownHeight}">
           <Border
            x:Name="DropDownBorder"
            Background="{StaticResource WindowBackgroundBrush}"
            BorderThickness="1"/>
           <ScrollViewer Margin="4,6,4,6" SnapsToDevicePixels="True">
            <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
           </ScrollViewer>
          </Grid>
         </Popup>
        </Grid>
       </ControlTemplate>
      </Setter.Value>
     </Setter>
    <Style.Triggers>
   </Style.Triggers>
  </Style>
 </Window.Resources>
 <Grid>
    <ComboBox HorizontalAlignment="Left" Margin="256,57,0,0" VerticalAlignment="Top" Width="120">
    </ComboBox>

 </Grid>

Here is the complete style that you can change : http://msdn.microsoft.com/en-us/library/ms752094%28v=VS.85%29.aspx

A: While I like the accepted answer the problem I have with it is the text box presenter was completely missed and thus you can select and stylize things but they will never be presented to the end user.  I think the easiest way to achieve a combo-box that shows data and then when chosen displays it would be this:
<Window http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Test" x:Class="MainWindow"
        mc:Ignorable="d" Title="MainWindow" Height="100" Width="200">
  <Window.Resources>
    <Style x:Key="ComboBoxTest2" TargetType="{x:Type ComboBox}">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="ComboBox">
            <Grid>
              <ToggleButton Grid.Column="2" Focusable="false" IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}" >
                <ToggleButton.Template>
                  <ControlTemplate>
                    <Grid>
                      <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="5*" />
                        <ColumnDefinition Width="*" />
                      </Grid.ColumnDefinitions>
                      <Border x:Name="Border"  Grid.ColumnSpan="2" CornerRadius="5" Background="Beige" BorderBrush="Black" BorderThickness="1" />
                      <Border Grid.Column="0" CornerRadius="5,0,0,5"  Margin="1"  Background="AliceBlue"  BorderBrush="Black" BorderThickness="0,0,1,0" />
                      <Path x:Name="Arrow" Grid.Column="1"  Fill="Orange" HorizontalAlignment="Center" VerticalAlignment="Center" Data="M 0 0 L 4 4 L 8 0 Z"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                      <Trigger Property="ToggleButton.IsMouseOver" Value="true">
                        <Setter TargetName="Border" Property="Background" Value="Green" />
                      </Trigger>
                      <Trigger Property="ToggleButton.IsChecked" Value="true">
                        <Setter TargetName="Border" Property="Background" Value="Green" />
                      </Trigger>
                    </ControlTemplate.Triggers>
                  </ControlTemplate>
                </ToggleButton.Template>
              </ToggleButton>
              <ContentPresenter Name="ContentSite" IsHitTestVisible="False"  Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" Margin="3"  />
              <TextBox x:Name="PART_EditableTextBox" Visibility="Hidden" IsReadOnly="{TemplateBinding IsReadOnly}"/>
              <Popup Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True"  Focusable="False" PopupAnimation="Slide">
                <Grid  Name="DropDown" SnapsToDevicePixels="True" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}">
                  <Border x:Name="DropDownBorder" Background="Blue" />
                  <ScrollViewer SnapsToDevicePixels="True">
                    <StackPanel IsItemsHost="True" />
                  </ScrollViewer>
                </Grid>
              </Popup>
            </Grid>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
      <Style.Triggers>
      </Style.Triggers>
    </Style>
  </Window.Resources>
  <StackPanel Margin="10">
    <ComboBox VerticalAlignment="Top" Width="120" Style="{StaticResource ComboBoxTest2}">
      <ComboBoxItem>Item1</ComboBoxItem>
      <ComboBoxItem>Item2</ComboBoxItem>
    </ComboBox>
  </StackPanel>
</Window>

The key parts of the presentation needed to be done is the template 'ToggleButton.Template' for the initial display.  I chose to ignore making more brushes and links to more templates and just do it all inline so others could play with it as needed.  I also chose what I thought were easily Identifiable colors to just jump to for reference it should look like below when it works:

A: If you are using VS 2012 or VS 2013 in the Document Outline window while viewing your xaml get the control template of a combobox.
Find the style x:Key="ComboBoxReadonlyToggleButton"  and update the RenderMouseOver = "False" and RenderPressed="False" on the Themes:ButtonChrome and also comment out the trigger that affects IsEnabled.

Below is the one on I edited on my box to illustrate what I mean.
<Style x:Key="ComboBoxReadonlyToggleButton" TargetType="{x:Type ToggleButton}">
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="IsTabStop" Value="false"/>
        <Setter Property="Focusable" Value="false"/>
        <Setter Property="ClickMode" Value="Press"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToggleButton}">
                    <Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderMouseOver="False" RenderPressed="False" SnapsToDevicePixels="true">
                        <Grid HorizontalAlignment="Right" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}">
                            <Path x:Name="Arrow" Data="{StaticResource DownArrowGeometry}" Fill="Black" HorizontalAlignment="Center" Margin="3,1,0,0" VerticalAlignment="Center"/>
                        </Grid>
                    </Themes:ButtonChrome>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="true">
                            <Setter Property="RenderPressed" TargetName="Chrome" Value="False"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <!--<Setter Property="Fill" TargetName="Arrow" Value="#AFAFAF"/>-->
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

A: It is possible to put a TextBlock onto the combobox, but the TextBlock should be smaller than the ComboBox so that the drop down button is not hidden. In the TextBlock the desired background color can easily be set. When the selected item in the ComboBox changes, the text block has to be updated.
XAML code:
<ComboBox x:Name="TestComboBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="145"
          Margin="35, 5, 0, 0" SelectionChanged="TestComboBox_SelectionChanged"/>
<TextBlock x:Name="TestTextBlock" Text="" HorizontalAlignment="Left" VerticalAlignment="Top"
           Margin="36, 6, 0, 0" Padding="4,1" Width="126" Height="20">
  <TextBlock.Background>
    <SolidColorBrush Color="Yellow"/>
  </TextBlock.Background>
</TextBlock>

C# code:
private void TestComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  ComboBoxItem cbi = (ComboBoxItem)TestComboBox.SelectedItem;
  if (cbi != null)
  {
    TestTextBlock.Text = cbi.Content.ToString();
  }
  else TestTextBlock.Text = "";
}

A: On windows 8 or 10 this is proper WPF way without redesign the Combobox and 100% customizable.
Just copy paste and test! :)
Click here to see how look the ComboBox
  <Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Test_Combo_Custom"
    xmlns:Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero2" x:Class="Test_Combo_Custom.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">

<Window.Resources>
    <Style x:Key="FocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <SolidColorBrush x:Key="ComboBox.Static.Background" Color="Yellow"/>
    <SolidColorBrush x:Key="ComboBox.MouseOver.Background" Color="#FFFF0C00"/>
    <SolidColorBrush x:Key="ComboBox.Static.Border" Color="#FFACACAC"/>
    <SolidColorBrush x:Key="ComboBox.Static.Editable.Background" Color="#FFFB0F0F"/>
    <SolidColorBrush x:Key="ComboBox.Static.Editable.Border" Color="#FFABADB3"/>
    <SolidColorBrush x:Key="ComboBox.Static.Editable.Button.Background" Color="Transparent"/>
    <SolidColorBrush x:Key="ComboBox.Static.Editable.Button.Border" Color="Transparent"/>
    <SolidColorBrush x:Key="ComboBox.MouseOver.Glyph" Color="#FF000000"/>
    <SolidColorBrush x:Key="ComboBox.MouseOver.Border" Color="#FF7EB4EA"/>
    <SolidColorBrush x:Key="ComboBox.MouseOver.Editable.Background" Color="#FF88E00A"/>
    <SolidColorBrush x:Key="ComboBox.MouseOver.Editable.Border" Color="#FF7EB4EA"/>
    <SolidColorBrush x:Key="ComboBox.MouseOver.Editable.Button.Background" Color="#FF7EB4EA"/>
    <SolidColorBrush x:Key="ComboBox.MouseOver.Editable.Button.Border" Color="#FF7EB4EA"/>
    <SolidColorBrush x:Key="ComboBox.Pressed.Glyph" Color="#FF000000"/>
    <SolidColorBrush x:Key="ComboBox.Pressed.Background" Color="#FF000000"/>
    <SolidColorBrush x:Key="ComboBox.Pressed.Border" Color="#FF569DE5"/>
    <SolidColorBrush x:Key="ComboBox.Pressed.Editable.Background" Color="#FF00FFC5"/>
    <SolidColorBrush x:Key="ComboBox.Pressed.Editable.Border" Color="#FF569DE5"/>
    <SolidColorBrush x:Key="ComboBox.Pressed.Editable.Button.Background" Color="#FF569DE5"/>
    <SolidColorBrush x:Key="ComboBox.Pressed.Editable.Button.Border" Color="#FF569DE5"/>
    <SolidColorBrush x:Key="ComboBox.Disabled.Glyph" Color="#FFBFBFBF"/>
    <SolidColorBrush x:Key="ComboBox.Disabled.Background" Color="#FF101AEC"/>
    <SolidColorBrush x:Key="ComboBox.Disabled.Border" Color="#FFD9D9D9"/>
    <SolidColorBrush x:Key="ComboBox.Disabled.Editable.Background" Color="#FFC91355"/>
    <SolidColorBrush x:Key="ComboBox.Disabled.Editable.Border" Color="#FFBFBFBF"/>
    <SolidColorBrush x:Key="ComboBox.Disabled.Editable.Button.Background" Color="Transparent"/>
    <SolidColorBrush x:Key="ComboBox.Disabled.Editable.Button.Border" Color="Transparent"/>
    <SolidColorBrush x:Key="ComboBox.Static.Glyph" Color="#FF606060"/>

    <Style x:Key="ComboBoxToggleButton2" TargetType="{x:Type ToggleButton}">
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="IsTabStop" Value="false"/>
        <Setter Property="Focusable" Value="false"/>
        <Setter Property="ClickMode" Value="Press"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToggleButton}">
                    <Border x:Name="templateRoot" BorderBrush="{StaticResource ComboBox.Static.Border}" BorderThickness="{TemplateBinding BorderThickness}" Background="{StaticResource ComboBox.Static.Background}" SnapsToDevicePixels="true">
                        <Border x:Name="splitBorder" BorderBrush="Transparent" BorderThickness="1" HorizontalAlignment="Right" Margin="0" SnapsToDevicePixels="true" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}">
                            <Path x:Name="arrow" Data="F1 M 0,0 L 2.667,2.66665 L 5.3334,0 L 5.3334,-1.78168 L 2.6667,0.88501 L0,-1.78168 L0,0 Z" Fill="{StaticResource ComboBox.Static.Glyph}" HorizontalAlignment="Center" Margin="0" VerticalAlignment="Center"/>
                        </Border>
                    </Border>
                    <ControlTemplate.Triggers>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}" Value="true"/>
                                <Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="false"/>
                                <Condition Binding="{Binding IsPressed, RelativeSource={RelativeSource Self}}" Value="false"/>
                                <Condition Binding="{Binding IsEnabled, RelativeSource={RelativeSource Self}}" Value="true"/>
                            </MultiDataTrigger.Conditions>
                            <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource ComboBox.Static.Editable.Background}"/>
                            <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource ComboBox.Static.Editable.Border}"/>
                            <Setter Property="Background" TargetName="splitBorder" Value="{StaticResource ComboBox.Static.Editable.Button.Background}"/>
                            <Setter Property="BorderBrush" TargetName="splitBorder" Value="{StaticResource ComboBox.Static.Editable.Button.Border}"/>
                        </MultiDataTrigger>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter Property="Fill" TargetName="arrow" Value="{StaticResource ComboBox.MouseOver.Glyph}"/>
                        </Trigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="true"/>
                                <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}" Value="false"/>
                            </MultiDataTrigger.Conditions>
                            <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource ComboBox.MouseOver.Background}"/>
                            <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource ComboBox.MouseOver.Border}"/>
                        </MultiDataTrigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="true"/>
                                <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}" Value="true"/>
                            </MultiDataTrigger.Conditions>
                            <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource ComboBox.MouseOver.Editable.Background}"/>
                            <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource ComboBox.MouseOver.Editable.Border}"/>
                            <Setter Property="Background" TargetName="splitBorder" Value="{StaticResource ComboBox.MouseOver.Editable.Button.Background}"/>
                            <Setter Property="BorderBrush" TargetName="splitBorder" Value="{StaticResource ComboBox.MouseOver.Editable.Button.Border}"/>
                        </MultiDataTrigger>
                        <Trigger Property="IsPressed" Value="true">
                            <Setter Property="Fill" TargetName="arrow" Value="{StaticResource ComboBox.Pressed.Glyph}"/>
                        </Trigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding IsPressed, RelativeSource={RelativeSource Self}}" Value="true"/>
                                <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}" Value="false"/>
                            </MultiDataTrigger.Conditions>
                            <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource ComboBox.Pressed.Background}"/>
                            <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource ComboBox.Pressed.Border}"/>
                        </MultiDataTrigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding IsPressed, RelativeSource={RelativeSource Self}}" Value="true"/>
                                <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}" Value="true"/>
                            </MultiDataTrigger.Conditions>
                            <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource ComboBox.Pressed.Editable.Background}"/>
                            <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource ComboBox.Pressed.Editable.Border}"/>
                            <Setter Property="Background" TargetName="splitBorder" Value="{StaticResource ComboBox.Pressed.Editable.Button.Background}"/>
                            <Setter Property="BorderBrush" TargetName="splitBorder" Value="{StaticResource ComboBox.Pressed.Editable.Button.Border}"/>
                        </MultiDataTrigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Fill" TargetName="arrow" Value="{StaticResource ComboBox.Disabled.Glyph}"/>
                        </Trigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding IsEnabled, RelativeSource={RelativeSource Self}}" Value="false"/>
                                <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}" Value="false"/>
                            </MultiDataTrigger.Conditions>
                            <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource ComboBox.Disabled.Background}"/>
                            <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource ComboBox.Disabled.Border}"/>
                        </MultiDataTrigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding IsEnabled, RelativeSource={RelativeSource Self}}" Value="false"/>
                                <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}" Value="true"/>
                            </MultiDataTrigger.Conditions>
                            <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource ComboBox.Disabled.Editable.Background}"/>
                            <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource ComboBox.Disabled.Editable.Border}"/>
                            <Setter Property="Background" TargetName="splitBorder" Value="{StaticResource ComboBox.Disabled.Editable.Button.Background}"/>
                            <Setter Property="BorderBrush" TargetName="splitBorder" Value="{StaticResource ComboBox.Disabled.Editable.Button.Border}"/>
                        </MultiDataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <ControlTemplate x:Key="ComboBoxTemplate" TargetType="{x:Type ComboBox}">
        <Grid x:Name="templateRoot" SnapsToDevicePixels="true">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Width="0"/>
            </Grid.ColumnDefinitions>
            <Popup x:Name="PART_Popup" AllowsTransparency="true" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" Margin="1" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Placement="Bottom">
                <Themes:SystemDropShadowChrome x:Name="shadow" Color="Transparent" MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{Binding ActualWidth, ElementName=templateRoot}">
                    <Border x:Name="dropDownBorder" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">
                        <ScrollViewer x:Name="DropDownScrollViewer">
                            <Grid x:Name="grid" RenderOptions.ClearTypeHint="Enabled">
                                <Canvas x:Name="canvas" HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                    <Rectangle x:Name="opaqueRect" Fill="{Binding Background, ElementName=dropDownBorder}" Height="{Binding ActualHeight, ElementName=dropDownBorder}" Width="{Binding ActualWidth, ElementName=dropDownBorder}"/>
                                </Canvas>
                                <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            </Grid>
                        </ScrollViewer>
                    </Border>
                </Themes:SystemDropShadowChrome>
            </Popup>
            <ToggleButton x:Name="toggleButton" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.ColumnSpan="2" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ComboBoxToggleButton2}"/>
            <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" Content="{TemplateBinding SelectionBoxItem}" ContentStringFormat="{TemplateBinding SelectionBoxItemStringFormat}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" IsHitTestVisible="false" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
        </Grid>
        <ControlTemplate.Triggers>
            <Trigger Property="HasDropShadow" SourceName="PART_Popup" Value="true">
                <Setter Property="Margin" TargetName="shadow" Value="0,0,5,5"/>
                <Setter Property="Color" TargetName="shadow" Value="#71000000"/>
            </Trigger>
            <Trigger Property="HasItems" Value="false">
                <Setter Property="Height" TargetName="dropDownBorder" Value="95"/>
            </Trigger>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsGrouping" Value="true"/>
                    <Condition Property="VirtualizingPanel.IsVirtualizingWhenGrouping" Value="false"/>
                </MultiTrigger.Conditions>
                <Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
            </MultiTrigger>
            <Trigger Property="ScrollViewer.CanContentScroll" SourceName="DropDownScrollViewer" Value="false">
                <Setter Property="Canvas.Top" TargetName="opaqueRect" Value="{Binding VerticalOffset, ElementName=DropDownScrollViewer}"/>
                <Setter Property="Canvas.Left" TargetName="opaqueRect" Value="{Binding HorizontalOffset, ElementName=DropDownScrollViewer}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
    <SolidColorBrush x:Key="TextBox.Static.Background" Color="#FFFFFFFF"/>
    <Style x:Key="ComboBoxEditableTextBox" TargetType="{x:Type TextBox}">
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="AllowDrop" Value="true"/>
        <Setter Property="MinWidth" Value="0"/>
        <Setter Property="MinHeight" Value="0"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <ScrollViewer x:Name="PART_ContentHost" Background="Transparent" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <ControlTemplate x:Key="ComboBoxEditableTemplate" TargetType="{x:Type ComboBox}">
        <Grid x:Name="templateRoot" SnapsToDevicePixels="true">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Width="0"/>
            </Grid.ColumnDefinitions>
            <Popup x:Name="PART_Popup" AllowsTransparency="true" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Placement="Bottom">
                <Themes:SystemDropShadowChrome x:Name="shadow" Color="Transparent" MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{Binding ActualWidth, ElementName=templateRoot}">
                    <Border x:Name="dropDownBorder" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">
                        <ScrollViewer x:Name="DropDownScrollViewer">
                            <Grid x:Name="grid" RenderOptions.ClearTypeHint="Enabled">
                                <Canvas x:Name="canvas" HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                    <Rectangle x:Name="opaqueRect" Fill="{Binding Background, ElementName=dropDownBorder}" Height="{Binding ActualHeight, ElementName=dropDownBorder}" Width="{Binding ActualWidth, ElementName=dropDownBorder}"/>
                                </Canvas>
                                <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            </Grid>
                        </ScrollViewer>
                    </Border>
                </Themes:SystemDropShadowChrome>
            </Popup>
            <ToggleButton x:Name="toggleButton" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.ColumnSpan="2" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ComboBoxToggleButton2}"/>
            <Border x:Name="border" Background="{StaticResource TextBox.Static.Background}" Margin="{TemplateBinding BorderThickness}">
                <TextBox x:Name="PART_EditableTextBox" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsReadOnly="{Binding IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}" Margin="{TemplateBinding Padding}" Style="{StaticResource ComboBoxEditableTextBox}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
            </Border>
        </Grid>
        <ControlTemplate.Triggers>
            <Trigger Property="IsEnabled" Value="false">
                <Setter Property="Opacity" TargetName="border" Value="0.56"/>
            </Trigger>
            <Trigger Property="IsKeyboardFocusWithin" Value="true">
                <Setter Property="Foreground" Value="Black"/>
            </Trigger>
            <Trigger Property="HasDropShadow" SourceName="PART_Popup" Value="true">
                <Setter Property="Margin" TargetName="shadow" Value="0,0,5,5"/>
                <Setter Property="Color" TargetName="shadow" Value="#71000000"/>
            </Trigger>
            <Trigger Property="HasItems" Value="false">
                <Setter Property="Height" TargetName="dropDownBorder" Value="95"/>
            </Trigger>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsGrouping" Value="true"/>
                    <Condition Property="VirtualizingPanel.IsVirtualizingWhenGrouping" Value="false"/>
                </MultiTrigger.Conditions>
                <Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
            </MultiTrigger>
            <Trigger Property="ScrollViewer.CanContentScroll" SourceName="DropDownScrollViewer" Value="false">
                <Setter Property="Canvas.Top" TargetName="opaqueRect" Value="{Binding VerticalOffset, ElementName=DropDownScrollViewer}"/>
                <Setter Property="Canvas.Left" TargetName="opaqueRect" Value="{Binding HorizontalOffset, ElementName=DropDownScrollViewer}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
    <Style x:Key="ComboBoxStyleCustom" TargetType="{x:Type ComboBox}">
        <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
        <Setter Property="Background" Value="{StaticResource ComboBox.Static.Background}"/>
        <Setter Property="BorderBrush" Value="{StaticResource ComboBox.Static.Border}"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
        <Setter Property="Padding" Value="6,3,5,3"/>
        <Setter Property="ScrollViewer.CanContentScroll" Value="true"/>
        <Setter Property="ScrollViewer.PanningMode" Value="Both"/>
        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
        <Setter Property="Template" Value="{StaticResource ComboBoxTemplate}"/>
        <Style.Triggers>
            <Trigger Property="IsEditable" Value="true">
                <Setter Property="IsTabStop" Value="false"/>
                <Setter Property="Padding" Value="2"/>
                <Setter Property="Template" Value="{StaticResource ComboBoxEditableTemplate}"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<Grid>
    <ComboBox HorizontalAlignment="Left" Margin="317.429,194.428,0,0" VerticalAlignment="Top" Width="120" Style="{DynamicResource ComboBoxStyleCustom}">
        <ComboBox.Resources>
            <!-- color of ComboBoxItem -->
            <SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="#FF17FF00" />
        </ComboBox.Resources>
        <ComboBoxItem>One</ComboBoxItem>
        <ComboBoxItem>Two</ComboBoxItem>
        <ComboBoxItem>Three</ComboBoxItem>
    </ComboBox>

</Grid>
</Window>

A: Just add the following to your ComboBox style :)
BasedOn="{StaticResource {x:Type ComboBox}}"

Example:
<Style TargetType="ComboBox" BasedOn="{StaticResource {x:Type ComboBox}}">
    <Setter Property="Background" Value="Red" />
    //Other setters, triggers, etc...
</Style>

Believe me, it's probably the shortest way to do it... I don't see why we have to completely re-define the ComboBox template.


text:
Q: Javascript: selecting values from a dropdown I had a standard calculation javascript and now I need to add-in multiple calculations based on a user-selected value - can't seem to get it to work....!  Any chance someone could have a look and tell me where I'm going wrong???
<script type="text/javascript">
function calculate() {
  var noPeople = document.ContactForm.noPeople.value;
  var ddl = document.getElementById("menuType");
  var selectedValue = ddl.options[ddl.selectedIndex].value;
  var noPeople_excess = (noPeople-6);

  if (selectedValue == 3)  {
    var basic = 337;
    var marchCost = (50*noPeople);
    if (marchCost <= basic)         {
      document.ContactForm.marchCost.value = 337;
      document.ContactForm.marchCostVin.value = basic +(noPeople*25)
    } else {
      document.ContactForm.marchCost.value = basic +(noPeople_excess*34);
      document.ContactForm.marchCostVin.value = basic +(noPeople_excess*34)+(noPeople*25)
    }
  } else (selectedValue == 4)  {
    var basic = 368;
    var marchCost = (55*noPeople);
    if (marchCost <= basic) {
      document.ContactForm.marchCost.value = 368;
      document.ContactForm.marchCostVin.value = basic +(noPeople*25)
    } else {
      document.ContactForm.marchCost.value = basic +(noPeople_excess*44);
      document.ContactForm.marchCostVin.value = basic +(noPeople_excess*44)+(noPeople*25)
    }
  } else (selectedValue == 5) {
    var basic = 419;
    var marchCost = (60*noPeople);
    if (marchCost <= basic) {
      document.ContactForm.marchCost.value = 419;
      document.ContactForm.marchCostVin.value = basic +(noPeople*25)
    } else {
      document.ContactForm.marchCost.value = basic +(noPeople_excess*54);
      document.ContactForm.marchCostVin.value = basic +(noPeople_excess*54)+(noPeople*25)
    }
  }
}
</script>

A: This question was indeed many times answered, however here is a simple solution for you:
    //get select value and assing to an input element
function setValue(selectId, elemId) {
    var thisID = selectId,
    valueSelected = document.getElementById(thisID).value
    console.log(thisID + ' has value of ' + valueSelected);
    document.getElementById(elemId).value = valueSelected;
}

http://plnkr.co/edit/rnenKVaNcJ9RhqLzUaWi
regards.

A: I might be confused about the two DDLs, but either the selected value should be the selectedIndex to compare with integers:
var selectedValue = ddl.selectedIndex;

or the conditions should be checking strings:
if (selectedValue == "3"){

A: your elses are missing an if.. eg: else if (selectedvalue==4)
I suggest using switch(selectedvalue) { case 3: ... break; case 4: ...etc
would be easier to read in this case, especially if you add more options.


text:
Q: symfony Jms error argument 2 passed must be an instance of Doctrine\Common\Persistence\ManagerRegistry I have this error when trying to deserialize JSON data:

Uncaught Error: Argument 2 passed to
JMS\Serializer\Metadata\Driver\AbstractDoctrineTypeDriver::__construct()
must be an instance of Doctrine\Common\Persistence\ManagerRegistry,
instance of Doctrine\Bundle\DoctrineBundle\Registry given,   called in
/var/www/mda-api/var/cache/prod/ContainerXJGxuAr/getJmsSerializer_MetadataDriverService.php
on line 13

$result = $this->serializer->deserialize(
    $encoder->encode($jsonContent,'json'),
    Client::class,
    "json",
);

Does anyone have any idea why this error happen?


text:
Q: How to generate a 0-1 sequence according to different probabilities efficiently? I want to get a random 0-1 sequence. Now I generate the number one by one. My code is as follows:
p_arr = [0.1, 0.5, 0.3, 0.8]
seq = []
for pb in p_arr:
  seq.append(np.random.choice(2, 1, p=[1-pb, pb]))

It's very time-consuming when the length of p_arr is very large (i.e. 10000). I wonder if there is another faster way to do this.

A: If you want to use Numpy, do:
Try it online!
import numpy as np
p_arr = [0.1, 0.5, 0.3, 0.8]
seq = (np.random.rand(len(p_arr)) > p_arr).astype(np.uint8)
print(seq)

If you don't want to use Numpy then you can still make your code simpler:
Try it online!
import random
p_arr = [0.1, 0.5, 0.3, 0.8]
seq = []
for pb in p_arr:
  seq.append(1 if random.random() > pb else 0)
print(seq)

Also notice that in both cases I thought that your p_arr contains probability of 0 (not 1). If you want to inverse logic, then replace > with < in both of my codes.


text:
Q: 2D array not printing out in grid/not full array? The issue I'm having is that the 2D array is not printing out everything in the array, and when I run the evolve method, it doesn't print out the 2D array the same as the first time. Wondering what's wrong to make it not print out the entire array, and not print the array the same way when the evolve method runs? Each print out of the array needs to be in a 25x75 grid
Desired initial result:

Actual result:

evolve method result:

Project 4:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

public class Project4 {

    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in); // Created a scanner
        System.out.println("Enter the file name you would like to use");
        File file = new File(input.nextLine()); // Takes file name to find file
        Scanner inputFromFile = new Scanner(file);
        FileInputStream fileInput = new FileInputStream(file); // reads file
        int r;
        int y = 0;
        int i = 0;
        while ((r = fileInput.read()) != -1) { // goes through each character in
                                                // file, char by char
            char c = (char) r;
            GameOfLife.grid[i][y] = c;
            y++;
            if (y == 75) {
                y = 0;
                i++;
                if (i == 25) {
                    break;
                }
            }
        }
        // Prints the initial environment
        System.out.println("Initial set: ");
        for (int j = 0; j < GameOfLife.grid.length; j++) {
            System.out.print(GameOfLife.grid[j]);
        }
        boolean operate = true;
        while (operate = true) {
            System.out.println("Do you want to see the next generation? Y/N?");
            String q = input.nextLine();
            if (q.equalsIgnoreCase("y")) {
                GameOfLife.evolve();
                for (int j = 0; j < GameOfLife.grid.length; j++) {
                    System.out.print(GameOfLife.grid[j]);
                    operate = true;
                }
            } else {
                operate = false;
                System.exit(0);
            }
        }
    }
}

GameOfLife:
import java.util.Arrays;

public class GameOfLife {

    static final int m = 25; // number of rows
    static final int n = 75; // number of columns
    static char[][] grid = new char[m][n]; // Creates an empty (no dots or
                                            // X's)grid of rows and columns.

    static int count_neighbors(int i, int j) {
        int nn = 0; // number of neighbors of cell(i,j)

        if (i > 0 && j > 0 && grid[i - 1][j - 1] == 'X') {
            nn++;
        }
        ;
        if (i > 0 && grid[i - 1][j] == 'X') {
            nn++;
        }
        ;
        if (i > 0 && j < 72 && grid[i - 1][j + 1] == 'X') {
            nn++;
        }
        ;
        if (j > 0 && grid[i][j - 1] == 'X') {
            nn++;
        }
        ;
        if (j < 72 && grid[i][j + 1] == 'X') {
            nn++;
        }
        ;
        if (j > 0 && i < 22 && grid[i + 1][j - 1] == 'X') {
            nn++;
        }
        ;
        if (i < 22 && grid[i + 1][j] == 'X') {
            nn++;
        }
        ;
        if (i < 22 && j < 72 && grid[i + 1][j + 1] == 'X') {
            nn++;
        }

        return nn;
    }

    static void evolve() {
        for (int i = 0; i < 23; i++) {
            for (int j = 0; j < 73; j++) {
                int s = count_neighbors(i, j);
                if (s < 2) {
                    grid[i][j] = '.';
                }
                if (s == 2 || s == 3) {
                    grid[i][j] = 'X';
                }
                if (s > 3) {
                    grid[i][j] = '.';
                }
            }

        }

    }

}

A: Add a System.out.println() after each for-loop to start printing the grid on the next line.
// Print out grid.length characters
for (int j = 0; j < GameOfLife.grid.length; j++) {
    System.out.print(GameOfLife.grid[j]);
}
// Print a new line
System.out.println();

Updated
The problem I failed to notice above is that you are printing an entire row in one line, and the whole grid in one (visible) loop. The following System.out.println() would therefore print a blank line after the entire grid is printed. Please see my solution which extracts out the printing of the game, uses a try-catch for the file reader, and removes the unnecessary operate variable at the bottom since you were just exiting anyway.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class Project4 {

    private static void printGame() {
        for (char[] row : GameOfLife.grid) {
            for (char c : row) {
                System.out.print(c);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in); // Created a scanner
        System.out.println("Enter the file name you would like to use");
        File file = new File(input.nextLine()); // Takes file name to find file
        BufferedReader br = null;
        String line;
        int i = 0;

        try {
            br = new BufferedReader(new FileReader(file));
            while ((line = br.readLine()) != null) {
                for (int col = 0; col < line.length(); col++) {
                    GameOfLife.grid[i][col] = line.charAt(col);
                }
                i++;
                if (i == 25) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                br.close();
            }
        }

        // Prints the initial environment
        System.out.println("Initial set: ");
        printGame();

        while (true) {
            System.out.println("Do you want to see the next generation? Y/N?");
            String q = input.nextLine();
            if (q.equalsIgnoreCase("y")) {
                GameOfLife.evolve();
                printGame();
            } else {
                System.exit(0);
            }
        }
    }
}

A: I think you should try using println this in both places like this:
System.out.println(GameOfLife.grid[j]);

System.out.print() is not flushed automatically, it's only flushed when a newline is written.  This means that rather than writing out everything, it might buffer the IO to keep things more efficient.


text:
Q: SQL Server recursive CTE and paging I have this table
 CREATE TABLE [dbo].[friend_blocked_list](
 [subdomain] [varchar](50) NOT NULL,
 [un] [nvarchar](50) NOT NULL,
 [friend] [nvarchar](50) NOT NULL,
 [is_blocked] [bit] NOT NULL,
 [approved] [bit] NOT NULL)

where i select data from it with below query. Select query combines users that added user as friend and users that have been added as friend by user
declare @un varchar(50), @subdomain varchar(50)

set @un='user2';
set @subdomain ='test.domain.com';

WITH FRIENDS as
(
  SELECT friend
  FROM friend_blocked_list
  WHERE un=@un and subdomain=@subdomain and approved=1 and is_blocked=0

  UNION ALL

  SELECT un as friend
  FROM friend_blocked_list
  WHERE friend=@un and subdomain=@subdomain and approved=1 and is_blocked=0
)
select friend from FRIENDS group by FRIENDS.friend order by FRIENDS.friend asc

It works fine with small amout of data but i want to be able to do a paging on the server side in order to reduce load. I am trying to combine it with my paging sp below
create PROCEDURE [dbo].[Paging]
    @subdomain varchar(50),
    @un varchar(50),
    @PageNumber int,
    @PageSize int
AS
BEGIN
   --paging
   DECLARE @FirstRow INT,@LastRow INT,@RowCount INT,@PageCount INT

   --find recordcount and pages
   SELECT @RowCount = COUNT(*), @PageCount = COUNT(*) / @PageSize
   FROM friend_blocked_list
   WHERE subdomain=@subdomain AND un=@un AND approved=1 AND is_blocked=0;

   --- calculate pages
   IF @RowCount % @PageSize != 0 SET @PageCount = @PageCount + 1
   IF @PageNumber < 1 SET @PageNumber = 1
   IF @PageNumber > @PageCount SET @PageNumber = @PageCount

   SELECT
        CurrentPage = @PageNumber,
        TotalPages = @PageCount,
        TotalRows = @RowCount

   -- mora calculation
   SELECT @FirstRow = ( @PageNumber - 1) * @PageSize + 1,
          @LastRow = (@PageNumber - 1) * @PageSize + @PageSize ;

   WITH MyTopics  AS
   (
      SELECT *, ROW_NUMBER() OVER (order by un asc) AS RowNumber
      FROM friend_blocked_list
      WHERE subdomain=@subdomain AND un=@un AND approved=1 AND is_blocked=0
   )
   SELECT *
   FROM MyTopics
   WHERE RowNumber BETWEEN @FirstRow AND @LastRow
   ORDER BY RowNumber ASC;
end

But as always i am having trouble :). Main problem is the UNION ALL in my query. It prevents me using ROW_NUMBER() OVER.
Any ideas?

A: Here's your procedure updated for paging:
CREATE PROCEDURE [dbo].[Paging]
  @subdomain varchar(50),
  @un varchar(50),
  @PageNumber int,
  @PageSize int
AS

  DECLARE @start_row int
  DECLARE @end_row int

  SET @end_row = @PageNumber * @PageSize
  SET @start_row = @end_row - (@PageSize - 1)

BEGIN

  WITH FRIENDS AS (
    SELECT t.friend
      FROM FRIEND_BLOCKED_LIST t
     WHERE t.un = @un
       AND t.subdomain = @subdomain
       AND t.approved = 1
       AND t.is_blocked = 0
   UNION ALL
    SELECT t.un as friend
      FROM FRIEND_BLOCKED_LIST t
     WHERE t.friend = @un
       AND t.subdomain = @subdomain
       AND t.approved = 1
       AND t.is_blocked = 0)
SELECT t.friend
  FROM (SELECT f.friend,
               ROW_NUMBER() OVER (ORDER BY f.friend) AS rownum
          FROM FRIENDS f
      GROUP BY f.friend) t
 WHERE t.rownum BETWEEN @start_row AND @end_row

END

It might be possible to change the query to use one CTE if you could provide more information on the FRIEND_BLOCKED_LIST table.  The UNION of two queries with identical WHERE clauses while differentiating between two columns makes me wonder if it couldn't be written better.  Could the FRIENDS CTE be rewritten as:
SELECT COALESCE(t.un, t.friend) as friend
  FROM FRIEND_BLOCKED_LIST t
 WHERE @un = COALESCE(t.un, t.friend)
   AND t.subdomain = @subdomain
   AND t.approved = 1
   AND t.is_blocked = 0

A: Apply the row number to the list you want to return:
WITH FRIENDS as
(
SELECT friend
  FROM friend_blocked_list
  WHERE un=@un and subdomain=@subdomain and approved=1 and is_blocked=0
UNION ALL
SELECT un as friend
  FROM friend_blocked_list
  WHERE friend=@un and subdomain=@subdomain and approved=1 and is_blocked=0 )
, recursive_friends as  (
select friend
 , row_number() over (order by friend asc) as rn
from FRIENDS )
select friend
  from recursive_friends
  where rn between @firstRow and @lastRow
  order by FRIENDS.friend asc;


text:
Q: Undesired newline (LF) after execution of PHP script on AWS I've a simple PHP script called from an AJAX function.  To check if the script was successful i'm doing something like this:
$http({
      url: '/xxxx.php',
      method: "GET",
      params: {yyy: zzz}
    })
    .success(function(data) {
      if (data!="") { // if success
             ...........

The problem is that on my local server all works fine, but when I upload the scripts to my AWS servers, the execution of PHP scripts always add a LF (newline or \n) at the end of the file, and all my JS scripts fail because the data string is not empty.
I've checked the data string and data has a LF (ASCII code 10) at first position, so the JS 'if check' (data!="") always fails.
Anyone knows why the PHP script adds a LF at the end on AWS, but the same script works fine on my local stack? I don't wanna change all my conditional JS checks, so I like to remove the LF attached at the end of the PHP output, but changing the ¿PHP/APACHE/SERVER? configuration itself, not modifiying the script files.
Thanks in advance!


text:
Q: jQuery validation not validating proper on submit event I am usinng jQuery validation plugin, and have used so many times for form validating but facing this issue first time and don't understand why not validating.
Issue: When I click first time on submit button, form validation not appering but When I hit second time validation message appears.
jQuery Code:
$(document).ready(function() {
    $(document.body).on('submit', 'form#register-form', function(event) {
        event.preventDefault();
        $("#register-form").validate({

            // Specify the validation rules
            rules : {
                firstname : "required",
                lastname : "required"
            },

            // Specify the validation error messages
            messages : {
                firstname : "Please enter your first name",
                lastname : "Please enter your last name"
            }
        });
    });
});

HTML Code:

Register here

<form action="#" method="post" id="register-form">

        First Name

    <input type="text" id="firstname" name="firstname" />

        Last Name

    <input type="text" id="lastname" name="lastname" />

        <input type="submit" name="submit" value="Submit" />

</form>

JSFiddle: http://jsfiddle.net/mananpatel/68vgh7x1/1/
Any idea where I am doing wrong.

A: In your case you are initializing the validation plugin only when the first submit is done, so the plugin is not getting called during the first submit operation.
You need to initialize the validation plugin out of the submit handler. Instead of using your own submit handler you can use the submitHandler option provided by the validation framework to submit the form - it will be called only of the form is valid. else in the submit handler you will have to check whether the form is valid.

 $("#register-form").validate({

     // Specify the validation rules
     rules: {
         firstname: "required",
         lastname: "required"
     },

     // Specify the validation error messages
     messages: {
         firstname: "Please enter your first name",
         lastname: "Please enter your last name"
     },

     submitHandler: function(){
         //do your form submit here
         return false;
     }
 });

Register here

<form action="#" method="post" id="register-form">

First Name

    <input type="text" id="firstname" name="firstname" />

Last Name

    <input type="text" id="lastname" name="lastname" />

        <input type="submit" name="submit" value="Submit" />

</form>

A: You are calling method onsubmit. Instead of this validate is called on DOM ready.
Have a look at this :
http://jsfiddle.net/68vgh7x1/3/
 $("#register-form").validate({
        // Specify the validation rules
        rules: {
            firstname: "required",
            lastname: "required"
        },

        // Specify the validation error messages
        messages: {
            firstname: "Please enter your first name",
            lastname: "Please enter your last name"
        }
    });

A: $(document).ready(function() {
    $("#register-form").validate({

        // Specify the validation rules
        rules : {
            firstname : "required",
            lastname : "required"
        },

        // Specify the validation error messages
        messages : {
            firstname : "Please enter your first name",
            lastname : "Please enter your last name"
        }
    });
    // adding submit event is unnecessary.
});

A: If you're using HTML5, I suggest using the element properties:
required="true"

http://jsfiddle.net/sud6L2bn/
Source: http://jqueryvalidation.org/files/demo/
PS: consider using the label element for labelling fields.


text:
Q: How to modify the innerHTML of a contenteditable element I'm using Selenium with Chrome-driver and python3.6 to test a website.
I have code snippet in the webpage as follow:

Type a message

*******

I want to replace the ******* with Hello World! using Selenium in the webpage. How do I do that ?

A: To replace the text ******* with the text Hello World! as the element is a React element and having the attribute contenteditable="true" you need to induce WebDriverWait for the element to be clickable and you can use either of the following solutions:

*

*Using CSS_SELECTOR:
  element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.copyable-text.selectable-text[data-tab='1']")))
  element.click()
  element.clear()
  element.send_keys("Hello World!")

*Using XPATH:
  element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class,'selectable-text')][contains(.,'*******')]")))
  element.click()
  element.clear()
  element.send_keys("Hello World!")

*Note: You have to add the following imports :
  from selenium.webdriver.support.ui import WebDriverWait
  from selenium.webdriver.common.by import By
  from selenium.webdriver.support import expected_conditions as EC


text:
Q: Representing softmax mathematically I have softmax as follows:
$$\sigma(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}} \text{ for } i = 1, \dotsc , K \text{ and } \mathbf z=(z_1,\dotsc,z_K) \in\mathbb{R}^K$$
As borrowed from Wikipedia.
I have a tensor of dimension $100 \times 100 \times 256$, let's call this $\mathcal{X}$. I have a variable that I have to denote just as $\mathbf{x}_{i,j} \in \mathcal{X}$ - I can't use triple indices. I am doing a channel-wise softmax using python. However, I'd also like to write this mathematically but unsure how to represent this along the depth dimension. Here's my attempt at it:
$$\sigma(\mathbf{x}_{i,j}) = \frac{e^{\mathbf{x}_{i,j,k'}}}{\sum_{k=1}^{256}{e^{\mathbf{x}_{i,j,k}}}}$$ where $1 \leq k' \leq 256$.
Is this proper notation or does it not have the intended understanding?


text:
Q: Generating sequences in MongoDB using PHP-Lib I am porting an old PHP application from the legacy Mongo DB code to the current mongoDB library version. For invoice generation, I require a sequence. Previously I used:
db.system.js.save(
{
    _id: "getNextSequence",
    value: function (client, id) {
       var ret = db.counter.findAndModify(
            {
                query: {client: client, id: id},
                update: {$inc: {seq: 1}},
                new: true
            }
        );

        return ret.seq;
    }
});

And from PHP side:
$getNextSequence = new MongoCode("getNextSequence('$client', 'invoices')");
$ret = $this->db->execute($getNextSequence);
$nextId = $ret['retval'];

Unfortunately this is no longer possible as the MongoCode class is no longer around. And frankly, the documentation on MongoDB PHP Library is useless.
Question:
How can I either
a) call this Javascript from PHP using the new MongoDB PHP Library or
b) find a different way to increase the sequence and fetch the updated number at the same time

A: $collection = $this->db->counter;
$ret = $collection->findOneAndUpdate(
    array("client" => $client, "id" => "invoices"),
    array('$inc' => array("seq" => 1)),
    array("new" => true, "upsert" => true)
);
$nextId = $ret->seq;

Works nicely, except for the very first insert, in which case MongoDB provides an empty $id. Improvement ideas are welcome.


text:
Q: Should i use an auto-increment primary key although i already have a UNIQUE column? Is there any reason to use id int auto-increment for a primary key while a UNIQUE column (that is not a foreign key or anything) already exists in a table?
I'm reading someone else's thesis about a project that uses freebase data.
Every topic in freebase is uniquely identified by an mid. (example: m.gugkl395).
But instead of using mid as the primary key in the topics table he chose to use an id (int auto-increment). So the topics table looks like this
CREATE TABLE topics (
id INT NOT NULL AUTO-INCREMENT,
mid VARCHAR(254) NOT NULL UNIQUE,
name VARCHAR(254) NOT NULL,
description VARCHAR(2048),
type VARCHAR(254) NOT NULL,
PRIMARY KEY (id)
);

I should mention that there are 3 other tables that use this id as a foreign key and that because it has to do with freebase there will probably be a lot of data in the database. Also in case it matters MySQL version 5.7.15 is being used.

A: Theoretically,IMHO after 26+ years from dbaseIII+, if you have a Unique key, you can use it, auto increment field just simplify the things if you are not sure about uniqueness.
Practically, Regarding actual programming and performance of the database, you need to add multiple lines of code to create the primary key value and some times require connections to the server to get the last value of the key before the new one, these plus the space used by varchar in the design of the tables may affect the performance of the solution and take more time in programming.
I hope this may help.

A: The m.gugkl395 is the RDF encoding of MID which looks like /m/gugkl395 in its native form, but the prefix is constant and the gugkl395 is a radix 32(?) encoding of an integer. The most space efficient and performant schema would be to just store that integer.
The MID encoding is described in an earlier answer of mine here: https://stackoverflow.com/a/56012791/167425


text:
Q: css uikit grid component: text overlapping in div in Google Chrome I am working on the following web page using the uikit grid component to display books/journal subscriptions:
http://booktest.ersnet.org/PublicationsSubscriptions/
Everything looks fine in Firefox and Internet Explorer. But with Google Chrome I have an issue with the display of the descriptions of the items. Description texts are overlapping into the other columns.
I already searched on the web and tried solving the problem by using some css tricks as: display:block; overflow:hidden; clear:both;
With no success at the moment.
I would be very grateful if anyone can help me with this.

A: wrap your text in a div and put a width of 90%

     your text is here

A: What you need is to set the word-wrap attribute to break-word.
Example:
*{
    word-wrap: break-word;
}


text:
Q: React native initalRouteName not working with Stack Navigation I am new to react-native and I am trying to implement a simple application using StackNavigation and react-redux with welcome and signup screens. I have configured both the screens using StackNavigation but for some reasons , only the SignUp screen pops up when the app starts. Below are my files :
Index.js
import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('MyApp', () => App);

App.js
import React, { Component } from 'react';
import { Provider, connect } from "react-redux";
import { addNavigationHelpers } from "react-navigation";
import StackNavConfig from "./js/config/routes";
import getStore from "./js/store";

const AppNavigator = StackNavConfig;

const initialState = AppNavigator.router.getActionForPathAndParams('Welcome');

const navReducer = (state = initialState, action) => {
    const newState = AppNavigator.router.getStateForAction(action, state);
    return newState || state;
};

const AppWithNavigationState = connect(state => ({
    nav: state.nav,
}))(({ dispatch, nav }) => (
    <AppNavigator navigation={addNavigationHelpers({ dispatch, state: nav })} />
));

const store = getStore(navReducer);

class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <AppWithNavigationState />
      </Provider>
    );
  }
}

export default App;

js/config/routes.js
import Welcome from "../components/Welcome/view/Welcome";
import SignUp from "../components/SignUp/view/SignUp";
import { StackNavigator } from "react-navigation";

const Routes = {
    Welcome: { screen: Welcome , path: ''},
    SignUp: { screen: SignUp , path : '/signup'},
};

const RoutesConfig = {
    initialRouteName: 'Welcome',
    headerMode: 'none',
};

export default StackNavConfig = StackNavigator(Routes, RoutesConfig);

store.js
import { createStore, applyMiddleware } from "redux";

import thunk from "redux-thunk";
import getRootReducer from "./reducers/index";

export default function getStore(navReducer) {
    const store = createStore(
        getRootReducer(navReducer),
        undefined,
        applyMiddleware(thunk)
    );

    return store;
}

Below are my components
Welcome.js
import React from 'react';
import {
  View,
  Image} from 'react-native';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as welcomeActions from "../actions/WelcomeActions";
import { welcomeStyles } from '../styles/WelcomeStyles';

class Welcome extends React.Component {

  constructor(){
    super();
    this.state = {  };
  }

  render(){
    return (
      <View style = {welcomeStyles.mainContainer}>
         <Text>Welcome</Text>
      </View>
    );
  }
}

export default connect(
  state => ({

  }),
  dispatch => bindActionCreators(welcomeActions, dispatch)
)(Welcome);

SignUp.js
import React from 'react';
import {
  View,
  Image} from 'react-native';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as welcomeActions from "../actions/SignUpActions";
import { signUpStyles } from '../styles/SignUpStyles';

class Welcome extends React.Component {

  constructor(){
    super();
    this.state = {  };
  }

  render(){
    return (
      <View style = {signUpStyles.mainContainer}>
         <Text>SignUp</Text>
      </View>
    );
  }
}

export default connect(
  state => ({

  }),
  dispatch => bindActionCreators(signUpActions, dispatch)
)(SignUp);

I also have action and reducer files for each of my component.But they are blank as of now , since I haven't yet implemented the redux part.I am combining the reducers as below.
import { combineReducers } from "redux";
import welcomeReducer from "../components/Welcome/reducers/WelcomeReducer";
import signUpReducer from "../components/SignUp/reducers/SignUpReducer";

export default function getRootReducer(navReducer) {
    return combineReducers({
        nav: navReducer,
        welcomeReducer : welcomeReducer,
        signUpReducer : signUpReducer,
    });
}

As mentioned before , even after setting the initialRouteName to Welcome in my routes.js , the SignUp screen appears first everytime I launch the app. Please help

A: I found out what was the issue. I was calling this.props.navigate inside the render function by mistake which was causing the navigation to different screen.


text:
Q: How does the equation of time period of a simple pendulum change in a very high gravitational field I want to calculate the time period of oscillation of a simple pendulum in a planet with a very high gravity. In classical mechanics where time is absolute, the time period of a simple pendulum is $$T=2\pi\sqrt{\frac{l}{g}}$$
Where $g$ is the acceleration due to gravity. But in relativistic mechanics, we know that time is not absolute. So how will this change the equation of time period of simple pendulum?

A: T is in the frame of reference of the pendulum so the formula stands. If you want to compare different time dilations in different frames of reference that could be a different matter.


text:
Q: Declare Data Table on handlebars template i have recently started using handlerbar.js in my projects and it seems quite interesting.So far so good, but im struggling in creating dynamic data grids using a template.
i have following json
gridrow: [
    { col1: 'a', col2: 'b', col3: 'c' },
    { col1: 'd', col2: 'e', col3: 'f' },
    { col1: 'g', col2: 'h', col3: 'i' }
]

when I create template

{{#each gridrow}}

        {{col1}}
        {{col2}}
        {{col3}}

{{/each}}

when I declare datatable for table dt_scroll show error
$invoice_preview.html(theCompiledHtml);
$invoice_form.html('');
$window.resize();
$dt_scroll = $('#dt_scroll');
console.log($dt_scroll.length);
if ($dt_scroll.length) {
    $('#dt_scroll').DataTable({
        "scrollY": "200px",
        "scrollCollapse": false,
        "paging": false
    });
}

A: I assume the problem is that the browser tries to parse the
. When you try that, it will fail. {{#each gridrow}} is not allowed as a first child of a table.
To fix this, simply put your template in a script tag. I also fixed here your HTML because it wasn't valid for the DataTable plugin

Now the JavaScript code has to look similar to something like this.
var context = {title: "My New Post", gridrow: [
    { col1: 'a', col2: 'b', col3: 'c' },
    { col1: 'd', col2: 'e', col3: 'f' },
    { col1: 'g', col2: 'h', col3: 'i' }
]}

// compile the template
var html = Handlebars.compile($('#dt_scroll').html())(context)

// setting the compiled html
var $invoice_preview = $('#invoice_preview')
$invoice_preview.html(html)

// start the plugin
$invoice_preview.find(">:first-child").DataTable({
  "scrollY": "200px",
  "scrollCollapse": false,
  "paging": false
})


text:
Q: Typescript coverage seems incorrect with tsc It seems that the coverage is not correct with the function that I'd like to test :
public isSelfTweet = function(tweet: Tweet, twitterScreenName: string) {
    if(null == tweet || null == tweet.user || null == tweet.user.screen_name) {
        return false;
    }
    if(tweet.user.screen_name.toLowerCase() === twitterScreenName) {
        return true;
    }
    return false;
}

I write three tests and I have a 100% coverage :

*

*tweet = null, twitterScreenName = "toto"

*tweet with screen_name = "toto", twitterScreenName = "toto"

*tweet with screen_name = "toto", twitterScreenName = "tutu"

Here is the coverage which seems incorrect for me. I never have tested tweet not null, but tweet.user null for instance

In my package json :
"nyc": "^11.2.1",

A: What exactly do you think is not working?
When I try the following in Typescript Playground, the test works. By the way, you can't call isSelfTweet with null since you declare it has to be Tweet...
interface Tweet {
    user:User
}

interface User {
    screen_name:string
}

class Test {
    public isSelfTweet(tweet: Tweet, twitterScreenName: string) : boolean {
        if (tweet.user) {
            if (tweet.user.screen_name) {
                if (tweet.user.screen_name.toLowerCase() === twitterScreenName) {
                    return true;
                }
            }
        }
        return false;
    }
}

let t = new Test()
let tweet = { user: {screen_name:"willy"}}

let test1 = t.isSelfTweet(tweet, "willy")
console.log(test1)   // returns true

let test2 = t.isSelfTweet(tweet, "wally")
console.log(test2)   // returns false


text:
Q: ZXING Android Embedded Usage of IntentIntegrator I am new to Android development and still trying to get the grasp of some of the concepts. I find the best way to learn is to jump right into the deep end with a project.  With that said, here is my question:
I have integrated ZXing Android Embedded into my application; however, I am having trouble understanding the way in which you use IntentIntegrator.  All I am trying to do at the moment is call the QR scanner to the screen when the user taps a button.  I have been trying to follow the instructions on their github link [here][1] but have been unsuccessful.
Here is what my function looks like so far:
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            IntentIntegrator integrator = new IntentIntegrator(this);
            IntentIntegrator.forFragment(this).initiateScan();

        }

    });

I keep getting an error saying:

Error:(109, 25) error: constructor IntentIntegrator in class
  IntentIntegrator cannot be applied to given types; required: Activity
  found: Intent reason: actual argument Intent cannot be converted to
  Activity by method invocation conversion

Also, as I put my mouse over '(this)' in Android Studio, it says:

anonymous android.view.View.onClickListener

Any help would be greatly appreciated, thanks!  If you need any other information, please let me know.

A: An even easier solution than ChrisStillwell´s would be to make your activity-/fragment-class implement the OnClickListener, this way you do not need the reference variable:
public class SomeFragment extends Fragment implements View.OnClickListener {
    // Rest of your code

    @Override
    public void onClick(View v) {

         if (v.getId == button.getId) {
              IntentIntegrator integrator = new IntentIntegrator(getActivity());
              IntentIntegrator.forFragment(this).initiateScan();
         }
    }
}

If you are implementing a fragment-class, note that you have to call getActivity() when creating the IntentIntegrator.

A: You are referencing your OnClickListener and not your Fragment when you say this inside your onClick. You need to reference your Fragment, the easiest way to do that is setup a global variable and call it myFragment or something to your liking, then assign it this. For example:
Fragment myFragment = this;

public void myFunction(){
    // Code and stuff //
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            IntentIntegrator integrator = new IntentIntegrator(this);
            IntentIntegrator.forFragment(myFragment).initiateScan();
        }
    });
}

A: following can work:
btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new IntentIntegrator(getActivity()).initiateScan();
                popupWindow.dismiss();

            }
        });


text:
Q: SearchBar in UINavigationItem I added a search bar in the UINavigationItem using the following code:
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
[searchBar sizeToFit];
searchBar.delegate = self;
self.navigationItem.titleView = searchBar;
self.navigationItem.title = self.category.title;
[searchBar release];

but the result UI is like this:

How can I change the color of the search bar and make it the same with the background of the navigation bar?
Thanks.

A: For a UINavigationBar there is multiple ways to manipulate background color of it:

*

*Set a tintColor property to a color that you need.

*Follow proposed way of modification to apply custom gradient or other pattern image — http://leonov.co/2011/04/uinavigationbar-and-uitoolbar-customization-ultimate-solution/
For a search bar tintColor is also available. But in your case I suggest to inherit form UISearchBar and provide implementation as shown below to get rid from background drawing routine totally. In this case you will get search bar on an transparent toolbar and will and you will need to manage only UINavigationBar color.
//TransparentSearchBar.m

@interface TransparentSearchBar()
- (void)removeBackgroundView;
@end

@implementation TransparentSearchBar

- (id)init
{
    self = [super init];

    if(self) {
        [self removeBackgroundView];
    }

    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];

    if(self) {
        [self removeBackgroundView];
    }

    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if(self) {
        [self removeBackgroundView];
    }

    return self;
}

- (void)removeBackgroundView
{
    for (UIView *view in self.subviews)
    {
        if ([view isKindOfClass:NSClassFromString
             (@"UISearchBarBackground")])
        {
            [view removeFromSuperview];
            break;
        }
    }
}

@end

A: If you see the documentation on UISearchBar it has the property "tintColor".
Set that to color of the navigation bar.
If you do not know the color of navigationbar, get the tintColor of navigationBar.
You might also want to lay with the "translucent" property of the searchbar. Might work better.


text:
Q: Which model would fit the original data given these ACF and PACF plots? Given the following plots, I am confused as to which model would fit the best. Also, I am not sure how to incorporate the first difference ACF/PACF plots in the answer.
You can find the plots here


text:
Q: How to remove a shared preference I want to remove a shared preference created while registering my user in register activity
the code used to save the shared preference in RegisterActivity file is :
spf = getSharedPreferences(MyPref,0);
    SharedPreferences.Editor editor=spf.edit();
    editor.putString(name, txtfullname.getText().toString()); //name is a key which will help to identify.. abhi tera name is null.. its jus a variable now no key identifying value in it..
    editor.putString(age, txtage.getText().toString());//same for other two i.e age and ph_no these must b string keys
    editor.putString(ph_no, txtmobileno.getText().toString());
    editor.putString(email, txtemailid.getText().toString());
    editor.putString(password, txtpasskey.getText().toString());
    if(radio1.isChecked())
    {
        flag="Male";
    }
    else
    {
        flag="Female";
    }
    editor.putString(gender,flag);
    editor.putString(spinner_text, spinnertext);
    editor.commit();

now i want to remove this preference saved above
and i am using this code in my another activity:
SharedPreferences pref = getPreferences(0);
        SharedPreferences.Editor editoer = pref.edit();
        editoer.clear();
        editoer.commit();
        finish();

But i am not able to delete it this way , any suggestions what should i do ?

A: Use this code

SharedPreferences myPrefs =
v.getContext().getSharedPreferences(MyPref,Context.MODE_PRIVATE)
SharedPreferences.Editor editor = myPrefs.edit();
editor.clear();
editor.commit();

A: Replace SP by ""
SharedPreferences.Editor editor=spf.edit();
    editor.putString(name, ""); //name is a key which will help to identify.. abhi tera name is null.. its jus a variable now no key identifying value in it..
    editor.putString(age, "");//same for other two i.e age and ph_no these must b string keys
    editor.putString(ph_no, "");
    editor.putString(email, "");
    editor.putString(password, "");
    editor.putString(gender,"");
    editor.putString(spinner_text,"");
    editor.commit();

A: You are getting wrong preferences, your preference name is "MyPref" than you have to get than preference name and clear that preference, for ex:
SharedPreferences pref = getPreferences(MyPref,0);
Editor editoer = pref.edit();
editoer.clear();
editoer.commit();

A: Once you have the SharedPreference.Editor object, you could easily delete the key-pair value by calling the remove() method with the key as argument.
editor.remove(String key);
editor.apply();


text:
Q: Swift Error : 'DYLD_BOOL' is not convertible to 'bool' I am developing a simple tableview based application where If user touch at any cell then he will navigate to the DetailViewController and when user click on DetailViewController he goes back to the tableView for that I use:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.dismissViewControllerAnimated(TRUE, completion: nil)
}

But I can not use true in small later and that line give me error like:
'DYLD_BOOL' is not convertible to 'bool'

What is the solution for this?

A: Just use true, instead of TRUE.


text:
Q: timeout --> command not found in linux server I am using linux server from cPanel. Now I need to use one of the linux command to run. And the command is 'timeout'. My command is something as below
$timeout 2s ./myexecutable < input > output

This is just running ok in my linux machine. But I want to run it in server(linux). But it is not running out there. I saw error log using 2>$1 . and it says command not found.
So how do I specify the path. That means how can I know the exact path to run it.
I am very new to this type of server stuff, so please don't be rude :D.. whatever you know please help me to get out of it.
thank you

A: On Mac, you can use gtimeout from the coreutils package. To install it, run
brew install coreutils

If you need the command to be called "timeout" then you can alias it.
alias timeout="gtimeout"


text:
Q: How to delete replace in a word that have been repeated three or more times I am working with text data for pre-processing. The letters of some words are repeated and I have to correct them.

For example the following sentence:
sentence = 'likeeeee sooooo looovvve hmmmmmmm'

Must change to:
sentence = 'like so love hm'

Can anyone help?

A: You can use regex and lookaheads, like this. Feel free to ask any questions and I'll try my best to help.
import re

s = 'likeeeee sooooo looovvve hmmmmmmm'
print(re.sub(r"(.)(?=\1)","",s))

A: You could use a regular expression.
import re

sentence = 'likeeeee sooooo looovvve hmmmmmmm'

for m in re.findall(r"(\w)\1{2,}", sentence):
    s = m + m
    while s in sentence:
        sentence = sentence.replace(s, m)

print(sentence)

Output
like so love hm


text:
Q: Update logic for data integration I really need help in finding logic for my script for updating :(
I have a SQL Server database with customer data with ModifiedDate column. And I am moving this data to Odoo using External API with exactly the same columns.
My script will run every day and take the new data from the SQL Server database and add it to Odoo; it has to update those customers which have changed also.
For creating, I am taking max(CreateDate) and using it in the query to take customers after it.
But I am not able to find a good solution for update. Any help?
PS: as data is pretty big, I need to find the fastest solution :( Thanks!

A: I have found a solution.
I will do one time fetch to the data. And then take today as a parameter and use in the query as:
where ModifiedDate > today

If anybody has a better idea, please share :) Thanks :)