text:
Q: Android Studio retrieve information from XML in a override method Sorry for the noob question but I did not come across any situations that would work for me. Im sure this is super simple, I just need to be pointed in the right direction.
Objective:
I want to be able to take the name of what the user specified and add it to the markers title.
What I know:
I am unable to inflate the xml and grab it via that way cause the method is being override and if I inflate to my knowledge will no longer allow me to override the method. How should I approach this?
MapsAcitivy
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, addPlace.Communicator {

    private GoogleMap mMap;
    public static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 0;
    int mStackLevel;
    int YES_NO_CALL;
    FragmentManager manager = getSupportFragmentManager();
    final Context context = this;

    @InjectView(R.id.btn_login) Button _loginButton;

    ClusterManager<ClusterRequest> mClusterManager;

    class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

        // These are both viewgroups containing an ImageView with id "badge" and two TextViews with id
        // "title" and "snippet".
        private final View mWindow;

        //private final View mContents;

        CustomInfoWindowAdapter() {
            mWindow = getLayoutInflater().inflate(R.layout.info_window_layout, null);
            //mContents = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
        }

        @Override
        public View getInfoWindow(Marker marker) {
            render(marker, mWindow);
            return mWindow;
        }

        @Override
        public View getInfoContents(Marker marker) {
            // Getting view from the layout file info_window_layout
            View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);

            // Getting the position from the marker
            LatLng latLng = marker.getPosition();

            // Getting reference to the TextView to set latitude
            TextView tvLat = (TextView) v.findViewById(R.id.tv_lat);

            // Getting reference to the TextView to set longitude
            TextView tvLng = (TextView) v.findViewById(R.id.tv_lng);

            // Setting the latitude
            tvLat.setText("Latitude:" + latLng.latitude);

            // Setting the longitude
            tvLng.setText("Longitude:"+ latLng.longitude);

            // Returning the view containing InfoWindow contents
            return v;
            //render(marker, mContents);
            //return mContents;
        }

        private void render(Marker marker, View view) {
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    @TargetApi(23)
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSION_ACCESS_FINE_LOCATION);

                // MY_PERMISSION_ACCESS_FINE_LOCATION is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
            LocationManager initialLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            String initialProvider = initialLocationManager.getBestProvider(criteria, true);
            Location initialLocation = initialLocationManager.getLastKnownLocation(initialProvider);
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            double initialLatitude = initialLocation.getLatitude();
            double initialLongitude = initialLocation.getLongitude();
            LatLng initialLatLng = new LatLng(initialLatitude, initialLongitude);
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(initialLatLng, 14.9f));
            //mMap.setOnInfoWindowClickListener(this);
            mClusterManager = new ClusterManager<ClusterRequest>(getApplicationContext(), mMap);
            mMap.setOnCameraChangeListener(mClusterManager);
            mMap.setOnMarkerClickListener(mClusterManager);
        }
    }

    public void onButtonClick(View view){
        //do something when button is clicked.
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.add_place);
        dialog.setTitle("Add Place");

        Button btnLogin = (Button) dialog.findViewById(R.id.addPlacebtnSubmit);
        Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
        final EditText txtUsername = (EditText)dialog.findViewById(R.id.txtStopName);

        // Attached listener for add place GUI button
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String stopName = txtUsername.getText().toString();
                if(stopName.length() > 4){
                    // Here, thisActivity is the current activity
                    if (ContextCompat.checkSelfPermission(MapsActivity.this,
                            android.Manifest.permission.ACCESS_FINE_LOCATION)
                            != PackageManager.PERMISSION_GRANTED) {

                        // Should we show an explanation?
                        if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this,
                                android.Manifest.permission.ACCESS_FINE_LOCATION)) {

                            // Show an expanation to the user *asynchronously* -- don't block
                            // this thread waiting for the user's response! After the user
                            // sees the explanation, try again to request the permission.

                        } else {

                            // No explanation needed, we can request the permission.

                            ActivityCompat.requestPermissions(MapsActivity.this,
                                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                                    MY_PERMISSION_ACCESS_FINE_LOCATION);

                            // MY_PERMISSION_ACCESS_FINE_LOCATION is an
                            // app-defined int constant. The callback method gets the
                            // result of the request.
                        }
                    }
                    LocationManager currentLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    Criteria currentCriteria = new Criteria();
                    String currentProvider = currentLocationManager.getBestProvider(currentCriteria, true);
                    Location currentLocation = currentLocationManager.getLastKnownLocation(currentProvider);
                    double currentLatitude = currentLocation.getLatitude();
                    double currentLongitude = currentLocation.getLongitude();
                    LatLng currentLatLng = new LatLng(currentLatitude, currentLongitude);

                    ClusterRequest testCluster = new ClusterRequest(currentLatitude, currentLongitude);
                    mClusterManager.addItem(testCluster);
                    mClusterManager.setRenderer(new MapIconRender(getApplicationContext(), mMap, mClusterManager));

                    dialog.dismiss();

                }
                else{
                    txtUsername.setError("Stop name must be at least 5 characters long.");
                }
            }
        });
}

MapIconRender.java
public class MapIconRender extends DefaultClusterRenderer<ClusterRequest> {

        public MapIconRender(Context context, GoogleMap map,
                             ClusterManager<ClusterRequest> clusterManager) {
            super(context, map, clusterManager);
        }

            @Override
            protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions
            markerOptions){
                markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_outside_azure));
                markerOptions.snippet("Status: ");
                markerOptions.title(stopName); //<------ THIS IS WHERE I WANT THE STOP NAME TO BE WHAT THE USER ENTERED.
                super.onBeforeClusterItemRendered(item, markerOptions);
            }
}

add_place.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_height="match_parent"
    android:paddingLeft="10dp" android:paddingRight="10dp"
    android:background="#fff" android:layout_width="300dp"
    android:paddingTop="10dp">
    <View
        android:id="@+id/HorizontalLine"
        android:layout_width="match_parent"
        android:layout_height="1dip"
        android:background="#aaa" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Name:"
        android:paddingTop="20dp"
        android:id="@+id/name" />
    <EditText android:layout_height="wrap_content"
        android:id="@+id/txtStopName"
        android:maxLength="100"
        android:singleLine="true"
        android:hint="Name of this stop (5-100 characters)"
        android:layout_width="match_parent">
        <requestFocus></requestFocus>
    </EditText>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Type:"
        android:paddingTop="20dp"
        android:layout_marginBottom="10dp"
        android:id="@+id/type" />

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:entries="@array/type_arrays"
        android:prompt="@string/type_prompt"
        android:layout_marginBottom="10dp"/>
    <View
        android:id="@+id/HorizontalLine2"
        android:layout_width="match_parent"
        android:layout_height="1dip"
        android:background="#aaa" />
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content" android:id="@+id/linearLayout1"
        android:paddingTop="5dp">

        <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_weight="0.5"
            android:id="@+id/btnCancel" android:text="Cancel"
            android:onClick="addPlaceCancel"/>
        <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_weight="0.5"
            android:id="@+id/addPlacebtnSubmit" android:text="Submit"
            android:onClick="addPlaceSubmit"
            android:layout_marginBottom="10dp"/>
    </LinearLayout>
</LinearLayout>

ClusterRequest.java

public class ClusterRequest implements ClusterItem {
private final LatLng mPosition;

public ClusterRequest(double lat, double lng) {
    mPosition = new LatLng(lat, lng);
}

@Override
public LatLng getPosition() {
    return mPosition;
  }
}

A: Can't you override onClusterItemRendered() method?
I think you can save your marker name in onBeforeClusterItemRendered() to any class-global variable String, and set the marker name in onClusterItemRendered() with Marker.setTitle(yourSavedTitle); or something.

Something like this:

public class MapIconRender extends DefaultClusterRenderer<ClusterRequest> {
    private String mMarkerTitle;

    public MapIconRender(Context context, GoogleMap map,
                         ClusterManager<ClusterRequest> clusterManager) {
        super(context, map, clusterManager);
    }

        @Override
        protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions
        markerOptions){
            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_outside_azure));
            markerOptions.snippet("Status: ");
            markerOptions.title(stopName); //<------ THIS IS WHERE I WANT THE STOP NAME TO BE WHAT THE USER ENTERED.
            mMarkerTitle = stopName;
            super.onBeforeClusterItemRendered(item, markerOptions);
        }

        @Override
        protected void onClusterItemRendered (ClusterRequest item, Marker marker){
            marker.setTitle(mMarkerTitle);
        }
}

A: @SuhyeonLee Not sure if this is what you meant (please let me know) but I did find the answer surprisingly enough in the demo that google released for their customize cluster demo. Heres what I learned. When calling the MapIconRender.java class via
mClusterManager.setRenderer(new MapIconRender(getApplicationContext(), mMap, mClusterManager));
Which will run this method in the MapIconRender.java class

protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions
            markerOptions)

Which means whatever variables in the ClusterRequest class will be accessible here in the MapIconRender.java class and can be accessed via (item.variableName). I apologize for not posting the code for the file ClusterRequest, I didnt think it was needed. ill go back and add that snippet to my original question.
Anyway the new code I needed to add was as follows:
In the MapsActivity class I needed to pass the ClusterRequest class the name of the marker(or title of the marker) via:
ClusterRequest testCluster = new ClusterRequest(currentLatitude, currentLongitude, stopName); //stopName was added here.
And in the ClusterRequest class I needed to add the "global variable" of the marker name (aka stopName) via:

public class ClusterRequest implements ClusterItem {
private final LatLng mPosition;
public final String stopName; //Add a "global variable" here so it can be accessible in the MapIconRender class.

public ClusterRequest(double lat, double lng, String _stopName) {
    mPosition = new LatLng(lat, lng);
    stopName = _stopName;
}

@Override
public LatLng getPosition() {
    return mPosition;
  }
}

And finally in my MapIconRender.java class I can add the title name of the marker via:

public class MapIconRender extends DefaultClusterRenderer<ClusterRequest> {

        public MapIconRender(Context context, GoogleMap map,
                             ClusterManager<ClusterRequest> clusterManager) {
            super(context, map, clusterManager);
        }

            @Override
            protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions
            markerOptions){
                markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_outside_azure));
                markerOptions.snippet("Status: ");
                markerOptions.title("Title: " + item.stopName); //Now we can access the title of the marker by calling item.variableName
                super.onBeforeClusterItemRendered(item, markerOptions);
            }
}

Im really sorry about the noob question here but I hope this helps someone out that may have the same question as I did and thank you for your answers! "SO" community is awesome!


text:
Q: KeyError when using Colab I am working through a regression example however, I am receiving a KeyError: 'dataset' when I run the code.
As I am using Colab, I have updated the parser as follows:
# construct the argument parser and parse the arguments
args = {
    "input": "path/to/input_image.jpg",
    "output": "path/to/output_image.jpg"
}

When I run the following line, I get an error message:
inputPath = os.path.sep.join([args["dataset"], "HousesInfo.txt"])

I have changed the director to where I have installed the relevant files - any ideas what else I need to do to the code, please?
Cheers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap - Load modal residing in other page and form submission from modal 1.I've a page where on clicking button brings up the modal. What I would like do to is move all models to a separate page. I've tried this
    $('#newSection').click(function(){
        $('#temp').load('adminmodels.php');
        $('#newSectionModal').modal('show');
    });

On first click, nothing happens. On subsequent clicks, the modal appears and fades automatically. Please suggest and corret my code.
2.I would like to submit a form from inside of a modal and then display the response in the modal itself.
    $(document).ready(function(){
        $('#user_button').click(function(e){
            e.preventDefault();
            $(this).attr('disabled',true);
            $.post('__admin_ajax.php',postString,function(response){
                $('#user-modal-body').html(response);
            });
        });
    });

The response of previous form submission retained for subsequent modal loads.

A: I find for this type of logic, it's easier to just use an iframe.

And then in the code.
$('#newSection').click(function(){
    $('#modal_frame').attr('src', 'adminmodels.php');
    $('#newSectionModal').modal('show');
});

Because it's in a frame, you can handle the form submission as if it were in it's own window. At any time, you can trigger the parent frame by calling window.parent. Ex: window.parent.trigger("form-submitted")


text:
Q: Symfony backend form I use symfony 1.4.11. I have frontend and backend form.
Frontend :
<?php

{
  public function configure()
  {

     $user = sfContext::getInstance()->getUser()->getGuardUser()->getProfile();

    $this->removeFields();

$this->widgField();
      $this->widgetSchema->setLabels(array(
  'time_id'    => 'Duration *',

   ));
  }

 protected function removeFields()
  {
 unset(

      $this['created_at'],
      $this['updated_at'],
      $this['is_closed'],
      $this['invoice_url'],
      $this['is_cancel']
      );
  }

  protected function widgField()
  {
 $this->widgetSchema['user_id'] = new sfWidgetFormInputHidden();
  }

   protected function  doUpdateObject($values)
  {
    parent::doUpdateObject($values);
    $this->getObject()->setUserId(sfContext::getInstance()->getUser()->getGuardUser()->getId());
  }
}

And Backend:
<?php
class BackendPaymentForm extends PaymentForm
{
  public function configure()
  {
    parent::configure();

  }

  protected function removeFields()
  {
    unset(
     $this['updated_at'],
     $this['created_at'],
     $this['user_id'],
     $this['time_id'],
     $this['invoice_url'],
     $this['is_cancel']

    );
  }
   protected function widgField()
  {

  }

}

?>

Problem is, that I have in frontend  doUpdateObject which set user_id , and in backend I need that admin can set one parameter, it is all ok, but it change user_id to admin id... Thank you!

A: I do not is it good way but it is work:)
class BackendPaymentForm extends PaymentForm
{
  public function configure()
  {
    parent::configure();

  }

  protected function removeFields()
  {
    unset(
     $this['updated_at'],
     $this['created_at'],
     $this['time_id'],
     $this['invoice_url'],
     $this['is_cancel']

    );
  }
   protected function widgField()
  {
$this->widgetSchema['user_id'] = new sfWidgetFormInputHidden();
  }

 protected function  doUpdateObject($values)
  {
    parent::doUpdateObject($values);
    $this->getObject()->setUserId($values['user_id']);
  }
}


text:
Q: MVC3 AJAX Form - DateTime Overflow? In my application I have an Index page with a list of Documents. I want to add a new Document  with an AJAX form on that same Index page. I am passing a NewDocument object to the Index page using a ViewModel.
The AJAX Form (I omitted some parts for readability):
@using (Ajax.BeginForm("Index_AddDocument", new AjaxOptions { UpdateTargetId = "MainList" }))

<div class="editor-field">
        @Html.EditorFor(model => model.NewDocument.Date)
        @Html.ValidationMessageFor(model => model.NewDocument.Date)
</div>

And here is the method that should save the new Document to the database, and update the Partial View list of documents:
public ActionResult Index_AddDocument(HomeIndexViewModel viewModel)
    {

        db.Documents.Add(viewModel.NewDocument);
        db.SaveChanges();

        return PartialView("ListOfDocs", db.Documents);
    }

This doesn't work, I'm getting an exception at db.SaveChanges(). It says:

InnerException    {"An overflow occurred while converting to datetime."}  System.Exception {System.Data.SqlServerCe.SqlCeException}

EDIT:
My Document domain model has the following Date property:
[DataType(DataType.Date)]
public DateTime Date { get; set; }

In the AJAX form I just type a random date like 5/2/2005 and then click Submit, and then get the exception mentioned above.

A: What is the value of viewModel.NewDocument.Date prior to the db.SaveChanges() call?
C# can handle dates from 1st Jan 0000 to 31st Dec 9999.  I know SQL Server can't handle that whole range (e.g. SQL Server 2008 can't handle before 1/1/1753 i believe)
I suspect that SQL Server CE also has limits on its date range and is balking at the default 1/1/0000 DateTime value.

A: I think I just solved my own problem. The 'Date' column in my database is of the type 'datetime'. But my domain model had this:
[DataType(DataType.Date)]
public DateTime Date { get; set; }

I changed that DataType to 'DataType.DateTime' and now it seems to be working fine.
Thanks everyone for the guidance!


text:
Q: How to override default CURL timeout for Codeception - using Browserstack I am testing Browserstack for acceptance tests. They have a peculiar habit of taking a very long time to respond to certain requests. I am running Codeception and I am always getting the CURL 30 second timeout error. I want to be able to override this timeout but I cannot figure out how to do it. Is this even possible in Codeception?
This is the yml for my acceptance tests:
class_name: RemoteAcceptanceTester
modules:
  enabled:
    - WebDriver
  config:
    WebDriver:
      url: '{my url}'
      curl:
        CURLOPT_TIMEOUT: 120
      host: 'hub.browserstack.com'
      port: 80
      browser: firefox
      capabilities:
        'browserstack.user': '{user}'
        'browserstack.key' : '{key}'
        'browserVersion': '21.0'
        'browserstack.debug': 'false'
        'browserstack.local': 'true' # force use of local BrowserStackLocal binary

Is there any setting or any hack I can try to up the timeout to what I want, which is 120 seconds? I know that's a ridiculous amount of time, but Browserstack is a bit 'peculiar' when you are running their local binary.

A: A new release for Codeception is online
[WebDriver] Added WebDriver init settings connection_timeout and request_timeout by @n8whnp #2065
see => http://codeception.com/changelog
Also see the documentation Page
connection_timeout - timeout for opening a connection to remote selenium server (30 seconds by default).
request_timeout - timeout for a request to return something from remote selenium server (30 seconds by default).
here => http://codeception.com/docs/modules/WebDriver


text:
Q: Change the text color of multiple elements in a list with a:hover So, I have this list contained within a specific id.  I only want to manipulate the link colors for this specific id, which is #icon-header.  So here is the problem:
I want the whole li element to be the link, but instead of having the background color change on hover, I want all of the text elements to to the color #2BA6CB.  And no matter where the user clicks, I want the whole li element to be the link.
So, I was wondering if there was something wrong with where I am putting the a tag, and also what your suggestions were for the css of it all.
The i tag is a webfont.  I need that to change with the h4 and the p tag all at the same time when the user hovers over the li.
Any help would be amazing.  Here is the html:

Ready

Create a personal health and fitness profile.

Set

Set goals and chart your progress.

Go

Upload your exercise data from anywhere.

Learn

View real results and develop healthy patterns.

A: You need to give the a-tag the dimensions (width & height) of the li Element instead of styling the li Element. Then you will have the effect, that you can click the whole highlighted area instead of only the link.
To give an inline element like ´a´-Tag a width and height you need to give it ´display:block;`.

A: Make the 'a' tag display: block in the css. Note that wrapping an anchor tag around block level elements is only allowed in html5. Older specs explicitly disallow it.


text:
Q: jQuery Draggable reset position with double click I am a bit stuck with this jsfiddle example. When the user drags the square that's all working fine. But when the user double clicks the square after dragging it away from the original position i want it to return to the original position which is only half working (vertically). It is not going to the right!
Any help much appreciated :)

A: you could do (i corrected your fiddle because it was totally wrong):
jQuery("#drag_item").draggable({containment: '#container'});
var position = jQuery("#drag_item").position();
//you could also use
//var position = jQuery("#drag_item").offset();

$("#drag_item").dblclick(function() {

    $('#drag_item').css({
        'top': position.top
    });

    $('#drag_item').css({
        'position': 'fixed'
    });
    $('#drag_item').css({
        'left': position.left
    });
});

fiddle here http://jsfiddle.net/6kXTP/5/


text:
Q: Markdown typographical features or Unicode glyphs? Which are the pros and cons of depending on Markdown support for typographical features after ASCII characters (like --, --- and ... for en- and em-dashes and ellipsis) vs. using the Unicode glyphs themselves (–, — and …) in the text?
[I am considering writing dynamic reports in rmarkdown that can be converted (knitr+pandoc) to html, pdf and docx/odt formats.

A: Some editors that aren't compatible with Unicode will mangle Unicode glyphs.  It's more common in older or poorly written text editors. I've seen characters removed directly, or replaced with garbage depending on the editor.  If all editors used to manage your markdown, as well as the parsers you use to process your markdown, are compatible with Unicode, then there may be no downside to using those glyphs directly.


text:
Q: How to install Typescript in Laravel Vite? I was working on a Laravel vite which is running on JS but I want to change to TypeScript configuration. Can anyone help me how to configure TypeScript in below vite config?

import { defineConfig } from "vite";
import laravel from "laravel-vite-plugin";
import { viteStaticCopy } from "vite-plugin-static-copy";

export default defineConfig({
    plugins: [
        viteStaticCopy({
            targets: [
                {
                    src: "resources/images",
                    dest: "assets",
                },
                {
                    src: "resources/json",
                    dest: "assets",
                },
            ],
        }),
        laravel({
            input: [
                "resources/css/app.css",
                "resources/js/app.js",
                "resources/js/ckeditor-classic.js",
                "resources/js/ckeditor-inline.js",
                "resources/js/ckeditor-balloon.js",
                "resources/js/ckeditor-balloon-block.js",
                "resources/js/ckeditor-document.js",
            ],
            refresh: true,
        }),
    ],
});


text:
Q: Service Fabric multiple SSL secured WebAPIs and certificate rollover I have two WebAPI applications in my cluster. Both apps run on each node. They both use asp.net core and Weblistener. Following the advice here I have set them both up to listen for http and https on port 80, and 443 respectively.
Https is secured using the same certificate and is set up using the, er, endpoint binding(?) as discussed here. I got it working fine with a self signed certificate, but a problem arose when it came to changing the certificate to a proper one. Effectively simulating a certificate rollover.
I added the new certificate to the key vault and deployed it to the cluster. When it came to republishing my applications, with the new certificate reference, it would fail with this error ConfigurePortCertificate: httpsPort=443, certStoreName My, certfindvalue {SSLCertFingerPrint}, error AlreadyExists. Which kind of makes sense now..
Since both applications are running on each node, and we attempt to update one of them the following happens:

*

*WebAPI1 has Cert_A bound to https:443.

*WebAPI2 has Cert_A bound to https:443 (which is fine, they're the same cert)

*Attempt to update WebAPI1 with Cert_B.

*Publishes to cluster, attempts to bind Cert_B to https:443

*Error because a different cert (Cert_A) is already bound to https:443

The only workaround I found for this is to take every system which uses Cert_A on https:443 offline, and republish all the apps using the new Cert_B.
This is pretty unacceptable (as in, I'm clearly doing something wrongly) to have to take major parts of the system down to change certificates.
What are my options here?
Does Kestrel manage https differently? Would I run in to similar issues by doing something like... instead of having the certificates hosted locally (i.e. through VM provisioning), I could request the latest certificate from keyvault. I could provide Kestrel with a certificate provided by an unversioned URL to key vault (which gets the latest certificate). Then I suppose all I'd need to do is cause the services to restart (publish an upgrade for example) and they'd start using the newest certificate. However, I understand Kestrel is not currently "supported" to be used for externally facing web servers.
Would I be best off either

*

*Using a gatewaty (e.g. Application Gateway) and hosting all my WebListener services on different ports, secured with HTTPS

*Using a gateway and use Kestrel, either different or same ports

*Using a https secured gateway and have my services run on different ports, not worry about https internally.

Or is there a simple solution to my problem which I don't realise?
Thanks in advance!
I apologise for any incorrect terminology, please do correct me.

A: There's a reverse proxy built into ASF. It can be configured to use SSL and perform SSL termination. That's a very simple solution.

http(s): The reverse proxy can be configured to accept HTTP or HTTPS
  traffic. In the case of HTTPS traffic, SSL termination occurs at the
  reverse proxy. Requests that are forwarded by the reverse proxy to
  services in the cluster are over http. Note that HTTPS services are
  not currently supported.


text:
Q: Single View Layout Files: Does Compiler Autowrap with Layout/ViewGroup? If I have a layout file that simply contains a single TextView, I have no problems inflating it from within an activity.
However, if I try to inflate a similar layout file that instead contains a single custom view, then I get a inflation exception.
The only way I can get a custom view to inflate in this case is to wrap it in within Layout/ViewGroup (ie, LinearLayout).
Therefore, I was wondering if the compiler will auto-wrap a built-in view in a Layout/ViewGroup (ie, LinearLayout) if it detects
that the view is not already nested within one ?
(I'm going to test this when I get some time to setup an emulator and extract a layout tree, and post
any findings.)
Thank you for the help.

Case 1: works ok
TextViewLayoutFile.axml

<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/tv_name"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"/>

LayoutInflater infalInflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
view = infalInflater.Inflate(Resource.Layout.TextViewLayoutFile, null);

Case 2: Only works if the MyTextView is wrapped in a layout (LinearLayout)
2a: Produces inflation exception
----------------------------------------------------------------------------
TextViewLayoutFile.axml

<?xml version="1.0" encoding="utf-8"?>
<AppName.Views.MyTextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/tv_name"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"/>

LayoutInflater infalInflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
view = infalInflater.Inflate(Resource.Layout.TextViewLayoutFile, null);

2b: Inflates ok
----------------------------------------------------------------------------
TextViewLayoutFile.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/ll_android_is"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">

  <AppName.Views.MyTextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

</LinearLayout>

LayoutInflater infalInflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
view = infalInflater.Inflate(Resource.Layout.TextViewLayoutFile, null);

where
namespace AppName.Views
{
    public class MyTextView : TextView
    {
        public MyTextView(Context context) : base(context) { }

        public MyTextView(Context context, IAttributeSet attributes) : base(context, attributes) { }
    }
}

A: There is one more constructor I believe you have not provided,
TextView(Context context, AttributeSet attrs, int defStyle)

I've previously had issues inflating and instantiating things without covering all the default constructors, may be adding fuel to the fire here as well. As far as the magic of the auto-wrapping. As far as what it does automatically for you, I can't say however.


text:
Q: VBA pivot table sum/count button as stated in the title i'm trying to make a button  that swaps betweend the count and the sum in a particular pivot table field i could make it in two but i've troubles with the IF statement this is what i came up with :
Sub Count()
'
' Macro3 Macro
'

    With ActiveSheet.PivotTables("PivotTable2").PivotFields("Sum of SP/UOM")
        .Caption = "Count of SP/UOM"
        .Function = xlCount
    End With

End Sub

Sub Sum()
'
' Sum Macro
'

    With ActiveSheet.PivotTables("PivotTable2").PivotFields("Count of SP/UOM")
        .Caption = "Sum of SP/UOM"
        .Function = xlSum
    End With

End Sub

If someone has an idea on how to make it I would be thankful !

A: You could use a loop like this:
Dim pf As PivotField
For Each pf In ActiveSheet.PivotTables("PivotTable2").DataFields
    If pf.SourceName = "SP/UOM" Then
        If pf.Function = xlSum Then
            pf.Caption = "Count of SP/UOM"
            pf.Function = xlCount
        Else
            pf.Caption = "Sum of SP/UOM"
            pf.Function = xlSum
        End If
        Exit For
    End If
Next


text:
Q: Why exactly is a sample of size 142 too small for 11 variables? In a (logistic?) regression paper related to credit scoring and involving psychometric data and credit scoring, there are 11 predictor variables used to estimate credit score. The sample size is 142. Intuitively, it doesn't seem enough, but what exactly is the rule of thumb involved for regressions? That involve psychometric data? That are logistic?
the paper: An empirical investigation of dispositional antecedents and performance-related outcomes of credit scores.
ZUI slideshow summary: An Empirical Investigation of Dispositional Antecedents and


text:
Q: Bypass WebView crossdomain security Scenary

*

*A Cocoa application with a WebView element that loads file:///index.html

*A local resource file:///index.html that has an editable iframe with src="javascript:;"

*The editable iframe contains another iframe with src="file:///resource.html"
Problem
It seems that WebView does not allow loading local resources (resource.html) inside documents that are not local (iframe with src="javascript:;").
This is the exact message from the Error Console of Safari for MacOSX:
Not allowed to load local resource: file:///resource.html

Question
Do you know any way to bypass this security check? I can modify all the javascript and Cocoa code, but I preffer to modify only the Cocoa code.
Thanks guys!

A: Finally I downloaded the source code of WebKit, inserted a return true in the certain place to disable these security measures and compiled it.
It seems that it works.


text:
Q: Java ProgressBar gui builder netbeans I want to use ProgressBar from netbeans GUI builder.
Any example will be appreciated.
thanks

A: Sun/ Orcale's Java Tutorial is always good start to look for such information:
http://download.oracle.com/javase/tutorial/uiswing/components/progress.html

A: Heres a simple ProgressBar Demo Program
package test;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JProgressBar;

public class ProgressBarDemo {

    JFrame frame;
    JProgressBar progressBar;

    public ProgressBarDemo() {
        frame = new JFrame("ProgressBarDemo");
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        progressBar = new JProgressBar();
        progressBar.setValue(40);
        frame.getContentPane().add(progressBar,BorderLayout.SOUTH);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new ProgressBarDemo();
    }

}


text:
Q: Why does 'sudo pwd' work but not 'sudo cd'? Many of the StackOverflow answers suggest that it is because cd is a builtin, but type cd and type pwd both return "shell builtin" and only sudo cd returns a "command not found".
So is cd handled as a special case contrary to many answers on SO which is "sudo only works with programs"?

A: pwd exists as both a shell builtin (which is why type pwd returns that it is a shell builtin) and separately as a GNU Core Utility.
The version of pwd that your system is using is the GNU Core Utility version. It is a executable and as such sudo can be used to run it; unlike cd which is a shell builtin command.
You can verify this for yourself.
Type both these commands youself and observe the outcomes. (if there are multiple versions of the same command in your system the which command will tell you which one is being invoked when you enter it)
which pwd

which cd

A shell builtin will return no folder path to an executable when you run the which command.
Here are example outputs of both commands on my system:
nate@linux:~> which pwd
/usr/bin/pwd

nate@linux:~> which cd
which: no cd in (/home/nate/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games:/usr/lib/mit/bin:/usr/lib/mit/sbin:/home/nate/Scripts:/home/nate/Scripts)

A: There is a pwd executable somewhere (try whereis pwd) and sudo uses it.


text:
Q: BuildHive Jenkins build error I'm trying to use Cloudbees' BuildHive service to build my GitHub-hosted project - bkemu-android. This is android-maven-plugin controlled project, so Jenkins job was created using "Maven job" template. But project build is just failing constantly with some obscure log message:

Parsing POMs
  [bkemu-android] $ /usr/bin/tenant-isolate /opt/jdk/jdk1.6.latest/bin/java -XX:MaxPermSize=128m -cp /scratch/jenkins/maven3-agent.jar:/opt/maven/latest/boot/plexus-classworlds-2.4.jar org.jvnet.hudson.maven3.agent.Maven3Main /opt/maven/latest /scratch/jenkins/slave.jar /scratch/jenkins/maven3-interceptor.jar 52322
setup process failed (1): Success
ERROR: Failed to launch Maven. Exit code = 1

What I should change in my project or BuildHive job settings to successfully build my project?


text:
Q: Cannot push to heroku after adding a remote heroku repo to my existing local repo Here is the scenario:
1) My project partner and I were working on a Ruby on Rails app together using github as our code repo.
2) The app is under her github account and she had added me as a collaborator
3) She deployed to Heroku and added me as a collaborator there as well
4) I used the following command from my existing app directory with the intention of adding the existing Heroku remote app as a remote to my existing local app.  My existing local app, as I mentioned before, already had a remote github
git remote add heroku git@heroku.com:codefellow.git

5) I made some changes and pushed them to github and all was up to date
6) Then I attempted to push to heroku with the following command
git push heroku master

7) This gave me an error saying the tip of my branch was behind, as shown below, but when I tried to pull from github, it said I was up to date, as also shown below
➜  code-fellows-alumni git:(master) git push heroku master
To git@heroku.com:codefellow.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'git@heroku.com:codefellow.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
➜  code-fellows-alumni git:(master) git pull
Already up-to-date.

So does anyone know what is going on here?  How could my local branch be out of sync with Heroku if I'm up to date with Github?  Would it have been possible for my project partner to have pushed changes to Heroku without having pushed them to Github first?  I checked and she does not have a fork of the application.  I cannot get in touch with her at the moment to find out for sure what she might have done--I'm not even sure it would allow her to push changes to Heroku if they hadn't been pushed to Github yet.  Any insights would be much appreciated.  I don't want to clone the app from Heroku necessarily because I already have it locally synced with Github.  I want to use Github as the code repository and I am reluctant to start from a clone from Heroku.  I've already looked at the Heroku documentation on this: https://devcenter.heroku.com/articles/git.  It just says to do a clone but I don't want to do that for the aforementioned reasons.  I followed the directions given in the answer to this question (How to link a folder with an existing Heroku app) to get this far but it seems like there is a missing piece or else my project partner has done something unusual.  Thanks in advance for any helpful ideas you might have.

A: The message you are seeing means that changes have been made to the application that you do not have in your local copy. When you push it's rejected because the Heroku remote is further ahead than yours, so you're right in thinking that your partner has pushed to Heroku without pushing to Github - it's a common scenario since you deploy from your local repository when you deploy to Heroku, unlike a traditional Capistrano deploy which would deploy the code from Github typically.
It's down to you as a team to come up with ways of working which prevent this from occuring, but if you need to get working right now, you can either

*

*git push heroku master -f. This forces your changes and will overwrite what's there presently with your code

*git pull heroku master to pull the changes from Heroku into your local repo which should then let you do a git push heroku master when you have the changes.


text:
Q: cannot find symbol symbol: (maven and POM) I finally fix nearly all that was wrong in my POM for maven compilation but there is still one wrong dependency (?)
In my servlet class a have got 5 errors typeof
cannot find symbol
  symbol:   method getDispatcherType()
  location: variable request of type javax.servlet.http.HttpServletRequest
cannot find symbol
  symbol:   variable FORWARD
cannot find symbol
  symbol:   variable REQUEST

I have added in POM
<dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>

and (http://mvnrepository.com/artifact/javax.servlet.jsp.jstl/javax.servlet.jsp.jstl-api/1.2.1)
<dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>

because getDispatcherType is from package javax.servlet;
but it still couldn't find this methods, perhaps someone could tell me what is wrong in this POM description?
PS  : org.glassfish.web:javax.servlet.jsp.jstl:1.2.1  is also present

A: You have the wrong dependency for jstl. You should be using:
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

Your jsp dependency is correct.

A: finally after a hours of screwing around that piece of code I have found what exactly caused such trouble - the dependency of tomcat-servlet-api MUST BE FIRST in  section.
I am using 7.0.50 version by the way.

A: I am using InteliJ IDEA, I highlighted at the point where I am importing the packages import javax.servlet.jsp.JspException; and the IDE gave me an option of downloading  Java version 6 (Java EE 6) dependencies. That fixed the problem for me

A: <dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>

update the version if you like to do so


text:
Q: Handling lot of items in std::stack  Can C++ std::stack handle more than 10k int items? And how about its performance?

A: 10K what?  Most std::stack implementations could easily handle 10K primitives with good performance, since that's probably < 80KB.  However, the standard doesn't guarantee performance.
Also note that it depends what backend you use.  The default is std::deque, which is basically an array of arrays.  However, you should get decent performance with any backend.

A: A std::stack is only limited by the underlying container (a std::stack is a container adapter).
Depending on what the underlying container is, you'll have different limits.
A std::vector will require contiguous memory whereas a std::list will only be limited by the size of the heap (and possibly any heap fragmentation).  But std::deque (the default container) is between the two; it requires smaller chunks of contiguous memory but will primarily be limited by the size of the heap.

A: The performance depends on the underlying container used. As already mentioned, stack is an adapter, the underlying container can be deque (the default), or vector, or list (all in std namespace).
Following is an example of performance comparison. As the type to be stored is not clearly mentioned in the question, I am assuming it to be unsigned int. Feel free to change it per your requirements. The example constructs a stack of 100K items.
Contents of stack.cpp
#include <stack>
#include <vector>
#include <list>
#include <deque>
#include <assert.h>

typedef unsigned int Type;

#ifdef USE_VECTOR
typedef std::stack< Type, std::vector< Type > > StackType;
#elif USE_LIST
typedef std::stack< Type, std::list< Type > > StackType;
#else
typedef std::stack< Type, std::deque< Type > > StackType;
#endif

int main() {
    StackType mystack;
    for( unsigned int i = 0; i < 100 * 1024; ++i ) {
        mystack.push( i );
    }
    assert( mystack.size() == 100 * 1024 );
    return 0;
}

Execution comparison:
$ g++ -DUSE_VECTOR stack.cpp -o stack; time ./stack

real    0m0.023s
user    0m0.030s
sys     0m0.031s

$ g++ -DUSE_LIST stack.cpp -o stack; time ./stack

real    0m0.144s
user    0m0.186s
sys     0m0.030s

$ g++  stack.cpp -o stack; time ./stack

real    0m0.024s
user    0m0.030s
sys     0m0.015s

asaha@nedata8 ~/code
$

The above numbers are result of single run. To achieve statistically significant numbers run each variation large number of times, and observe the mean and standard deviation.
Apparently, deque and vector results in similar performance, whereas list is worse.

A: Yes, it can handle 10k.   As long as you have the memory resources for it.  If you are worried it uses the internal stack,  it doesn't.
Performance is implementation specific, but should be very quick

A: std::stack is not a container, but a container adapter. By default it uses an std::deque as container, but you can also use a std::vector or std::list. Deques free their memory when elements are removed.


text:
Q: Are there any good reasons to put logic (methods) into view Model classes I was doing a code review today and seen that someone having a view model classes that besides of data contains different methods, like
GetTable, GetPdf, LoadSomeData etc.

I personally didn't like it, since prefer to have a "plain" view Model classes, containing only the properties and put logic either into Controller either additional Service.
But on review I was not possible to find good arguments for that.
What do you think, is it a good way (style) of having a logic in view Model classes? What are pros/cons?
EDIT: It was ASP.net MVC2 application.
EDIT: Example (just from head) of such code..
public ActionResult SomeAction()
{
   var model = new ViewModel();
   model.LoadSomethingFromSomething();
   model.AnotherMethod();

   return View(model);
}

A: The principal of separation of concerns and the single responsibility principal dictates that the only "logic" that should be contained in the view should be that which manipulates how the view displays the data.  Everything else should be in the controller.  Semantically the view does one thing - displays data, anything unrelated to displaying said data - i.e. manipulating data, formatting data, loading data, converting data etc. should be handled by the controller.
In the real world, we don't always have the luxury of idealism, but in the ideal world, that's the way it should be.  The principal of least surprise says that code should be in the least surprising place to find it.  If I (as a code maintainer) need to fix something, I need to be able to find it quickly - if it's not where logic dictates I would find it, it provides unnecessary hindrance to my completing my tasks quickly and efficiently.
If GetTable pertains to loading a table construct (i.e. an HTML table) for the view, then perhaps it is relevant, if we're talking about getting table data from a database, then it is not.

A: Your question feels vague to me. When you say view model, do you mean a view specific model constructed from your domain's model that a view consumes? In that case, I agree the view model should be pretty simple overall. The view shouldn't have to "think" much (ideally, it shouldn't "think" at all). Calling methods from a view (that aren't defined in helpers), even branching in a view, is a code smell to me.
IMO, controllers should also be thin and light. I like the real bulk of my logic to be in my models and also in the data access layer. Just depending on what type of logic we are talking about.

A: I used to subscribe to the idea of totally "dumb" models.. I.E ones that don't do ANYTHING. However after using that idea in practice I found it wasn't ideal. I now subscribe to the idea that viewModels should know about how to create themselves from other objects.
I.E.
public ActionResult SomeAction(int? id)
{
   var serviceModel = _myService.Get(id ?? 0);
   var model = new ViewModel(serviceModel);

   return View(model);
}

Basically, rather than adding methods to your model, create several constructors that take in objects used in that view model's creation. This frees up your controllers & service from knowing anything about how the viewModel works (meaning there is no object mapping code cludging up everything).
Then, to get an object out of the viewModel, you can do the following:
[HttpPost]
public ActionResult SomeAction(ViewModel model)
{
   _myService.Update(model.MapToServiceModel() );

   return SomeAction(model.id);
}


text:
Q: Simple solr query in order to search for a name in a field I am trying to search for whatever docs which have for example Reddy and Kumar in the respondent_name field but whenever I tried this search I never get what I want.
I have tried it:
respondent_name:"Reddy Kumar"~3
/select?indent=on&q=respondent_name:%E2%80%9DReddy%20Kumar%E2%80%9D~3&rows=1000&wt=json

I did get result from this query but most of them returned for any docs which have Reddy and Kumar word in any field, not the docs which has these word in the respondent_name field.
I tried to follow this site but for some reason, it doesn't work for me:
https://dzone.com/articles/tips-name-search-solr
Json docs samples:
{
    "db_id":["590dd7e5fa25c3080f0d706e"],
    "main_title":["District Courts, Ananthapur"],
    "respondent_name":["Erikela Sunkanna",
      "The ManagerLegal CellICICI Lombard General Insurance Co.Ltd.",
      "S. Chandrasekhar Reddy"],
    "id":"9a3c1c41-a634-4df8-91e6-1a90072ebd9f",
    "_version_":1574199934804033536
},
{
    "db_id":["590dd7bbfa25c3080f0d6eb4"],
    "main_title":["Jr . Civil Courts,Uravakonda"],
    "respondent_name":["Nayika Chinnappayya",
      "Nayika Chinna Reddy",
      "Nayika Devi",
      "Nayika Gowramma"],
    "id":"65dff199-5e51-415e-9fa3-14693c74a6a9",
    "_version_":1574199931583856640
},
{
    "db_id":["590dd7d0fa25c3080f0d6f93"],
    "main_title":["Jr . Civil Courts,Tadipatri"],
    "respondent_name":["Y.Hari Kumar Reddy"],
    "id":"a162347b-6af1-4c1f-b65b-3eee76f71469",
    "_version_":1574199933688348672
}

Does anyone can tell me what I am doing wrong?


text:
Q: Bonjour networked printer with Time Capsule in bridge mode I have a 5th generation Airport Time Capsule as my primary router, and a 4th generation Airport Time Capsule in bridge mode, connected via cat5. When I connect my printer (a Brother HL-3040CN) to the 4th gen via USB, it's visible on the network and works fine. When I connect it by cat5 to one of the 4th gen's LAN ports, however, even though it seems to appear in the Bonjour list, from the 5th gen WiFi network I get "the printer is not responding". (This is after deleting it in the Printers and Scanners control panel and re-adding it as a new printer.)
Also suspicious is that when I try to ping the Bonjour address, brn001ba94e93ac.local, I get an IP address in the 192.168 range, even though the rest of my LAN is 10.0.
So I guess my questions are:

*

*is this a configuration that should work?

*why is the printer showing up as a Bonjour device if I can't connect to it?

*why is the Bonjour address mapped to an IP on a nonexistent subnet?

Edited to add: Ping and traceroute both fail, and iNet Network Scanner shows it under "Bonjour browser" but not under "Network scanner".

A: I'm not positive this answer will work, but these are the first things I'd try.
To answer your questions:
1) Yes, that configuration should work.
2) You can see it because it is a Bonjour device - just because you can't connect to it doesn't mean that it doesn't exist.
3) Check the settings on the printer. You can either do this on the screen of the printer (assuming it has one) or by opening a web browser and typing the internal IP address into the address bar. Make sure that the printer is configured to get its IP address using DHCP and is not self (manually) assigned.


text:
Q: Scheme : Lambda inside quoted list is unbound I'm programming a small lisp/scheme interpreter and I came across the following situation :
When a quoted list contains lambdas, they are not parsed as lambdas.
Here is a sample code (live on repl.it):
(define list1 '(
                   (lambda (x) (+ x 1))
                   (lambda (y) (+ y 2))
                )
)

(define add1 (car list1))
(print (add1 1))

and the result is  :
Error: ('lambda ('x) ('+ 'x 1)) is not a function [add1]

Is it normal behaviour ? I thought lambdas were special forms that should always be binded.
If it is indeed the expected behaviour : When my Parser parse the Lambda and wraps it in an object (say, of type LambdaWrap) and my Interpreter returns that object unevaluated then I guess that this is a wrong behaviour because it's supposed to return some unbinded symbols instead. Is that right ?

A: The problem is: what do you mean by "parsed as a lambda"?
Suppose I write this in Java:
String fun = "() -> 3";
int y = fun();

It fails, because you don't expect the string to be parsed, evaluated as a lambda expression and be directly usable as a function, do you?
The same applies with strings in Lisp and in a similar way with quote: the quoted form is read but not evaluated. More precisely, the evaluation of (quote x) returns x (the expression itself), and not (eval x), the value this expression yields upon evaluation.
So instead of having a function object, what you obtain after doing (car list1) is a list of values, the first one being the lambda symbol.
If you want to build a list of functions, use (list ...), which evaluates its arguments.

You say:

Ok but why is the inner list evaluated ? i.e : I get ('lambda ('x) ('+ 'x 1)) instead of : ('lambda '( 'x ') '( '+ 'x 1') )

The reader takes strings and produces a value, which is a symbolic expression: for example, an object in memory with car and cdr fields.
Your question assumes that this is a list of tokens, like quoted parenthesis etc., which is not the case. At this point you manipulate abstract syntax trees.
In order to see this value, your system must print it, and it tries to do it so that the printed form can be read back. If you play with repl.it a little, you can see how a regular list is printed, etc.
The particular message you see is taken from an error message where honestly, the form is printed in a strange way, different from the normal output as seen from the REPL. Maybe someone else can explain why this error message is formatted the way it is.


text:
Q: What is wrong with the following code to identify balanced parentheses using stack? Problem:
Given a sequence consisting of parentheses, determine whether the expression is balanced. A sequence of parentheses is balanced if every open parentheses can be paired uniquely with a closed parentheses that occurs after the former. Also, the interval between them must be balanced. You will be given three types of parentheses: (, {, and [.
{[()]} - This is a balanced parentheses.
{[(])} - This is not a balanced parentheses.
Input Format:
*The first line of input contains the number of test cases.
*Each test case consists of a single line with the sequence of parentheses.
stack <char> stk;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;

cin>>n;

for(int i=0;i<n;i++)
{
    string s;
    cin>>s;cout<<s;
    int j=0;
    while(j!=s.length())
    {
        if(stk.size()==0&&(s[j]==')'||s[j]==']'||s[j]=='}'))
        {stk.push('z');}
        if(s[j]=='('||s[j]=='['||s[j]=='{')
            stk.push(s[j]);
        if(stk.top()=='('&&s[j]==')')
            stk.pop();
        if(stk.top()=='['&&s[j]==']')
            stk.pop();
        if(stk.top()=='{'&&s[j]=='}')
            stk.pop();
        j++;
    }
    if(stk.size()==0)
        cout<<"YES"<<endl;
    else
    {
        cout<<"NO"<<endl;
        while(stk.size()!=0)
            stk.pop();
    }
}
return 0;
}

It is a code for checking for balanced parentheses. Its working fine with strings starting with a '{' but fails with strings like "[]"

A: You must be getting a Segmentation Fault.
Suppose,
s = "[]";

After 1st iteration your stack contains only "[".
During 2nd iteration,
if(stk.top()=='['&&s[j]==']')
        stk.pop();

above code makes your stack empty.
In next line you are calling
stk.top() // But your stack is empty

in
if(stk.top()=='{'&&s[j]=='}')
        stk.pop();

This is the problem. So before calling
stk.top();

make sure that your stack is not empty.
Check this tutorial on balanced parentheses.


text:
Q: Issue while Loading JSON with Store  I am trying to get some master data from server in JSON format and bind it to selectfield with the help of Store.
Find my code below
Model
Ext.define('Mobile.model.OrganizationModel', {
  extend: 'Ext.data.Model',
   config: {
    fields: [
        { name: 'Name', type: 'string' },
        { name: 'Id', type: 'int' }
    ]
   }
});

Store
Ext.define('Mobile.store.OrganizationStore', {
extend: 'Ext.data.Store',
model: 'Mobile.model.OrganizationModel',

autoLoad: true,

proxy: {
    type: 'ajax',
    url: 'login/GetOrgList',
    method: 'GET',
    reader: {
        type: 'json'
    }
}

});

View
Ext.define("Mobile.view.LoginView", {
extend: "Ext.form.FormPanel",
alias: "widget.login",
id: 'loginFormPanel',

config: {

    margin: '0 auto',
    name: 'loginform',
    frame: true,
    url: 'login/Authenticate',
    title: 'something',
    items: [

      {
          xtype: 'fieldset',

          itemId: 'LoginFieldset',
          margin: '10 auto 0 auto ',

          title: '',
          items: [
                  {
                      xtype: 'selectfield',
                      label: 'Organization',
                      name: 'Organization',
                      store: 'OrganizationStore',
                      displayField: 'Name',
                      valueField: 'Id',
                      placeHolder: 'Select a Value'
                  }
            ]
      },

    ]
 }

});

APP.js
Ext.application({
name: "Mobile",
controllers: ["LoginController"],
views: ['LoginView', 'HomeView'],
models: ['UserModel', 'OrganizationModel'],
stores: ['OrganizationStore'],
launch: function () {
    var loginPanel = Ext.create('Ext.Panel', {
        layout: 'fit',
        items: [
            {
                xtype: 'login'
            }
        ]
    });
    Ext.Viewport.add(loginPanel);
}

});

JSON Data format is
[{"Id":1,"Name":"Company 1"},{"Id":2,"Name":"Company 2"},{"Id":3,"Name":"Company 3"}]
The problem is it is not sending request to server and loading JSON data and binds. Any idea     about this issue?

A: update you store code to
    Ext.define('Mobile.store.OrganizationStore', {
extend: 'Ext.data.Store',
config:{
model: 'Mobile.model.OrganizationModel',

autoLoad: true,

proxy: {
    type: 'ajax',
    url: 'login/GetOrgList',
    method: 'GET',
    reader: {
        type: 'json'
    }
}

  }
  });


text:
Q: How can I process audio in real time using an USB guitar interface in android? I want to learn how to process audio input in real time in Android, so I want to make an experimental app that do simple audio manipulation of a guitar connected to the Android device, implementing a simple overdrive effect just to learn.
I know that it's posible to capture audio using the AudioRecord class when using a normal audio input like the built in device mic, or using an TRRS 3.5mm Jack cable, but in most phones the latency is high, I suppose that some guitar tuners apps works in this way, but I'm wondering how AndRig, DrAmp and usbEffects apps works using an external usb guitar interface like the Behringer
UCG102 to achieve a very low latency audio processing.
So, I want to use this usb guitar audio interface in my project to achieve low latency.
I searched for examples using this kind of guitar interfaces and I didn't find any tutorial or library to use it, so...
Do this Guitar to USB interface can be used like a normal input when connected to the device (So I can use the AudioRecord class like in a normal input)?
Do you know if exists some documentation or a tutorial to work with this kind of audio interfaces?
Or do I need to learn the Guitar to USB interface specific protocol and use low level USB API programming to do what I want?

A: The easiest way is probably buying this. There is also an  API for android that looks a lot like LibUsb, you could try that to read the Usb endpoint as raw data (not sure if it would work out for your device though).
Another option is to make your own hardware (buy a microcontroller with a good ADC), and use [bulk transfers](https://developer.android.com/reference/android/hardware/usb/UsbDeviceConnection.html#bulkTransfer(android.hardware.usb.UsbEndpoint, byte[], int, int)) (usb communication protocol for lots of data).


text:
Q: Run sudo mysql -e "SET ***'rootpassword')" ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) on Github Actions I ran the command sudo mysql -e "SET Password=PASSWORD('rootpassword')"
but it was showing the error
.

A: mysql -e "SET PASSWORD = 'YourChosenPassword';"


text:
Q: python dictionary manipulation not working I am doing data processing to filter and sort and etc...
for stock in context.timeSeriesData:
    try:
        if context.timeSeriesData.iloc[1,:][stock][2] > 0 and context.timeSeriesData.iloc[0,:][stock][2] > 0:
            if context.timeSeriesData.iloc[1,:][stock][2] > context.timeSeriesData.iloc[0,:][stock][2]:
                context.tradingList[stock] = []
                increment = context.timeSeriesData.iloc[1,:][stock][2] / context.timeSeriesData.iloc[0,:][stock][2]
                context.tradingList[stock].append(increment)
    except:
        pass

try:
    sorted_tradingList = sorted(context.tradingList.items(), key = lambda x: x[1], reverse = True)
except:
    pass

try:
    sorted_tradingList.clear()
except:
    pass

for x,stock in sorted_tradingList:
    if len(context.tradingBook) < (1.25/context.weightLong):
        if stock in data and 'price' in data[stock]:
            context.tradingBook[stock] = []
            context.tradingBook[stock].append(0.0)
            order_target_percent(stock, context.weightLong)

for k, v in context.tradingBook.iteritems():
    v[0] +=1

timeToSell = {k:v for (k,v) in context.tradingBook.iteritems() if v[0] == 10}

for stock in timeToSell:
    if stock in data and 'price' in data[stock]:
        TargetHedge = (len(context.tradingBook) - 1) * context.weightShort
        order_target_percent(stock, 0.0)
        del context.tradingBook[stock]

if len(timeToSell)>0:
    timeToSell.clear()

TargetHedge = (len(context.tradingBook)) * context.weightShort
order_target_percent(sid(8554), TargetHedge)

In the first loop context.timeSeriesData will generate many sets of company with three data elements.  For example, the first two is shown below.  Lets look at AAPL, 311 is an industry code (which I don't care to use it now), the second element 18024000000 is net income, and 3.08 is the earning per share (which I want to manipulate)
DataFrame:
          Equity(24 [AAPL])
1  [311.0, 18024000000.0, 3.08]
2  [311.0, 18024000000.0, 3.08]

In the data above first line indicates data received prior day and the second line indicates the data just arrived.  So in the future if the DataFrame: changes to as shown below. The the computer should put that into context.tradingBook
DataFrame:
          Equity(24 [AAPL])
1  [311.0, 18024000000.0, 3.08]
2  [311.0, 19033000000.0, 3.79]

so the purpose is that when a new data is received, and the earning per share improves it will be stored into context.tradingList.  Then it shorts by the highest "increment"
sorted_tradingList = sorted(context.tradingList.items(), key = lambda x: x[1], reverse = True)

Then the code
for k, v in context.tradingBook.iteritems():
    v[0] +=1

will add one day each time this whole block of code is processed (once a day).  As you can see it starts with 0 day, context.tradingBook[stock].append(0.0), but each day it will add one day until 10 days have passed, at which point, I will try to sell them.
order_target_percent(stock, context.weightLong) is a code to buy or sell stocks which is unique to my system so don't worry about it.  My question is...  why it is not adding days.  I am having issue with
for k, v in context.tradingBook.iteritems():
    v[0] +=1

It is currently not adding days.  What am I doing wrong.  Also I have another question, if you are interested in following along this far.  But I will let you know once we get the first step down.  Thank you so much.

A: The problem was at
try:
    sorted_tradingList.clear()
except:
    pass

It was not working and I wasn't aware of it.


text:
Q: How can I update this kinect depth-basics code so that i can save raw depth data such as uint16 format in C#? I want to change this code so it can save raw depth data as uint16 format. but at this stage, it saves the image in uint8 format by converting the values 0-255. but i need to save the value as it come from camera or kinect such as uint16 format.
Code:depthBasics:
    //------------------------------------------------------------------------------
// <copyright file="MainWindow.xaml.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Samples.Kinect.DepthBasics
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using Microsoft.Kinect;

    /// <summary>
    /// Interaction logic for MainWindow
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        /// <summary>
        /// Map depth range to byte range
        /// </summary>
        private const int MapDepthToByte = 8000 ;

        /// <summary>
        /// Active Kinect sensor
        /// </summary>
        private KinectSensor kinectSensor = null;

        /// <summary>
        /// Reader for depth frames
        /// </summary>
        private DepthFrameReader depthFrameReader = null;

        /// <summary>
        /// Description of the data contained in the depth frame
        /// </summary>
        private FrameDescription depthFrameDescription = null;

        /// <summary>
        /// Bitmap to display
        /// </summary>
        private WriteableBitmap depthBitmap = null;

        /// <summary>
        /// Intermediate storage for frame data converted to color
        /// </summary>
        private byte[] depthPixels = null;

        /// <summary>
        /// Current status text to display
        /// </summary>
        private string statusText = null;

        /// <summary>
        /// Initializes a new instance of the MainWindow class.
        /// </summary>
        public MainWindow()
        {
            // get the kinectSensor object
            this.kinectSensor = KinectSensor.GetDefault();

            // open the reader for the depth frames
            this.depthFrameReader = this.kinectSensor.DepthFrameSource.OpenReader();

            // wire handler for frame arrival
            this.depthFrameReader.FrameArrived += this.Reader_FrameArrived;

            // get FrameDescription from DepthFrameSource
            this.depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription;

            // allocate space to put the pixels being received and converted
            this.depthPixels = new byte[this.depthFrameDescription.Width * this.depthFrameDescription.Height];

            // create the bitmap to display
            this.depthBitmap = new WriteableBitmap(this.depthFrameDescription.Width, this.depthFrameDescription.Height, 96.0, 96.0, PixelFormats.Gray8, null);

            // set IsAvailableChanged event notifier
            this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged;

            // open the sensor
            this.kinectSensor.Open();

            // set the status text
            this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText
                                                            : Properties.Resources.NoSensorStatusText;

            // use the window object as the view model in this simple example
            this.DataContext = this;

            // initialize the components (controls) of the window
            this.InitializeComponent();
        }

        /// <summary>
        /// INotifyPropertyChangedPropertyChanged event to allow window controls to bind to changeable data
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Gets the bitmap to display
        /// </summary>
        public ImageSource ImageSource
        {
            get
            {
                return this.depthBitmap;
            }
        }

        /// <summary>
        /// Gets or sets the current status text to display
        /// </summary>
        public string StatusText
        {
            get
            {
                return this.statusText;
            }

            set
            {
                if (this.statusText != value)
                {
                    this.statusText = value;

                    // notify any bound elements that the text has changed
                    if (this.PropertyChanged != null)
                    {
                        this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText"));
                    }
                }
            }
        }

        /// <summary>
        /// Execute shutdown tasks
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            if (this.depthFrameReader != null)
            {
                // DepthFrameReader is IDisposable
                this.depthFrameReader.Dispose();
                this.depthFrameReader = null;
            }

            if (this.kinectSensor != null)
            {
                this.kinectSensor.Close();
                this.kinectSensor = null;
            }
        }

        /// <summary>
        /// Handles the user clicking on the screenshot button
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void ScreenshotButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.depthBitmap != null)
            {
                // create a png bitmap encoder which knows how to save a .png file
                BitmapEncoder encoder = new PngBitmapEncoder();

                // create frame from the writable bitmap and add to encoder
                encoder.Frames.Add(BitmapFrame.Create(this.depthBitmap));

                string time = System.DateTime.UtcNow.ToString("hh'-'mm'-'ss", CultureInfo.CurrentUICulture.DateTimeFormat);

                string myPhotos = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

                string path = Path.Combine(myPhotos, "KinectScreenshot-Depth-" + time + ".png");

                // write the new file to disk
                try
                {
                    // FileStream is IDisposable
                    using (FileStream fs = new FileStream(path, FileMode.Create))
                    {
                        encoder.Save(fs);
                    }

                    this.StatusText = string.Format(CultureInfo.CurrentCulture, Properties.Resources.SavedScreenshotStatusTextFormat, path);
                }
                catch (IOException)
                {
                    this.StatusText = string.Format(CultureInfo.CurrentCulture, Properties.Resources.FailedScreenshotStatusTextFormat, path);
                }
            }
        }

        /// <summary>
        /// Handles the depth frame data arriving from the sensor
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void Reader_FrameArrived(object sender, DepthFrameArrivedEventArgs e)
        {
            bool depthFrameProcessed = false;

            using (DepthFrame depthFrame = e.FrameReference.AcquireFrame())
            {
                if (depthFrame != null)
                {
                    // the fastest way to process the body index data is to directly access
                    // the underlying buffer
                    using (Microsoft.Kinect.KinectBuffer depthBuffer = depthFrame.LockImageBuffer())
                    {
                        // verify data and write the color data to the display bitmap
                        if (((this.depthFrameDescription.Width * this.depthFrameDescription.Height) == (depthBuffer.Size / this.depthFrameDescription.BytesPerPixel)) &&
                            (this.depthFrameDescription.Width == this.depthBitmap.PixelWidth) && (this.depthFrameDescription.Height == this.depthBitmap.PixelHeight))
                        {
                            // Note: In order to see the full range of depth (including the less reliable far field depth)
                            // we are setting maxDepth to the extreme potential depth threshold
                            ushort maxDepth = ushort.MaxValue;

                            // If you wish to filter by reliable depth distance, uncomment the following line:
                            //// maxDepth = depthFrame.DepthMaxReliableDistance

                            this.ProcessDepthFrameData(depthBuffer.UnderlyingBuffer, depthBuffer.Size, depthFrame.DepthMinReliableDistance, maxDepth);
                            depthFrameProcessed = true;
                        }
                    }
                }
            }

            if (depthFrameProcessed)
            {
                this.RenderDepthPixels();
            }
        }

        /// <summary>
        /// Directly accesses the underlying image buffer of the DepthFrame to
        /// create a displayable bitmap.
        /// This function requires the /unsafe compiler option as we make use of direct
        /// access to the native memory pointed to by the depthFrameData pointer.
        /// </summary>
        /// <param name="depthFrameData">Pointer to the DepthFrame image data</param>
        /// <param name="depthFrameDataSize">Size of the DepthFrame image data</param>
        /// <param name="minDepth">The minimum reliable depth value for the frame</param>
        /// <param name="maxDepth">The maximum reliable depth value for the frame</param>
        private unsafe void ProcessDepthFrameData(IntPtr depthFrameData, uint depthFrameDataSize, ushort minDepth, ushort maxDepth)
        {
            // depth frame data is a 16 bit value
            ushort* frameData = (ushort*)depthFrameData;

            // convert depth to a visual representation
            for (int i = 0; i < (int)(depthFrameDataSize / this.depthFrameDescription.BytesPerPixel); ++i)
            {
                // Get the depth for this pixel
                ushort depth = frameData[i];

                // To convert to a byte, we're mapping the depth value to the byte range.
                // Values outside the reliable depth range are mapped to 0 (black).
                this.depthPixels[i] = (byte)(depth >= minDepth && depth <= maxDepth ? (depth / MapDepthToByte) : 0);
            }
        }

        /// <summary>
        /// Renders color pixels into the writeableBitmap.
        /// </summary>
        private void RenderDepthPixels()
        {
            this.depthBitmap.WritePixels(
                new Int32Rect(0, 0, this.depthBitmap.PixelWidth, this.depthBitmap.PixelHeight),
                this.depthPixels,
                this.depthBitmap.PixelWidth,
                0);
        }

        /// <summary>
        /// Handles the event which the sensor becomes unavailable (E.g. paused, closed, unplugged).
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void Sensor_IsAvailableChanged(object sender, IsAvailableChangedEventArgs e)
        {
            // on failure, set the status text
            this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText
                                                            : Properties.Resources.SensorNotAvailableStatusText;
        }
    }
}

A: private unsafe void ProcessDepthFrameData(IntPtr depthFrameData, uint depthFrameDataSize, ushort minDepth, ushort maxDepth)
        {
           // CONVERT IN TO ANY VALID FORMAT YOU WANT
           // THEN HERE YOU HAVE DEPTH DATA ARRAY, SAVE IT AS YOU LIKE
            ushort* frameData = (ushort*)depthFrameData;

        }

If you need more efficiency, you can try something like
 depthFrame.CopyFrameDataToBuffer(buffer);

In Reader_FrameArrived function.

A: The example provided in the Kinect SDK saves the PNG's in 8-bit format (0-255) therefore you loose the depth values. The issue is that WPF(?) cannot display 16-bit image data on screen (i believe due to GDI+ restrictions as mentioned in another SO question)
To save the depth images as Raw 16-bit PNG's; a couple of things need to be done.

*

*WriteableBitmap item with PixelFormats.Gray16 needs to be declared, instead of the PixelFormats.Gray8

*Two separate WritePixels need to be called, one for displaying the image in (byte)  format and another for saving the depth image in 16-bit (ushort) format

*Lastly, the depth data acquired needs to be processed twice, once in a byte array for displaying on screen, and once in ushort array for saving.

Note that the above can be modified as required (or for performance reasons if req) but for me, this works just fine and i can display the depth images and save the raw depth data aswell.
The code is as follows:
Initialize a new var:
    private ushort[] raw = null;
    private WriteableBitmap rawPNG = null;

In MainWindow Create two writeableBitmap's
this.depthBitmap = new WriteableBitmap(this.depthFrameDescription.Width, this.depthFrameDescription.Height, 96.0, 96.0, PixelFormats.Gray8, null);
this.rawPNG= new WriteableBitmap( this.depthFrameDescription.Width, this.depthFrameDescription.Height, 96.0, 96.0, PixelFormats.Gray16, null );

In ProcessDepthFrameData assign the values:
// FOR DISPLAYING ON SCREEN:
// To convert to a byte, we're mapping the depth value to the byte range.
// Values outside the reliable depth range are mapped to 0 (black).
this.depthPixels[i] = (byte)(depth >= minDepth && depth <= maxDepth ? (depth / MapDepthToByte) : 0);

// FOR SAVING RAW PNG 16-BIT DATA
// Keeping the raw depth values after clipping them to the max depth. The data is converted to ushort which is 16bit data
raw[i] = (ushort)(depth >= minDepth && depth <= maxDepth ? (depth) : 0);

In RenderDepthPixels, create teh two images:
// Rendering frame for displaying on the screen, in 8-Bit grayscale format
    depthBitmap.WritePixels(
            new Int32Rect( 0, 0, depthBitmap.PixelWidth, depthBitmap.PixelHeight ),
            depthPixels,
            depthBitmap.PixelWidth,
            0 );

// Rendering frame for saving as raw-16-bit PNG file
    rawPNG.WritePixels(
            new Int32Rect( 0, 0, depthBitmap.PixelWidth, depthBitmap.PixelHeight ),
            raw,
            depthBitmap.PixelWidth * 2,
            0 );

And lastly, in ScreenshotButton_Click, save the file:
// TO SAVE THE DISPLAYED 8-BIT PNG
//encoder.Frames.Add( BitmapFrame.Create( this.depthBitmap) );

// TO SAVE THE RAW 16-BIT PNG
encoder.Frames.Add( BitmapFrame.Create( this.rawPNG ) );

The results can be verified by loading the depth image in Matlab. Imread shows a Uint16 image format and the depth values are retained in the matrix. Or by just checking the png file properties :)
I have shared the complete code that is working for me at Pastebin. Hopefully it should work for you aswell, and solves the issue.


text:
Q: Using PHP/MySQL to automate email campaign, not sure how to structure query I have two MySQL tables, one with subscriber details, the other where I keep track of who has had an email sent to them, which campaign, which version, etc (crawler and sent_mail, respectively.) I've built a script which can go through the crawler table and send emails based on the SendGrid API, a web form and some javascript. But I am trying to figure out how I can tell the script to pull emails from the crawler table which don't have the current campaign listed in the sent_mail table. I know I have to use a join, but am not really sure how to build the logic into the query. Thoughts? My attempt follows below:
foreach ('SELECT crawler.email FROM crawler LEFT JOIN sent_mail ON crawler.email = sent_mail.email WHERE sent_mail.campaigns <> "$campaign"') as $address) as $address) {
    $email = new SendGrid\Email();
    $email
        ->addTo($address)
        ->setFrom($address)
        ->setSubject($title)
        ->setText($text)
        ->setHtml($text)
    ;
    $sendgrid->send($email);
    $db-> $query = "
          INSERT INTO sent_mail (email, campaigns, campaign_version)
          VALUES ($address, $campaign, $campaign_version)"; echo 'great success';
}

A: I think you are looking for the below code..
i think the below code might help a bit
    $get_records = mysql_query('SELECT crawler.email as `email_val` FROM crawler LEFT JOIN sent_mail ON crawler.email = sent_mail.email WHERE sent_mail.campaigns <> "$campaign"');

$i = 1;
while($data = mysql_fetch_assoc($get_records)){

    $to = $data['email_val'];
    $subject = 'Your Subject';

    // Always set content-type when sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

    // More headers
    $headers .= 'From: Your Name <you@you.com>' . "\r\n";

    $sendmail = mail($to,$subject,$message,$headers);
    if($sendmail){
        $insert = mysql_query("INSERT INTO sent_mail (email, campaigns, campaign_version)
          VALUES ('your value', 'your value', 'your value')");
        if($insert){
            echo  $i.'Value inserted & Mail sent to'.$data['email'];
        }else{
            echo  $i.'Value not inserted but Mail sent to'.$data['email'];
        }
    }else{
        echo  $i.'Mail sending fail to'.$data['email'];
    }
$i++;
}

Note: Before running the above code make sure you have established database connection.


text:
Q: Setting modals size to 100% I have created a modal inside a button-container which utilizes some flex display elements.
The problem occurs when I want to size the .modal-mask to a 100% of width/height to the whole page (body) size which is my goal here, I can't seem to get it to adjust properly without disturbing my button-container elements.
In short, I want the inner div .modal-mask to be sized 100% to the body
Project Fiddle: https://jsfiddle.net/est857q0/
HTML:

    <htmlmodal v-if="showModal === 'html-modal'" @close="showModal = false"></htmlmodal>

    <csmodal v-if="showModal === 'cs-modal'" @close="showModal = false"></csmodal>

CSS:
    /*Global*/

html {
  margin-right: calc(100% - 100vw);
  /*overflow: hidden;*/
}

body {
  margin: 0 auto;
  background-image: url('../images/wallpaper.jpg');
  font-family: 'Josefin Sans', sans-serif;
}

*::selection {
  background-color: red;
}

/*Header*/

h1 {
  text-transform: uppercase;
  width: 100%;
  font-size: 9vw;
  text-align: center;
  margin-top: 4vh;
}

/*Containers*/

#button-container {
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;
  -webkit-flex-flow: row wrap;
  justify-content: space-around;
  margin-top: 40vh;
  margin-left: 50vw;
  transform: translate(-50%, -70%);
  width: 90vw;
  height: 45vh;
  align-items: baseline;
  background: linear-gradient(to right, transparent 0%, #fff 33%, #fff 66%, transparent 100%);
}

#button-container li {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

#button-container .html-text-block,
.cs-text-block {
  position: absolute;
  bottom: 4px;
  width: 100%;
  height: 30%;
  box-sizing: border-box;
  background-color: #fff;
  padding-left: 5px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
  transition: box-shadow 0.5s cubic-bezier(.25, .8, .25, 1), transform 0.5s cubic-bezier(.25, .8, .25, 1);
}

#button-container .htmllogo,
#button-container .csharplogo {
  width: 150px;
}

#button-container {
  border: 1px solid #000;
}

img:hover {
  transform: scale(1.1);
}

/* THE MODAL CSS SECTION */

/*Main Modal container*/

.modal-mask {
  position: fixed;
  z-index: 9998;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .5);
  display: table;
  transition: opacity .3s ease;
}

.modal-wrapper {
  display: table-cell;
  vertical-align: middle;
}

.modal-container {
  width: 300px;
  margin: 0px auto;
  padding: 20px 30px;
  background-color: #fff;
  border-radius: 2px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, .33);
  transition: all .3s ease;
  font-family: Helvetica, Arial, sans-serif;
}

.modal-content {
  margin: 20px 0;
}

I attempted to set the button-container too 100% : https://jsfiddle.net/est857q0/ yet this messes up the flow


text:
Q: Button is out of container in Bootstrap I'm using Bootstrap 3 to design my website. In a large window my button appears fine within its gray box and border.  However, when I resize the window to check responsiveness, the button ends up being outside the boundaries of the container.
Here's my code:

<?php echo __("Test");?>

<?php echo __("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in est nec mauris dapibus porta sit amet sit amet diam. Cras sit amet imperdiet elit. Nunc vehicula consectetur augue a pretium.");?>

  <?php echo __("Test");?>

And here's the css for the gray-box.
.gray-box {
  background-color: #F5F4F4;
  border: 1px solid #D3D3D3;
  border-radius: 10px;
  padding: 10px;
}

Anyone know what I'm doing wrong or what needs to be done? Thanks!

A: You just forgot to add the btn class to your button.  Buttons always require the btn class in addition to the btn-default (or -primary, etc.).  The btn class styles the element to look like the button and the btn-* classes apply the appropriate color and hover styles.

A: Two solutions off the top of my head.
1) Throw a .clearfix in after your pull-right to reset it:

Button

2) Put the button in its own div:

  Button

Also, no need to classify col-xs-12 and col-sm-12 and col-md-4 — the default is col-xs-12 until it hits something else, so you can just do col-md-4 for the same result.


text:
Q: SCV import : Special characters not supported I imported CSV file to Sendible.com (Facebook publication scheduler) folowing those instructions : http://blog.sendible.com/tag/csv/
Problem : When I write a "Message" that contain special caracters, result looks wrong. (CSV model : Message,Subject,SendDate)
"message" exemple :
Règle n°1 : Respecter les lois.

Result on the website sheduler prevew and on facebook when it was published :
R�gle n�1 : Respecter les lois.

So I tried to use HTML like this :
Règle n°1 : Respecter les lois.

Result looks right on the website sheduler prevew :
Règle n°1 : Respecter les lois.

but when it was published on facebook, it looks wrong :
Règle n°1 : Respecter les lois.

So if you have something that could help me, let me know. Thank you beforehand

A: � indicate the unicode replacement character, encoded in utf-8 (0xEF 0xBF 0xBD) and interpreted in cp1252 (�). In most cases it indicates that something was decoded in an UTF encoding, where that something was encoded in some other encoding.
The least you could do is to save the file as UTF-8 and then upload again:

*

*Open the original file, see that you see what you expect

*Select save as

*In the save as dialog, look for the tools dropdown menu left to the save button; select Web options

*In the web options dialog, select Encoding tab

*In the encoding tab, select Unicode (UTF-8) from the dropdown menu

*Save the file as CSV

*Upload the new file

Edit: It seems this doesn't actually work, seeing the resulting file in a hex editor and it still is cp1252...
But since csv is a plain text format, you can open it in a normal text editor like notepad, and then save as, and select UTF-8 from the encoding menu.


text:
Q: c# - Get a list of Type objects from another DLL I have a web app that uses 2 custom DLLs.  One is a mini-ORM I made on top of Dapper and the other is a class library containing all my model classes.  My ORM has a class that runs at startup, scans a provided package for types and builds a field registry for the ORM to use.  This class used to be in the same class library as the models and it worked perfectly since it was able to find the classes within its own class library.  Ever since I moved it to the ORM library, it (predictably) stopped working because of this line :
var types = Assembly.GetAssembly()
            .GetTypes()
            .Where(t => t.IsClass)
            .Where(t => t.Namespace != null)
            .Where(t => t.Namespace.StartsWith(packageName));

I tried replacing GetAssembly() by GetEntryAssembly() thinking the calling web app would encapsulate all the model classes it found in the models library but it looks like I was wrong.
My question in a nutshell is : Is there a way to access types contained in a DLL from a different DLL through a parent web app that references both?

A: Yes it is possible, but the way depends on your application.
You can search for types in all loaded assemblies
var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(t => t.IsClass)
    .Where(t => t.Namespace != null)
    .Where(t => t.Namespace.StartsWith(packageName));

Or instead of searching all types in all assemblies you can search in a single assembly by name
var types = AppDomain.CurrentDomain.GetAssemblies()
    .Single(a => a.GetName().Name == packageName)
    .GetTypes()
    .Where(t => t.IsClass)
    .Where(t => t.Namespace != null)
    .Where(t => t.Namespace.StartsWith(packageName));

The above code assumes the assembly is already loaded.
If you know any type inside the assembly
var types = typeof(SomeKnownType)
    .GetTypes()
    .Where(t => t.IsClass)
    .Where(t => t.Namespace != null)
    .Where(t => t.Namespace.StartsWith(packageName));

The above will ensure the assembly is loaded since you accessed a type in the assembly. Or you can manually load the assembly if it is not already loaded
var types = Assembly.Load(packageName)
    .GetTypes()
    .Where(t => t.IsClass)
    .Where(t => t.Namespace != null)
    .Where(t => t.Namespace.StartsWith(packageName));