text:
Q: Interleaving iterator methods Lets say we have an Iterator:
Iterator i;

And two Java methods:
static X f(Iterator i)
static Y g(Iterator i)

They both process through an iterator and produce a result, say "sum", "product", or something else.
Let say the results of these calls for a given i is:
x == f(i)
y == g(i)

And lets say we have another class:
class Pair<X,Y>
{
  public X x;
  public Y y;
}

I want to write a method:
static Pair<X,Y> h(Iterator i)

So that:
h(i) == Pair<X,Y>(x,y);

How can I write h without modifying or rewriting f or g? The issue is that I may not be able to copy the iterator (it could be an input stream for example), so it seems like me that both f and g have to use the iterator in "parallel". I'd rather not put the entire contents of the iterator into a list, and it may not be possible, as if I'm streaming a large source I might not have enough memory. I don't require the solution have multiple threads however, and would prefer a simpler approach if possible.

A: This is impossible to do with just the iterator you have. You'll need a quite elaborate scheme where akin to *nix's tee command, just for Java iterators: an object which contains your initial iterator and consumes it as needed, and can be requested to produce one or more "output" iterators. Inside you could be using a queue to store the unconsumed elements.
If you don't want multithreading, then it is simple to realize on theoretical grounds that you will absolutely have to cache the entire produce of the initial iterator. This is because both your iterator-consuming methods are based on the "pull" approach and will insist on consuming the entire sequence before returning.
BTW in Clojure the project lamina does something very similar, just not with Java iterators, but with a concept it calls "channels".

A: The trick is to get the stacktrace to know which of the two method is calling the iterator.next method.
As long as both callers have not called next(), you block the one ahead.

*

*This is not optimized.

*I tried to make this code Thread safe, but as i wrote it quickly, some synchronization issue may remain. I let you review it ;)

*I let you remove the lot of System.out.println

The originalIterator is based on a List, but use the data structure you wish. As you can see, stream.iterrator() is called only once.
public static class InterleavingIterator<E> implements Iterator<E> {

    private boolean hasNext;
    private E next;

    private final Iterator<E> originalIterator;

    private final Map<String, Integer> stepCaller = Collections.synchronizedMap(new HashMap<String, Integer>());
    private final AtomicInteger curStep = new AtomicInteger(0);

    public InterleavingIterator(Iterator<E> originalIterator, String caller1, String caller2) {
        this.originalIterator = originalIterator;
        stepCaller.put(caller1, 0);
        stepCaller.put(caller2, 0);

        hasNext = originalIterator.hasNext();
    }

    public boolean hasNext() {
        return hasNext;
    }

    public E next() {
        String caller = getCurrentCaller();
        int currentStep = curStep.get();
        System.out.println("caller is " + caller);
        if (stepCaller.get(caller) == currentStep) {
            System.out.println("Caller " + caller + " is on current step. We need to move on.");
            // we should go on next step. But first check that all caller are done with this step.
            while (otherCallerBehind(currentStep)) {
                System.out.println("Other caller are behind. Waiting for them...");
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("Ok, everybody is on current step. Going on.");

            synchronized (curStep) {
                if (currentStep == curStep.get()) {
                    // ok, go on.
                    curStep.incrementAndGet();
                    next = hasNext ? originalIterator.next() : null;
                    hasNext = originalIterator.hasNext();
                    System.out.println("hasNext=" + hasNext + ", next=" + next + ", currentStep=" + curStep.get());
                }
            }

        }
        E next2 = next;
        stepCaller.put(caller, stepCaller.get(caller) + 1);
        System.out.println("Caller " + caller + " is now at step " + stepCaller.get(caller) + ". Returning already fetch next : "
                + next);
        return next2;
    }

    private boolean otherCallerBehind(int currentStep) {
        for (Integer step : stepCaller.values()) {
            if (step < currentStep) {
                return true;
            }
        }
        return false;
    }

    public void remove() {
        throw new RuntimeException("Method remove not supported");
    }

    public String getCurrentCaller() {
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        //            System.out.println(stackTraceElements[3].getMethodName());
        return stackTraceElements[3].getMethodName();
    }

}

public static void main(String[] args) {

    List<Integer> stream = Arrays.asList(1, 2, 3, 4, 5);

    final InterleavingIterator<Integer> interleavingIterator = new InterleavingIterator<Integer>(stream.iterator(), "f", "g");

    final AtomicInteger fres = new AtomicInteger(-1);
    final AtomicInteger gres = new AtomicInteger(-1);

    new Thread() {
        @Override
        public void run() {
            fres.set(f(interleavingIterator));
        };
    }.start();

    new Thread() {
        @Override
        public void run() {
            gres.set(g(interleavingIterator));
        };
    }.start();

    while (fres.get() == -1 && gres.get() == -1) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    System.out.println(fres);
    System.out.println(gres);
}

public static Integer f(Iterator<Integer> i) {
    Integer sum = 0;
    while (i.hasNext()) {
        sum += i.next();
    }
    return sum;
}

public static Integer g(Iterator<Integer> i) {
    Integer prod = 1;
    while (i.hasNext()) {
        prod *= i.next();
    }
    return prod;
}

A: Since you probably know what you are iterating through, you can get the values, put it into a new list, and pass it's iterator to the function.
Pair<X,Y> getPair(Iterator i) {
  ValObj value = null;
  List<ValObj> artList = new LinkedList<ValObj>();

  while ((value=i.next())!=null) {
    artList.add(value);
  }

  X x = f(artList.iterator());
  Y y = g(artList.iterator());

  return new Pair<X,Y>(x,y);
}

Right now I noticed that you do not want to store the contents in a list. If that is the case, without any more details about the iterator, I believe it is impossible to do it.


text:
Q: VS2012 - Disable parallel test runs I've got some unit tests (c++) running in the Visual Studio 2012 test framework.
From what I can tell, the tests are running in parallel. In this case the tests are stepping on each other - I do not want to run them in parallel!
For example, I have two tests in which I have added breakpoints and they are hit in the following order:

*

*Test1 TEST_CLASS_INITIALIZE

*Test2 TEST_CLASS_INITIALIZE

*Test2 TEST_METHOD

*Test1 TEST_METHOD

If the init for Test1 runs first then all of its test methods should run to completion before anything related to Test2 is launched!
After doing some internet searches I am sufficiently confused. Everything I am reading says Visual Studio 2012 does not run tests concurrently by default, and you have to jump through hoops to enable it. We certainly have not enabled it in our project.
Any ideas on what could be happening? Am I missing something fundamental here?

A:
Am I missing something fundamental here?

Yes.
Your should never assume that another test case will work as expected. This means that it should never be a concern if the tests execute synchronously or asynchronously.
Of course there are test cases that expect some fundamental part code to work, this might be own code or a part of the framework/library you work with. When it comes to this, the programmer should know what data or object to expect as a result.
This is where Mock Objects come into play. Mock objects allow you to mimic a part of code and assure that the object provides exactly what you expect, so you don't rely on other (time consuming) services, such as HTTP requests, file stream etc.
You can read more here.
When project becomes complex, the setup takes a fair number of lines and code starts duplicating. Solution to this are Setup and TearDown methods. The naming convention differs from framework to framework, Setup might be called beforeEach or TestInitialize and TearDown can also appear as afterEach or TestCleanup. Names for NUnit, MSTest and xUnit.net can be found on xUnit.net codeplex page.

A simple example application:

*

*it should read a config file

*it should verify if config file is valid

*it should update user's config

The way I would go about building and testing this:

*

*have a method to read config and second one to verify it

*have a getter/setter for user's settings

*test read method if it returns desired result (object, string or however you've designed it)

*create mock config which you're expecting from read method and test if method accepts it

*

*at this point, you should create multiple mock configs, which test all possible scenarios to see if it works for all possible scenarios and fix it accordingly. This is also called code coverage.

*create mock object of accepted config and use the setter to update user's config, then use to check if it was set correctly

This is a basic principle of Test-Driven Development (TDD).
If the test suite is set up as described and all tests pass, all these parts, connected together, should work perfectly. Additional test, for example End-to-End (E2E) testing isn't necessarily needed, I use them only to assure that whole application flow works and to easily catch the error (e.g. http connection error).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to send a model in jQuery $.ajax() post request to MVC controller method In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:
$.ajax({
    url: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    //data:  ??????
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

Every time there is a post, I need to increment the value attribute in the model:
public ActionResult Modelpage(MyModel model)
    {
        model.value = model.value + 1;

        return PartialView("ModelPartialView", this.ViewData);
    }

But the model is not passed to the controller when the page is posted with jQuery AJAX request.  How can I send the model in the AJAX request?

A: The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.
As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.
For example, the Javascript:
var values =
{
    "Name": "Chris",
    "Color": "Green"
}

$.post("@Url.Action("Update")",values,function(data)
{
    // do stuff;
});

The model:
public class UserModel
{
     public string Name { get;set; }
     public string Color { get;set; }
     public IEnumerable<string> Contacts { get;set; }
}

The controller:
public ActionResult Update(UserModel model)
{
     // do something with the model

     return Json(new { success = true });
}

A: I have an MVC page that submits JSON of selected values from a group of radio buttons.
I use:
var dataArray = $.makeArray($("input[type=radio]").serializeArray());

To make an array of their names and values.  Then I convert it to JSON with:
var json = $.toJSON(dataArray)

and then post it with jQuery's ajax() to the MVC controller
$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json,
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});

Which sends the data across as native JSON data.
You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.
To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.
Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller.  It's works wonderfully for me.
Article on MVC JSON deserialization

A: This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.
I am achieving this either by a double click event on a grid row or click event on a button of some sort.
@model TestProject.Models.TestModel

<script>

function testButton_Click(){
  var javaModel ={
  ModelId: '@Model.TestId',
  CreatedDate: '@Model.CreatedDate.ToShortDateString()',
  TestDescription: '@Model.TestDescription',
  //Here I am using a Kendo editor and I want to bind the text value to my javascript
  //object. This may be different for you depending on what controls you use.
  TestStatus: ($('#StatusTextBox'))[0].value,
  TestType: '@Model.TestType'
  }

  //Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox
    //selected value. This puzzled me due to the conversion to Json object in the Ajax call.
  //By parsing the Type to an int this worked.

  javaModel.TestType = parseInt(javaModel.TestType);

  $.ajax({
      //This is where you want to post to.
      url:'@Url.Action("TestModelUpdate","TestController")',
      async:true,
      type:"POST",
      contentType: 'application/json',
      dataType:"json",
      data: JSON.stringify(javaModel)
  });
}
</script>

//This is your controller action on the server, and it will autobind your values
//to the newTestModel on post.

[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
 TestModel.UpdateTestModel(newTestModel);
 return //do some return action;
}

A: If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.
In our app, we do this with an extension method:
public static class JsonExtensions
{
    public static string ToJson(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

On the view, we use it to render the model:
<script type="javascript">
  var model = <%= Model.ToJson() %>
</script>

You can then pass the model variable into your $.ajax call.

A: I think you need to explicitly pass the data attribute.  One way to do this is to use the
data =  $('#your-form-id').serialize();
This post may be helpful.
Post with jquery and ajax
Have a look at the doc here..
Ajax serialize

A: you can create a variable and send to ajax.
var m = { "Value": @Model.Value }

$.ajax({
    url: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    data:  m,
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

All of model's field must bo ceated in m.

A: In ajax call mention-
data:MakeModel(),

use the below function to bind data to model
function MakeModel() {

    var MyModel = {};

    MyModel.value = $('#input element id').val() or your value;

    return JSON.stringify(MyModel);
}

Attach [HttpPost] attribute to your controller action
on POST this data will get available


text:
Q: How to postgres search with two search text parameter, Search FIlter text 1 && search filter text 2 How to Postgres search with two search text parameter ,  pg-search + Search FIlter 1 + search filter 2 .
How to search in pg_Search  output I want union of  "filter 1" && "filter 1"
 @output = PgSearch.multisearch("filter 1") +  PgSearch.multisearch("filter 2")

A: I'm the author and maintainer of pg_search.
Search terms are joined by AND by default in PostgreSQL full text search. Thus, you could simply do this:
 @output = PgSearch.multisearch("filter 1 filter 2")

Assuming you have the query terms in string variables, it would look something like one of these:
 @output = PgSearch.multisearch("#{query1} #{query2}") # if query1 and query2 are strings
 @output = PgSearch.multisearch(queries.join(" "))     # if queries is an array of strings

Joining by OR is a lot more complicated. I don't yet have an easy solution for it, although it should be possible.


text:
Q: Programming a simple compiler I am writing a compiler for a simple language.
I made a lexer/tokenizer that takes a file and prints the tokens in stdout.
Now I want to to make the syntactical analysis, but I don't know how to modify my lexer in order to take the tokens as input.

*

*A linked list is extremely inefficient for large files (source files around 80MB take about 1.3GB of ram)

*I could modify my lexer to give the next token every time it is called (idea taken from the Dragon Book), but I don't know what I will do if somewhere in the process I have to go back and read a previous token.

What is the right way to do these things?

A: Implementing a nextToken() method in the lexical analyser is the standard way. This method is called by the parser (or syntax analyser) until the entire input has been consumed.

but I dont what I will do if somewhere in the process i have to go back and read a previous token

This is not usually the case. But, what the parser may need to do is 'push back' a token (or a number of tokens depending on the lookahead of the parser) which has already been seen. In this case the lexer provides a pushBack(Token) which ensures that the next call to nextToken() will return the supplied token, rather than the next token appearing in the input.

A:
but I dont what I will do if somewhere in the process i have to go back and read a previous token

It sounds like your matches are too greedy.
You might look into Backtracking


text:
Q: Parsing JSON in Retrofit android? I'm trying to parse the following JSON structure using Retrofit on android.
{
    "payload": [
        {
          "name": "Rice",
          "brands": [
            {
              "name": "Dawat",
              "subProducts": [
                {
                  "id": 1,
                  "name": "Basmati Long Grain",
                  "creditDays": 20,
                  "currency": "$",
                  "willDeliver": false,
                  "minPrice": 250,
                  "maxPrice": 400,
                  "sku": "1Kg",
                  "uom": ""
                }
              ]
            }
          ]
        }
      ],
      "messages": []
    }

I have made models using http://www.jsonschema2pojo.org/. The keys I'm particularly are payload-->name, brands-->name and subProducts-->name. Below is what I've tried so far. Can anyone please help? I can't parse this JSON Structure using retrofit
       productDetails.enqueue(new Callback<GetProductDetailsByPhoneNumber>() {
        @Override
        public void onResponse(Call<GetProductDetailsByPhoneNumber> call, Response<GetProductDetailsByPhoneNumber> response) {
            Toast.makeText(getApplicationContext(), "Response mil gaya", Toast.LENGTH_LONG);
            List<Payload> subProducts = new ArrayList<Payload>(response.body().payload);
        }

        @Override
        public void onFailure(Call<GetProductDetailsByPhoneNumber> call, Throwable t) {

        }
    });

Interface:
@GET("wholesaler/getProductDetailsByPhoneNumber")
Call<GetProductDetailsByPhoneNumber> getProducts(@Query("phoneNumber") String number);

getDService()
public API getDService(){
    /**
     * The Retrofit class generates an implementation of the API interface.
     */
    if(service == null){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        service = retrofit.create(API.class);
    }
    return service;
}

Payload.java
public class Payload {

public String name;
public List<Brand> brands;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public List<Brand> getBrands() {
    return brands;
}

public void setBrands(List<Brand> brands) {
    this.brands = brands;
}
}

A: Try using this, as you are not providing your "Payload"o bject
 productDetails.enqueue(new Callback<JsonObject>() {
    @Override
    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {

      if(response.body()!=null{
         JsonObject jsonObject=response.body();
         if(response.code() == 200){
            if(jsonObject.has("payload"){
              JsonArray dataArray = jsonObject.getAsJsonArray(HAS_DATA);
              if (dataArray.size() > 0) {
                Toast.makeText(getApplicationContext(), "Response Called", Toast.LENGTH_LONG);

                 //your further code

              }
            }
         }
      }

    }

    @Override
    public void onFailure(Call<JsonObject> call, Throwable t) {

     //logic for if response fails

    }
});

A: Use this code in your onResponse:
if(response.code()==HttpsURLConnection.HTTP_OK) {   //HttpOk is the response code for 200
    if (response.body() != null) {
        if (response.body().payload!= null) {
            //data is there in an array of type payload
            //save all the data there
            //like you want the name, you can get that by response.body().payload.name and you will get "rice"
            //similarly if you want the name which is in subproducts array use : response.body().payload.get(0).brands.get(0).subProducts.get(0).name and you
            //  will get "Basmati Long Grain"
        }
    }
}

The code will help you deserialise all the data from the JSON and you can store that wherever you want. Plus I will recommend you to keep a check on other response codes as well(such as 400 for bad request, 500 for internal server error etc). See here, you have your payload in an array, and there was only one element in it, that is why I have used payload.get(0). In case of multiple elements in the array you need to use a loop and then fetch the values, same goes for your brands and subProduct array.

A: You are trying to get an object PayLoad, and you have
{
"payload": [
    {
      "name"

this means it doesn't start with a parent, so you need to save the answer in a List like List and letter in the iteration you can use Response.get(position) <-- and this one going to be your payload number position, I hope this can help you


text:
Q: How to refresh gmap markers in primefaces p:gmap after updating the gmap with new markers I have problem on a project with Gmap component of Primefaces 3.5 I'm using JSF2.0.
I have this command Button that do filtering on the markers and most important updates mapForm
<h:form id="epsFilterForm">
      <p:commandButton action="#{mapMB.filterProjects}" value="#{bundle['filter'] }" update=":mapForm" />
</h:form>

mapForm:
<h:form id="mapForm">
<p:gmap id="googleMap" center="48.849988,2.3805715" zoom="11"  type="TERRAIN" fitBounds="false" model="#{mapMB.advancedModel}"
    widgetVar="wmap" style="width:1000px;height:700px;display: inline-block;" >

    <p:ajax event="overlaySelect"  listener="#{mapMB.onMarkerSelect}" />
    <p:gmapInfoWindow>
        <p:outputPanel style="text-align:center;display:block;margin:auto:">
            <p:panelGrid columns="2" styleClass="InfoTable" >

                <p:outputLabel value="#{bundle['ep.operation.name'] }" />
                <p:outputLabel value="#{mapMB.selectedEp.opName}" />
            </p:panelGrid>
        </p:outputPanel>
    </p:gmapInfoWindow>
</p:gmap>

MapMB - scope - Session scope
populateAdvancedModel()
public void populateAdvancedModel(List<EP> eps) {
    advancedModel = new DefaultMapModel();
    int count = 0;
    Marker marker;
    for (EP ep :eps) {
        //advancedModel.addOverlay(new Marker(coord1, "Konyaalti", "konyaalti.png", "http://maps.google.com/mapfiles/ms/micons/blue-dot.png"));
        System.out.println("Integer.toString(ep.getId()):"+Integer.toString(ep.getId()));
        marker =  new Marker(new LatLng(  Double.parseDouble(ep.getLatitude()) ,  Double.parseDouble(ep.getLongitude())));
        marker.setTitle( Integer.toString(count));
        advancedModel.addOverlay(marker);
        count++;
    }
}

filterProjects()
public String filterProjects() {
    //FilterMB filterMB = (FilterMB) JSFUtil.getManagedObject("filterMB");
    eps = EPDAO.filterEPs(client, architect, realizationType, state, selectedCert);
    populateAdvancedModel(eps);
    return null;
}

onMarkerSelect()
public void onMarkerSelect(OverlaySelectEvent event) {
    Marker marker = (Marker) event.getOverlay();
    String markerTitle = marker.getTitle();
    selectedEp = eps.get(Integer.parseInt(markerTitle));
}

When I load the page for first time everything is OK. Info (p:gmapInfoWindow ) window is loading and information for EP variable is there. But when I click the command button in epsFilterForm (that has some input fields that i haven't posted here) the map is updated and the filtered markers are there and they obviously have title when i hover on them, but overlaySelect event is not working in the same way. I thing that when page is loading for the first time there is some initial script that puts that behavior on the markers but when I refresh the map this initial script is not running again and that's is why when I click on the marker and overlaySelect event is fired I have null pointer Exception in onMarkerSelect() method (marker is null).      IMPORTANT - this is working without a problem on local server but when I deploy it to google app engine it's working as i described above.

A: The DefaultMapModel of the gmap (referenced from 'model' attribute in p:gmap element) has no proper functionality to clear, unlike other Model objects, like e.g. the EventModel of p:schedule.
IF you provide that object from a SessionScoped controller, even if you recreate that object from scratch, the p:gmap for some reason is keeping reference to the first mapModel that was provided. Practically this means that all new/updated mapmodel objects are not being used, except the first one.
So, a tricky point of gmap that is going to be updated (adding/removing markers, overlays etc) is that the mapmodel object should be retrieved from a RequestScoped object.
Now, another option, would be iterating through all the markers. You can find similar posts here. This way you can keep your backing bean as SessionScoped, but again, you are not supposed to create a new mapModel.
EDIT: I'm m getting the impression that the view fails to update the markers, not the mapModel itself. Anyway, the solution is the same. It's just that sometimes you can't drop the bean Scope to request (e.g. fetching an info window on overlaySelect), so you end up refreshing the markers

A: I use the onGeocode event, in the backing bean check if there are any loaded markers. Remove these markers before adding your new markers. Hope this helps.
public void onGeocode(GeocodeEvent event) {

    try {

        List<GeocodeResult> results = event.getResults();

        if (results != null && !results.isEmpty()) {
            LatLng center = results.get(0).getLatLng();
            centerGeoMap = center.getLat() + "," + center.getLng();

            List<Marker> markers = geoModel.getMarkers();

            if (markers != null && markers.size() > 0) {

                geoModel.getMarkers().removeAll(markers);
            }

            for (int i = 0; i < results.size(); i++) {
                GeocodeResult result = results.get(i);
                geoModel.addOverlay(new Marker(result.getLatLng(), result.getAddress()));

            }
        }
    } catch (Exception e) {
        logger.error("Could not update GMap from geoCode", e);
    }
}

A: I have a similar situation. In fact what I am trying to do is to update the markers in gmap after the gmap is rendered. As @yannicuLar said, the mapModel is retrieved once at the beginning when map is rendered. Later update on mapModel is not reflected on the map.
My solution is to use primefaces functionality to trigger executing javascript from server side.
In xhtml:
            var markers = [];
            function clearMarkers() {
                for (var i = 0; i < markers.length; i++) {
                      markers[i].setMap(null);
                 }
                markers=[];
            }
            function addMarkers() {
                for (var i = 0; i < markers.length; i++) {
                    PF('yourMap').addOverlay(markers[i]);
                   }
            }

In java/server side, at the place where you are supposed to update your mapModel with lat/lng, you add codes as below:
To clear the markers:
RequestContext.getCurrentInstance().execute("clearMarkers()");

Suppose you have multiple marks, to iteratively add all the markers to marker array:
RequestContext.getCurrentInstance().execute("var currentMarker = new google.maps.Marker({ position:new google.maps.LatLng("
                    + latitude + ", " + longitude
                    + "), map:PF('yourMap').getMap()});"
                    + "markers.push(currentMarker);");

To add markers to map after the marker array is populated:
RequestContext.getCurrentInstance().execute("addMarkers()");

It is tested, and works for me.


text:
Q: com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused: connect I've been trying to start and stop Jetty automatically in  mvn clean install phase for my unit tests. The annoying thing is when I deploy my war file in JBoss all the tests are working fine, however, when I try to use maven-jetty-plugin I have a Connection refuse: connect error. I'm sure about that Jetty starts but doesnt recognize the URLs so that it can't establish the connection.
pom.xml
        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>8.1.13.v20130916</version>
            <configuration>
                <webApp>
                    <contextPath>/</contextPath>
                </webApp>
                <scanIntervalSeconds>10</scanIntervalSeconds>
                <stopKey>foo</stopKey>
                <stopPort>9999</stopPort>
            </configuration>
            <executions>
                <execution>
                    <id>start-jetty</id>
                    <phase>pre-integration-test</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <scanIntervalSeconds>0</scanIntervalSeconds>
                        <daemon>true</daemon>
                    </configuration>
                </execution>
                <execution>
                    <id>stop-jetty</id>
                    <phase>post-integration-test</phase>
                    <goals>
                        <goal>stop</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

default web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0">
</web-app>

and my other classes
import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

import com.buraktas.resource.DefaultBookResource;

@ApplicationPath("/services")
public class BaseApplication extends Application {

    private Set<Object> singletons = new HashSet<Object>();

    public BaseApplication() {

        singletons.add(new DefaultBookResource());
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

entity class
public class BookEntity {
private int    id;
private String title;
private String author;
private double price;

... setters and getters

}
resource interface
@Path("/book-service")
public interface BookResource {

    @POST
    @Path("/create")
    @Consumes("application/json")
    @Produces("application/json")
    public BookEntity createBook(BookEntity bookEntity);

}

and the implementation of it
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import com.buraktas.entity.BookEntity;

public class DefaultBookResource implements BookResource {

    private Map<Integer, BookEntity> list      = new HashMap<Integer, BookEntity>();
    private AtomicInteger            idCounter = new AtomicInteger();

    @Override
    public BookEntity createBook(BookEntity bookEntity) {

        bookEntity.setId(idCounter.getAndIncrement());
        list.put(bookEntity.getId(), bookEntity);

        return bookEntity;
    }

}

finally test class
public class TestClass {

    private static final String POST_INPUT = "{\"title\" : \"LOTR\",\"author\" : \"J.K.Rowling\",\"price\" : 12.99}";
    private static Client       client;

    @Before
    public void setUp() {

        ClientConfig clientConfig = new DefaultClientConfig();
        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
        client = Client.create(clientConfig);
    }

    @After
    public void close() {

        client.destroy();
    }

    @Test
    public void testCreateSuccess() throws Exception {

        WebResource webResourcePost = client.resource("http://localhost:8080/jersey-rest-client/services/book-service/create");
        ClientResponse response = webResourcePost.accept("application/json").type("application/json").post(ClientResponse.class, POST_INPUT);
        BookEntity responseEntity = response.getEntity(BookEntity.class);

        assertEquals(200, response.getStatus());
        assertEquals("LOTR", responseEntity.getTitle());
        assertEquals("J.K.Rowling", responseEntity.getAuthor());
        assertEquals(12.99, responseEntity.getPrice(), 0.0001);

    }
}

Also you can find the whole implementation from here
https://github.com/flexelem/jersey-client-example
I will appreciate for every response. Thanks anyway


text:
Q: Default activity not found and problems in manifest file image link
android:default activity not found and i use the intent filter on the manifest file but it gave many errors and warnings please help me to resolve this problems The Android version is 3.0.1


text:
Q: iPhone make toolbar visible in UITableView I have a UITableView has a subview of a UIView and I've added a toolbar on top of the UITableView so it should look like this:

However when I actually run it, it looks like this:

So for some reason the UIToolBar isn't showing up. I really don't know why, is anybody able to figure this one out? Thanks in advance.
EDIT: I've changed the simulated metrics like suggested and it still does not show up:

EDIT2: Here is a list of objects as requested by Raixer.

A: Alright. I have a similar setup in my app so I will show you what I did.
I setup a tab bar controller with navigation controllers in each tab (this gives me the navigation bar automatically that is why I use it). If you notice the View on the first tab is being loaded from another nib (that is what I am assuming you are doing). I did this by changing the view's class to my own view controller and then setting the name of the NIB file to load in the Inspector like this:

(source: minus.com)
Then in my other nib file I only have this:

I hope this helps.

A: That's because you configured your nib file without counting with the height of the Tab bar.
The toolbar's height is 49 pixels. So when the view appears all your elements are moved 49 pixels up.
You should got to IB, open your View, go to Attributes Inspector, and in simulated metrics select Tab bar for Bottom Bar.

A: I doubt you will succeed with this approch. UITableViewController is very picky about adding subviews to its UITableView. However, you can have your UITableView handled by a standard UIViewController (just let IB point to a custom class inheritng from UIViewController). Add the table view to the controller's view as a subview and add the toolbar to the outer view.
Then you should be able to add subviews. UITableViewController gives you some convinience and functionality. If you can live without, UIViewController is no disadvantage. If you can't, you'll have to implement it yourself.
Another alternative to get the toolbar: put your table into a UINavigationController. That one comes with a toolbar (on top).


text:
Q: Typescript copy properties of an object using for..in I'm trying to copy the properties of an object using for..in but I got the error:
Type 'Greeter[Extract]' is not assignable to type 'this[Extract]'.
Any ideas how to solve this?
class Greeter {
a: string;
b: string;
c: string;
// etc

constructor(cloned: Greeter) {

    for (const i in this) {
        if (cloned.hasOwnProperty(i)) {
            this[i] = cloned[i];
        }
    }
}

Here is the sample in the typescript playground.
Thanks!

A: The problem is that the type of this is not Greeter it's the polymorphic this type. An unfortunate consequence is that the i in your for loop i typed as keyof this while Greeting can be indexed using a keyof Greeting. These may seem like the same thing, but if you consider that Greeting can be derived, keyof this could potentially contain a lot more members. A similar discussion applies to the value of the indexing operation.
The compiler is not wrong, this may have more keys than Greeter so this is not 100% safe.
The simplest solution is to use a type assertion to change the type of this:
class Greeter {
    a: string;
    b: string;
    c: string;
    // etc

    constructor(cloned: Greeter) {
        for (const i in this as Greeter) {
            if (cloned.hasOwnProperty(i)) {
                this[i] = cloned[i]
            }
        }

    }
}

Or you can iterate over the cloned object:
class Greeter {
    a: string;
    b: string;
    c: string;
    // etc

    constructor(cloned: Greeter) {
        for (const i in cloned) {
            if (cloned.hasOwnProperty(i)) {
                this[i] = cloned[i]
            }
        }

    }
}


text:
Q: Using Objectify to concurrently write data on GAE Let's for example say I have the following objectify model:
@Cache
@Entity
public class CompanyViews implements Serializable, Persistence {

    @Id
    private Long id;
    private Date created;
    private Date modified;
    private Long companyId;

    ........

    private Integer counter;

    ........

    @Override
    public void persist() {
        persist(false);
    }

    @Override
    public void persist(Boolean async) {
        ObjectifyService.register(Feedback.class);
        // setup some variables
        setUuid(UUID.randomUUID().toString().toUpperCase());
        setModified(new Date());
        if (getCreated() == null) {
            setCreated(new Date());
        }
        // do the persist
        if (async) {
            ofy().save().entity(this);
        } else {
            ofy().save().entity(this).now();
        }
    }
}

I want to use the counter field to track the number of views, or number opens or basically count something using an integer field.
What happens now is that for one GAE instance, the following will be called:
A:
CompanyViews views = CompanyViews.findByCompanyId(...);
views.setCounter(views.getCounter() + 1);
views.persist();

and for another instance:
B:
CompanyViews views = CompanyViews.findByCompanyId(...);
views.setCounter(views.getCounter() + 1);
views.persist();

If they both read the counter at the same time or read the counter before the other instance has persisted it, they will overwrite each other.
In MySQL / Postgres you get row-level locking, how does one do a "row-level lock" for Objectify entities on GAE?

A: You need to use transactions when concurrently updating entities.
Note that since you update same entity you will have a limitation of about 1 write/s. To work around that look into sharding counters.


text:
Q: Missing 'Ajax' does not exist in the namespace 'System.Web.Mvc' I am trying out examples from a book.  The first one is really simple .. a few lines of code in a view (MVC).
I run the code but get an error :
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0234: The type or namespace name 'Ajax' does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)
Source Error:

Line 22:     using System.Web.WebPages;
Line 23:     using System.Web.Mvc;
Line 24:     using System.Web.Mvc.Ajax;
Line 25:     using System.Web.Mvc.Html;
Line 26:     using System.Web.Routing;

Source File: c:\Users\Aindriu\AppData\Local\Temp\Temporary ASP.NET Files\root\6882868f\b519e811\App_Web_index.cshtml.a8d08dba.h-o4pos5.0.cs    Line: 24

I fixed the problem - I right clicked the solution in Solution Properties (on the right) and selected Manage Nuget Packages - i typed in MVC on top right search bar - and installed MVC.... it installed a whole load of files and my program worked..... but it added code to the solution I am working on..
Is there a easy way to get around this error ? I don't want to have to keep doing this every time I create a MVC program...

A: If you are using Visual Studio, from the project's References select the System.Web.Mvc dll. At the Properties Window set the Copy Local attribute to True.
You could even copy the necessary references to the bin\Debug or bin\Release directory (whichever you would use) manually, but setting it to happen automatically by Visual Studio is far better.

A: With newer versions of MVC, the preferred method is to use the NuGet package manager. Under: View > Other Windows > Package Manager Console. Type:
Install-Package Microsoft.AspNet.Mvc -Version 4.5.1

You should do this for every Mvc project.


text:
Q: Any way we can passing a value from one page to another page (from difference window)? Just wondering will it be possible to passing a value from one page (window browser 1) to another page (window browser 2) without reloading the page?
Example:
I have a page called test1.aspx, and inside this page with a button, when user clicked on this button, this will pop-up a new browser by displaying test2.aspx.
Inside test2.aspx will contain some data and when user clicked on the 'close' button there, it will passing the value back to test1.aspx without reload the page for test1.aspx (by fill in all data from test2.aspx into the fields in test.aspx).
Does anyone know will it possible? also any way I can find out some example? Thanks.

A: Yes you can do this by using AJAX and JQuery.
From the POP-UP window you can store the value in the Session variable, You have to do some code of Jquery when POP-UP Window is closed and then reload the particular portion in your page using AJAX. This is how you can do this.
You need to search the Jquery using which you can get the event of closing the POP-UP Window.


text:
Q: Using Prism.js line-highlight plugin with Next.js app causes "Text content did not match" error I have basic Prism.js functionality working with my Next.js site by doing the following things:
package.json
  "dependencies": {
   ...
    "next": "9.5.3",
    "react": "16.13.1",
    "typescript": "3.9.4",
    "prismjs": "1.22.0"
  },
  "devDependencies": {
    ...
    "@types/prismjs": "1.16.2"
  }

pages/_app.tsx
...
import "prismjs/themes/prism-tomorrow.css";
...

pages/blog-article.tsx
...
import Prism from "prismjs";
import "prismjs/components/prism-hcl";
import "prismjs/plugins/line-highlight/prism-line-highlight";
...

export default function BlogArticle(){
  useEffect(() => {
    if (typeof window !== 'undefined') {
      Prism.highlightAll();
    }
  }, []);

  return

      {`xxx`}

}

That all works fine and source code is hightlighted properly - the problem comes when I try to use the line-highlight plugin for Prism.
When I add the data-line attribute to the HTML, as following.
pages/blog-article.tsx
...

      {`xxx`}

...

I get the following error:
Warning: Text content did not match. Server: "xxx
" Client: "xxx"

So, if I'm understanding right: this is an error from Next.js, telling me that my server-rendered and client-rendered content are different?
Looking at the error message, it looks like the plugin is adding a newline at the end of the content, but only during the server-render, not the client-render.
Note that other Prism plugins seem to work; I tried out the line-numbers plugin and it didn't cause this problem.
Is this a bug with Prism.js, the line-highlight plugin or am I doing something wrong?
Is there a workaround I can do to get it going?

A: Initially mount the
 element without the data-line attribute.
In the useEffect, before calling Prism.highlightAll(), imperatively set the data-line attribute:
'use client'
import React, { useEffect, useRef } from 'react'
import Prism from 'prismjs'
import 'prismjs/themes/prism-tomorrow.css'

export default function Code({
  code,
  language,
  lineNumbers,
}: {
  code: string
  language: string
  lineNumbers?: string
}) {
  const ref = useRef<HTMLPreElement>(null)
  useEffect(() => {
    lineNumbers && ref.current?.setAttribute('data-line', `${lineNumbers}`)
    Prism.highlightAll()
  }, [])

  return (

        <code className={`language-${language}`}>{code}

  )
}

Note: One downside is that the page paints with unstyled code blocks. A potential "flash of unstyled content".

Original answer:
Same. The only workarounds I've found so far are to build a custom line highlighter with CSS, such as:

*

*https://css-tricks.com/syntax-highlighting-prism-on-a-next-js-site/#aa-highlighting-lines

*https://www.felixmokross.dev/blog/code-samples-line-highlighting


text:
Q: SQL Server not configured for data access I'm running a SQL Server 2005 database from a VB 6 Application. I connect to the database
through an ODBC DSN.
I renamed the computer on which I'm running the default instance of SQL server from 'Software' to 'IT'. I then ran the sp_dropserver and sp_addserver stored procedures to rename the instance.
On restarting the SQL Server service, the server was able to pick up on the new SQL Server name.
After configuring the ODBC data source name to the new name, the connection was Ok. I'm able to run my application and read records through ADO record sets. However I'm unable to update any recordset using the .Update method. I get the following error instead ... SQL Server not configured for data access
How can I enable data access on the renamed server instance?

A: How to: Rename a Computer that Hosts a Stand-Alone Instance of SQL Server 2005
You should be able to run this but not against any linked server. It's not a linked server. It's local.
EXEC sp_serveroption 'YourServer', 'DATA ACCESS', TRUE

A: Just go to the linked server properties > Server options > Data access --> true
Works on SQL Server 2014.
Regards

A: with this
use master
go

exec sp_serveroption 'server name', 'data access', 'true'
go

linked servers generated for replication still showing same error

A: I just would like to add to the previous answers that, at least in my case here, I needed to enable data access in both places.
for instance:
there is server A and server B
On server A
I have a linked server LB that links me from server A to server B
I need to execute the following:
-- on server A
exec sp_serveroption 'LB', 'data access', 'true'

-- on server B
exec sp_serveroption 'B', 'data access', 'true'

A: I've just come across this error and found that it was caused by me trying to run OpenQuery against the local server (doh!).  Changing the server name to that of an actual linked server resolved my issue.


text:
Q: Missing values remaining after applying sklearn SimpleImputer I'm trying to handle missing values in a list of countries by replacing them with 'US':
imputer_const = SimpleImputer(strategy="constant", fill_value="US")
imputed_X_temp=X_temp.copy()
imputed_X_temp["countryCode"] = pd.DataFrame(imputer_const.fit_transform(imputed_X_temp['countryCode'].array.reshape(-1, 1)))
imputed_X_temp.columns=X_temp.columns

but after checking with
print(" \nCount total NaN at each column in train data : \n\n", imputed_X_temp.isnull().sum())

I still have 10 missing values (vs. 27 before imputation). What am I doing wrong?
Thank you for your help!

A: imputer_const = SimpleImputer(strategy="constant", fill_value="US")
imputed_X_temp = X_temp.copy()
imputed_X_temp["countryCode"] = imputer_const.fit_transform(X_temp['countryCode'].values.reshape(-1, 1)))

If, after this, imputed_X_temp still has missing values, they're most likely from other columns.


text:
Q: Is it faster to read the first element of an array, or the 4000th? Is there any speed difference when reading from the first element of an array rather than the 4000th? Same goes for any other element in an array.
Mostly asking about c++ but any language is alright.
As for the array, it will be an array of integers.

A: If you are specifically calling an element in an array and you know the exact position in the array of the element you need to retrieve, then there will be no difference in speed.  However, if there is a loop involved, or some type of functionality that searches through the array for a specific value, then speed could be impacted.

A: Should be the same. If you know index of element you are looking for, you have nothing to worry about, if not, be careful when looping through large arrays.
Depends on a language probably, but I'm sure that it's true in Java or C/C++, for the rest I really couldn't say.
Okay, now I see you are talking about C++ so you can be sure it' the same.

A: In C++ is exactly the same, that's why arrays are excellent structures in order to do algorithms an a lot of things that depends on that fact.

A: Accessing something in memory given an explicit address is O(1)
Accessing an array element is done by taking the starting position of the array and then adding the offset.
e.g.if arr = 0x000001f0
Access arr[0]   = 0x000001f0 + 0x00000000
Access arr[256] = 0x000001f0 + 0x00000100
[Disclaimer: may vary by OS and virtualization and and and... -- but don't worry about that]


text:
Q: Curve Fitting to Exponential I am currently attempting to find the values of RH and TMP in the function for vapor pressure deficit (VPD) that result in the ideal VPD. So I've defined my functions for VPD and tried to do a non-linear regression but am not getting the curve I am looking for.
import numpy as np
from scipy.optimize import curve_fit

def ES(C):
    es = 0.6108*np.exp((17.27*C)/(C+273.3))
    return es

def EA(RH,es):
    ea = (float(RH)/100)*es
    return ea

def VPD(C,RH):
    es = ES(C)
    ea = EA(RH,es)
    vpd = ea
    return vpd

C = np.linspace(0,50,100)
vpd = [0.5]*len(C)

popt, pcov = curve_fit(VPD, C, vpd)

Which gives me the values for popt and pcov of 10.09132776 and 0.51489686. However, what I would really like to do here is determine the values of RH at these temperature values in C that give me VPD values of 0.5. I may be going about this in the wrong way but I've really been struggling with this for a long time and could really use some outside perspective as to how to go about this task.

A: Assuming your equations are correct which I did not verify you can simply do this:
from sympy.solvers import solve
from sympy import Symbol

r = Symbol('r')
for C in np.linspace(0,50,100):
    result = solve(((r/100)*(0.6108*np.exp((17.27*C)/(C+273.3))))-0.5, r )
    print("For C = {} RH = {}".format(C, result[0]))

This will print the RH for each value of C assuming your equations are correct. I simply substituted the equations and set the resulting equation equal to 0. Just change the -0.5 to -(new VPD) to get the results for a different VPD.


text:
Q: Struts2 input values lost when calling interceptor i have a problem with Struts2
This is my action configuration, before executing the roleDete in the Action, the interceptor is call, but after this, the values of the input are lost, there is no id to delete, if i remove the interceptor then the id to delete exist, could some one guide me to solve this?
<action name="roleDelete" method="roleDelete" class="com.webapp.role.action.RoleAction">
  <interceptor-ref name="validateUser"/>
  <result name="input" type="tiles">usertypePage</result>
  <result name="success" type="redirect">usertypeForm</result>
</action>

Thanks

A: It sounds like you've defined a custom validateUser interceptor stack that doesn't include a required Struts 2 interceptor.  By default, Struts 2 invokes the following interceptors on every request unless you define your own stack (as you've done):
        <interceptor-stack name="defaultStack">
            <interceptor-ref name="exception"/>
            <interceptor-ref name="alias"/>
            <interceptor-ref name="servletConfig"/>
            <interceptor-ref name="i18n"/>
            <interceptor-ref name="prepare"/>
            <interceptor-ref name="chain"/>
            <interceptor-ref name="debugging"/>
            <interceptor-ref name="scopedModelDriven"/>
            <interceptor-ref name="modelDriven"/>
            <interceptor-ref name="fileUpload"/>
            <interceptor-ref name="checkbox"/>
            <interceptor-ref name="multiselect"/>
            <interceptor-ref name="staticParams"/>
            <interceptor-ref name="actionMappingParams"/>
            <interceptor-ref name="params">
              <param name="excludeParams">dojo\..*,^struts\..*</param>
            </interceptor-ref>
            <interceptor-ref name="conversionError"/>
            <interceptor-ref name="validation">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
            <interceptor-ref name="workflow">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
        </interceptor-stack>

My advice would be to go through the above list and add them back in one at a time until you figure out which you need to properly populate your request variable.  You can read more about interceptors in the Struts 2 docs.

A:      <interceptors>
        <interceptor name="vendorStoreInterceptor" class="br.org.myapp.actions.interceptors.VendorStoreInterceptor"></interceptor>

        <interceptor-stack name="defaultStack">
            <interceptor-ref name="exception"/>
            <interceptor-ref name="alias"/>
            <interceptor-ref name="servletConfig"/>
            <interceptor-ref name="i18n"/>
            <interceptor-ref name="prepare"/>
            <interceptor-ref name="chain"/>
            <interceptor-ref name="debugging"/>
            <interceptor-ref name="scopedModelDriven"/>
            <interceptor-ref name="modelDriven"/>
            <interceptor-ref name="fileUpload"/>
            <interceptor-ref name="checkbox"/>
            <interceptor-ref name="multiselect"/>
            <interceptor-ref name="staticParams"/>
            <interceptor-ref name="actionMappingParams"/>
            <interceptor-ref name="params">
              <param name="excludeParams">dojo\..*,^struts\..*</param>
            </interceptor-ref>
            <interceptor-ref name="conversionError"/>
            <interceptor-ref name="validation">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
            <interceptor-ref name="workflow">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
        </interceptor-stack>

        <interceptor-stack name="mainStack">
            <interceptor-ref name="vendorStoreInterceptor"/>
            <interceptor-ref name="defaultStack"/>
        </interceptor-stack>
    </interceptors>

    <default-interceptor-ref name="mainStack"/>

--
Use that. You have to include your interceptor and the defaultStack after (watch the last 'interceptor-stack' with my 'vendorStoreInterceptor' and the 'defaultStack').
That's it!


text:
Q: Parse html from json in c# We have developed class with following procedures which contacts yandex translation api and submit post message for translation html from english to german (etc..) language.
The reason why we are sending html is that we need to translate values in title attributes and urls in document.
Libraries used are RestSharp and HtmlAgilityPack.
Procedure is simple as is :
private RestClient _client = new RestClient("https://translate.yandex.net/api/v1.5/tr.json");
private RestRequest request = new RestRequest("translate");
request.AddParameter("key", key);
request.AddParameter("text", textToTranslate);
request.AddParameter("lang", from + "-" + to);
request.AddParameter("format", "html");
RestResponse response = (RestResponse)_client.Execute(request);
var result = response.Content;

so far so good, we are getting response from yandex.
Now the fun begins :
HtmlDocument htmlDoc = new HtmlDocument();
dynamic typedResult = JsonConvert.DeserializeObject<dynamic>(result);
string text = Convert.ToString(typedResult.text);
text = HtmlAgilityPack.HtmlEntity.DeEntitize(text);
htmlDoc.LoadHtml(HttpUtility.HtmlDecode(text));

First we had lot of exceptions becouse yandex returns html as array in text property of response, html encoded for json.
    HtmlAgilityPack.HtmlEntity.DeEntitize(text)

solve this problem. Now we have lot of \ and \n\r and escape characters in html document, HtmlAgility pack can parse but we are getting wrong values for href attributes in a tags.
We need those attributes href to change url from english to german url. Unfortunately, href attribute is encoded with quotation marks
like so

and forward slash are escaped like :

Hello<\/div>

,so there is a lot of fight to remove those chars, as I have run out of ideas how to deal with this.
Question is:
What is the proper way to parse json encoded html?
I am getting from yandex this response :
{{
  "code": 200,
  "lang": "en-fr",
  "text": [
    "
\n La raison de la popularité pour les hors-bord de l'Atlantique 670,.. Elaphites.\n
\n
\nDétails\n Les îles elaphites demi-journée\n Les îles elaphites journée complète\n L'Île De Mljet\n L'Île De Korcula\n Hvar\n
\n                \n
"
  ]
}}

So I want to get (decoded) value of text json object and pass it to the HtmlAgility pack to translate title attributes.
How I can get clean html without escape chars and quotation marks?
Regards,
Frano Hartman.


text:
Q: In Unity Android build, the black background flash blue light when make the game inactive then awake it To make the fit different screen resolutiosn, I added code below to add black sides when the screen resolution is not the same. It works fine when I open the game in android. But when I sleep the phone, or switch to another app and switch back, the black side start to flash with blue color. Any suggestion what can be the reason of this? Or is there a better way to fix screen resolution? Thanks!
private void Awake()
{
    FitCamera(Camera.main);
}

public void FitCamera(Camera camera)
{
    if (DevelopRate <= ScreenRate)
    {
        camera.rect = new Rect(0, (1 - cameraRectHeightRate) / 2, 1, cameraRectHeightRate);
    }
    else
    {
        camera.rect = new Rect((1 - cameraRectWidthRate) / 2, 0, cameraRectWidthRate, 1);
    }
}

A: Try attach this script to your camera, it will clear the whole screen before rendering.
public class ClearScreen : MonoBehaviour
{
    void OnPreRender()
    {
        GL.Clear(true, true, Color.black);
    }
}


text:
Q: ASP.NET Chart Error On a page (I've called Cashflow.aspx) I have an asp.net chart to plot out some data. It works wonderfully when debugging on my local machine. However, when I try to deploy the site to my staging server there is an error that I can't seem to track down. It fails and redirects back to my default.aspx page. If I comment out the chart and deploy again the rest of the page works just fine.
aspx Page:
<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

Cashflow

                <asp:Chart ID="Chart1" runat="server" Width="1400px" Height="500px">
                    <Series>
                        <asp:Series Name="As Bid Projected Cashflow" ChartType="Line" ChartArea="ChartArea1" BorderWidth="3" BorderColor="#86a44a"></asp:Series>
                        <asp:Series Name="Actual Cashflow" ChartType="Line" ChartArea="ChartArea1" BorderWidth="3" BorderColor="#da8137"></asp:Series>
                    </Series>
                    <ChartAreas>
                        <asp:ChartArea Name="ChartArea1" />
                    </ChartAreas>
                </asp:Chart>

</asp:Content>

Code Behind:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;

namespace MySite
{
    public partial class Cashflow : System.Web.UI.Page
    {
    DataTable tbl;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            LoadData();
            decimal maxValue = 0;

            Chart1.DataSource = tbl;
            Chart1.Series["As Bid Projected Cashflow"].XValueMember = "Period";
            Chart1.Series["As Bid Projected Cashflow"].YValueMembers = "AsBidProjectedCashflow";
            Chart1.Series["Actual Cashflow"].XValueMember = "Period";
            Chart1.Series["Actual Cashflow"].YValueMembers = "ActualCashflow";
            Chart1.Series["Actual Cashflow"].Sort(PointSortOrder.Ascending);

            Chart1.ChartAreas[0].AxisX.LabelStyle.Angle = 45;
            Chart1.ChartAreas[0].AxisY.LabelStyle.Format = "C";
            Chart1.Legends.Add("As Bid Projected Cashflow");
            Chart1.Legends["As Bid Projected Cashflow"].Position.Auto = false;
            Chart1.Legends["As Bid Projected Cashflow"].Position = new ElementPosition(0, 0, 30, 15);
            Chart1.Legends["As Bid Projected Cashflow"].Docking = Docking.Right;
            Chart1.Legends["As Bid Projected Cashflow"].DockedToChartArea = "ChartArea1";
            Chart1.Legends["As Bid Projected Cashflow"].IsDockedInsideChartArea = false;
            Chart1.ChartAreas[0].Position.Auto = false;
            Chart1.ChartAreas[0].Position = new ElementPosition(0, 15, 105, 85);
            Chart1.DataBind();
        }
    }

    private void LoadData()
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter da = new SqlDataAdapter();
        tbl = new DataTable();
        cmd = new SqlCommand("GetCashflow", con);
        cmd.CommandType = CommandType.StoredProcedure;
        da.SelectCommand = cmd;
        da.Fill(tbl);
    }

    protected void btnRefreshCharts_Click(object sender, EventArgs e)
    {
        Response.Redirect("Cashflow.aspx?pnum=" + Request.QueryString["pnum"]);
    }
}
}

(Relevant) Web.config
<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <configSections>

  </configSections>
  <system.web>
    <httpHandlers>
      <add verb="GET,HEAD,POST" path="ChartImg.axd"  type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  />
    </httpHandlers>
    <compilation debug="true" targetFramework="4.6">
      <buildProviders>
        <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
      </buildProviders>
      <assemblies>
        <add assembly="Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845DCD8080CC91" />
        <add assembly="Microsoft.ReportViewer.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845DCD8080CC91" />
        <add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.6" requestValidationMode="2.0" maxRequestLength="262144000" executionTimeout="110" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
        <add namespace="Microsoft.AspNet.Identity" />
      </namespaces>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting"
      assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </controls>
    </pages>
  </system.web>
  <system.webServer>

    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ChartImageHandler" />
      <add name="ChartImageHandler" preCondition="integratedMode"  verb="GET,HEAD,POST"
    path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </handlers>
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory  type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <appSettings>
    <add key="ChartImageHandler" value="storage=file;timeout=20;" />
  </appSettings>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

Network Monitor

All relevant dlls are installed and up to date. Not really sure where to look next to track down the issue. Any pointers are greatly appreciated.

A: The solution was to change this line in my web.config from:
<add key="ChartImageHandler" value="storage=file;timeout=20;" />

to:
<add key="ChartImageHandler" value="storage=memory;deleteAfterServicing=true;" />


text:
Q: Create a Lock Function for DataClass I have a simple dataclass to track a status of my switch like this
@dataclass
class status:
    switch: bool = False

This class is used by two threads so I would like to implement a logic to lock the switch variable change while other thread changing the switch value.
something like
@dataclass
class status:
    lock: bool = False
    switch: bool = False

    def setattr(self, val):
        if self.lock is not False:
            self.switch = val

I would like to know if there is a better way to set some logic like this. Something where I do not need to call the method above to check lock on change switch variable.

A: You should use the existing "Lock".  e.g. in the Threading library.  You "acquire" the lock when you want one thread to have it and use the locked resource.  When another thread tries to acquire the lock it will block until the first thread releases it.


text:
Q: Getting the ID when message is sent - Firebase & AngularFire I have a messaging "app" and I need to get the ID when a message is created.
Here is all of the code below:

            <input ng-model="message.message" ng-change="messages.$save(message)" />
            <input ng-model="message.by" ng-change="messages.$save(message)" />
            <button ng-click="messages.$remove(message)">Delete Message</button>

    <form ng-submit="addMessage()">
        <input ng-model="newMessageText" />
        <input ng-model="newMessageBy" />
        <button type="submit">Add Message</button>
    </form>

When a message is sent, it creates a ID and the message content under it. So, I need to get the ID of the message sent, and write the ID to Firebase.
Here's what the database looks like:
{
  "messages" : {
    "-KrsHPUi7pIWTQ1qgO4q" : { // I NEED TO GET THIS
      "message": "blah blah blah...",
      "by": "john"
    }
  },
  "ids" : {
    "first": "-KrsHPUi7pIWTQ1qgO4q" // AND PUT IT HERE
}

A: here how you can get the id
$scope.messages.$add({
                    message: $scope.newMessageText,
                    by: $scope.newMessageBy
                }).then(function(ref) {
                   var id = ref.key;
                  // do with the key what ever you want
})


text:
Q: Is there an effective way to map seasons such that order is preserved on a time series? I want to order the seasons i.e. 1999: winter, spring, summer, autumn, winter, 2000, winter, spring, etc
what I have at the moment is just long and not nice:
import calendar

df['month_num'] = pd.DatetimeIndex(df.index).month
df['year_num'] = pd.DatetimeIndex(df.index).year
df['year_month_num'] = df.month_num + (df.year_num +- 1999)*12

year_month_num_to_season_num =  {1:1,2:1,3:2,4:2,5:2,6:3,7:3,8:3,9:4,10:4,11:4,12:5,
                                 13:5,14:5,15:6,16:6,17:6,18:7,19:7,20:7,21:8,22:8,23:8,24:9,
                                25:9,26:9,27:10,28:10,29:10,30:11,31:11,32:11,33:12,34:12,35:12,36:13,
                                 37:13,38:13,39:14,40:14,41:14,42:15,43:15,44:15,45:16,46:16,47:16,48:17,
                                49:17,50:17,51:18,52:18,53:18,54:19,55:19,56:19,57:20,58:20,59:20,60:21,
                                61:21,62:21,63:22,64:22,65:22,66:23,67:23,68:23,69:24,70:24,71:24,72:25,
                                73:25,74:25,75:26,76:26,77:26,78:27,79:27,80:27,81:28,82:28,83:28,84:29,
                                 85:29,86:29,87:30,88:30,89:30,90:31,91:31,92:31,93:32,94:32,95:32,96:33,
                                 97:33,98:33,99:34,100:34,101:34,102:35,103:35,104:35,105:36,106:36,107:36,108:37,
                                109:37,110:37,111:38,112:38,113:38,114:39,115:39,116:39,117:40,118:40,119:40,120:41,
                                121:41,122:41,123:42,124:42,125:42,126:43,127:43,128:43,129:44,130:44,131:44,132:45,
                                 133:45,134:45,135:46,136:46,137:46,138:47,139:47,140:47,141:48,142:48,143:48,144:49,
                                 145:49,146:49,147:50,148:50,149:50,150:51,151:51,152:51,153:52,154:52,155:52,156:53,
                                 157:53,158:53,159:54,160:54,161:54,162:55,163:55,164:55,165:56,166:56,167:56,168:57,
                                169:57,170:57,171:58,172:58,173:58,174:59,175:59,176:59,177:60,178:60,179:60,180:61,
                                181:61,182:61,183:62,184:62,185:62,186:63,187:63,188:63,189:64,190:64,191:64,192:65,
                                193:65,194:65,195:66,196:66,197:66,198:67,199:67,200:67,201:68,202:68,203:68,204:69,
                                205:69,206:69,207:70,208:70,209:70,210:71,211:71,212:71,213:72,214:72,215:72,216:73,
                                217:73,218:73,219:74}

df['season_ordinal'] = df.year_month_num.map(year_month_num_to_season_num)

A: Your mapping dictionary can be given exactly by a simple dictionary comprehension:
year_month_num_to_season_num = {i:(i+3)//3 for i in range(1,220)}

This uses integer division. A certain amount of shifting was required in the value part so that the first two values are 1.


text: Q: Django merging or joining more then 30 models with same fields into one? so i need to build rest api with django rest framework and the problem that i have is that I've got more then 30 models from already existing postgresql db with command inspect db. All these tables have exactly the same fields. They are collecting data in different countries so I can't change anything regarding db but i need to build api. Also there is more then 1 000 000 instances in all tables and the data is updating almost every day. Is there a way that i can join these tables into one. What would be the best way to serialize this and send it with view? Any idea is welcome. Thanks


text:
Q: Change the Theme from MasterPage I have a MasterPage that has two image buttons , and two content pages, What i want is that  when an Image button is clicked ----> the theme changes.
I know that MasterPage do not have a "OnPreInit" function and the theme has to be changed inside the "OnPreInit" function...
so is there any workaround for this problem ???
Thanks in advance.
Baher

A: The following is a process used in the Book "Beginning ASP.Net 4 in C# and VB.Net by Imar Spaanjaars". Note that in the book he uses a DropDownList to change the Theme, but I believe the same can be done with an Image button:

*

*In the MasterPage add code to the Image Button click event to save the theme name into a cookie. Once the cookie is set you redirect back to the current page.

*You will need to create a custom BasePage that inherits from the Page class and have all your pages inherit from this BasePage. It is in this BasePage that you will override the Page_PreInit to load the selected theme based on the value of the cookie. The redirect is to run the code in the Page_PreInit to have the Theme change.

I know this might not be the best option, because you will need to change all your pages to inherit from your new BasePage instead of Page.

A: Well I found the Solution for that which is i captured the Image Button clicked and then changed the theme
really easy


text:
Q: Eliminating dead space from a plot consisting of two pie charts I have this plot which I want to save as PDF.
pdf(file="pie_charts.pdf", width=8, height=5, onefile=F)
layout(matrix(c(1,2,3,3), ncol=2, byrow=TRUE), heights=c(4, 1))
par(mar=c(0,0,0,0), xpd=TRUE)
pie(c(1,9),col=c("black","white"))
pie(c(1,3),col=c("black","white"))
plot.new()
legend(x="center", ncol=2,legend=c("Black","Whtie"),fill=c("black","white"), bty = "n",cex=1.3)
dev.off()

And this is what I am getting

It looks quite good but I want to eliminate as much empty space as possible between the individual pie charts as well as between them and the legend. Any suggestions?

A: With layout(), I think you may be a bit limited with changing margins to squeeze the pie charts together.
This isn't an elegant solution but it works.  I went in to the pie() function and modified the xlim arguments.  This was my only change.
In other words, pie has this inside its function:
xlim <- ylim <- c(-1, 1)

Change the xlim to shift the pie charts left or right.
I made mypieleft() and mypieright().
mypieleft<-function(blah blah){
[untouched code from pie]
    #  xlim <- ylim <- c(-1, 1)
    xlim <- c(-1.20, 0.80)
    ylim <- c(-1, 1)
[untouched code from pie]
}

and
mypieright<-function(blah blah){
[untouched code from pie]
    #  xlim <- ylim <- c(-1, 1)
    xlim <- c(-0.75, 1.25)
    ylim <- c(-1, 1)
[untouched code from pie]
}

Then change your code slightly:
layout(matrix(c(1,2,3,3), ncol=2, byrow=TRUE), heights=c(4, 1))
par(oma=c(0,0,0,0), xpd=TRUE)
mypieleft(c(1,9),col=c("black","white"))
mypieright(c(1,3),col=c("black","white"))
plot.new()
legend(x="center", ncol=2,legend=c("Black","Whtie"),fill=c("black","white"), bty = "n",cex=1.3)

I get this image.

A: Just increase the radius of the pies:
layout(matrix(c(1, 2, 3, 3), ncol=2, byrow=TRUE), heights=c(4, 1))
par(mar=c(0, 1, 0, 0)) # increase left margin to accommodate text
pie(c(1, 9), col=c("black","white"), radius=1)
par(mar=c(0, 0, 0, 1)) # increase right margin to accommodate text
pie(c(1, 3), col=c("black", "white"), radius=1)
plot.new()
legend(x="center", ncol=2, legend=c("Black", "White"),
       fill=c("black", "white"), bty="n", cex=1.3)

See the radius arg at ?pie.


text:
Q: How to make the DIV contents slide out and appear only when the user clicks on the DIV heading? If I have a DIV heading of Contact Details or Address Details, as in the following example:
http://jsfiddle.net/2CZFL/
how can I use jQuery to implement a feature whereby the contents of the div only slide out and appear to the user when the user clicks on the DIV heading.

A: See fiddle for how to make it open and close: http://jsfiddle.net/maniator/wU8s2/

A: here's a simple example

Click Me Newb!

Keep eating those stackoverflow weaties kiddies and you can be as cool as me!

A: Simple demo with using your fiddle, http://jsfiddle.net/andresilich/DR3x8/
[Make sure to add "display:none" to the content below the headers in order to hide them and only show when clicked.]


text:
Q: Styling is not applied on Kendo grid and Chart in Angular2 I have loaded all the dependencies that are required for kendo grid and chart. I have even checked the node_modules/@progress folder. The grid and chart are loaded but the styling is missing.

A: You need to install the KendoUI default theme, which is not a dependancy to other kendo packages.
@progress/kendo-theme-default

See documentation and tutorial here :
http://www.telerik.com/kendo-angular-ui/components/styling/
You can then include the all.css file in your  tag, or include it in your root component (usually app.component) with Encapsuation set to None, so it can be applied to all components beneath.
If you want to use the scss file, you need to configure your package manager to be able to build scss files.


text:
Q: What is the use of ThisType in Java? I am using Java and I am trying to investigate and learn from the source code of sqlbuilder from healthmarketscience. You can get the source code by adding this maven dependency.
The file BaseCreateQuery.class has the following code
public abstract class BaseCreateQuery<ThisType extends BaseCreateQuery<ThisType>> extends Query<ThisType> {
    protected SqlObject _object;
    protected SqlObjectList<SqlObject> _columns = SqlObjectList.create();

    protected BaseCreateQuery(SqlObject objectStr) {
        this._object = objectStr;
    }

    public ThisType setName(String name) {
        return this.setCustomName(name);
    }

    public ThisType setCustomName(Object name) {
        this._object = Converter.toCustomSqlObject(name);
        return (BaseCreateQuery)this.getThisType();
    }

    public ThisType addColumns(Column... columns) {
        return this.addCustomColumns((Object[])columns);
    }

    protected void collectSchemaObjects(ValidationContext vContext) {
        super.collectSchemaObjects(vContext);
        this._object.collectSchemaObjects(vContext);
        this._columns.collectSchemaObjects(vContext);
    }

    public void validate(ValidationContext vContext) throws ValidationException {
        super.validate(vContext);
        if (SelectQuery.hasAllColumns(this._columns)) {
            throw new ValidationException("Cannot use the '*' syntax in this query");
        }
    }

    public abstract ThisType addCustomColumns(Object... var1);

    public abstract DropQuery getDropQuery();
}

I want to know what is meant by ThisType (in line 1). Is it something to do with Generics in Java. I studied Generics in Java but I did not find a reference to ThisType. TypeScript has the ThisType construct. Is that similar to ThisType in Java?

A: Indeed its related to Generics. This is a type of the builder (this query is actually a builder) with a generified parameter called ThisType. It could be called T instead, so nothing special about it. However, ThisType is used to emphasize what the parameter actually is.
In general, parameterized build is quite an advanced concept, if you really want to delve into the way of using builders like this consider reading this article for example


text:
Q: Single search box produces "ERROR: column reference "name" is ambiguous" I am trying to use a single search field to filter any column following Railscasts 240. The key piece for defining the search function is in the Contact model.
  def self.search(search)
    if search
      joins(:school).where(['name ILIKE ? OR email ILIKE ? OR school.name ILIKE ?', "%#{search}%", "%#{search}%", "%#{search}%"])
    else
      all
    end
  end

This works without the join and school.name. Contact belongs to school and has a school_id column. The exact error is:
PG::AmbiguousColumn: ERROR:  column reference "name" is ambiguous

I'm guessing the ambiguous error is because I am trying to search both contact.name and school.name. Looking for a suggestion to allow searching both without adding another search field or needing the user to specify the search type.
Edit:
Good suggestions below to use contact.name to deal with the ambiguity, but that leads to another error:
PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "contact"
LINE 1: ...ON "schools"."id" = "contacts"."school_id" WHERE (contact.na...
                                                             ^
: SELECT  "contacts".* FROM "contacts" INNER JOIN "schools" ON "schools"."id" = "contacts"."school_id" WHERE (contact.name ILIKE '%joseph%' OR email ILIKE '%joseph%' OR school.name ILIKE '%joseph%')  ORDER BY name asc LIMIT 50 OFFSET 0

I thought this was due to the inner join moving the entire query into the schools table, but the error persists even if I remove the other two queries and ONLY search on school.name.

A: The ambiguous errors is caused by PG not knowing which name column the query reffers to - contacts.name or schools.name. You can fix it by changing your query to:
joins(:school).where(['contacts.name ILIKE ? OR email ILIKE ? OR schools.name ILIKE ?', "%#{search}%", "%#{search}%", "%#{search}%"])

A: if columns that same names is more then must add alias
try this, i add contacts.name
 def self.search(search)
    if search
      joins(:school).where(['contacts.name ILIKE ? OR email ILIKE ? school.name ILIKE ?', "%#{search}%", "%#{search}%", "%#{search}%"])
    else
      all
    end
  end


text:
Q: Prolong the sound of a word in writing How do I prolong the sound of a word in writing, while maintaining its natural sound?
I want to prolong the sound of these words:

Doh
  Rei
  Mi
  Fah
  Sol

If I write Doooooh, people might read it as doooo-oh.

A: Like they do in written choral music, use hyphens between the stretched out sounds (similar to what @seagull answered) except it would not be using phonetic spellings, as in their example.
So for Do Re Mi Fa... it might be written as:

"D-o-o-o, R-e-e-e, M-I-I-I, F-a-a-a, etc.

If it was words instead of sounds, the reader probably wouldn't be confused.
Another method, again borrowed from music, is to draw a line extending out from the word to be stretched, like in this example:

A: I recall an old tactic hymn writers used to use where a dash would represent a longer vowel sound.
For instance:
Do-h
Re-i
Mi-
Fa-h
So-l
etc.


text:
Q: Limit picture size in a Windows Store app I'll be working on a Windows store app (c#) that allow user to take pictures. Those pictures will be uploaded somewhere, but quality isn't really a matter and they shouldn't take too much space.
Is it possible to limit the size of those pictures inside the app ?
Thank you

A: There are quite a few ways you can do this.
Firstly, you can re-encode the images using different scales using BitmapEncoder[http://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmapencoder.aspx] and BitmapDecoder.
For either, you are going to create or set the BitmapTransform's ScaledWidth and ScaledHeight properties. You can lookup guides to scaling images pretty easily. The Encoder will allow you to choose a new encoding, such as PNG, which may drastically reduce the size of the image (especially if they select a BMP).
Secondly, you can crop the images. You can either do this yourself or allow the user to do it such as this one or this one.
Hope this helps and happy coding!


text:
Q: Trying to copy the text of selected treeview nodes to clipboard but only getting the last node in clipboard I am using excel/vba to create a tree structure. Nodes have checkbox in front of them. I am using a recursive function to traverse the nodes and copy the text of selected/checked nodes. I tried to put it in variable, excel rows, arrays but I am only getting last selected node's text.
Below is the recursive function.
I am passing the root node to it. How to copy selected items?
Public Sub TraverseTree(objNode As Node)

    Dim objSiblingNode As Node
    Set objSiblingNode = objNode

   Do
        If objSiblingNode.Checked Then
        Debug.Print objSiblingNode.Text
        End If
        If Not objSiblingNode.Child Is Nothing Then
            Call TraverseTree(objSiblingNode.Child)
        End If
        Set objSiblingNode = objSiblingNode.Next
   Loop While Not objSiblingNode Is Nothing

End Sub

Tree nodes defined in VBA code
'Parent Nodes

TreeView1.Nodes.Add Key:="P1", Text:="Phone is down/blank screen"
TreeView1.Nodes.Add Key:="P2", Text:="phone is showing Configuring IP"
TreeView1.Nodes.Add Key:="P3", Text:="Phone stuck at registering"

'Child for P1

TreeView1.Nodes.Add "P1", tvwChild, "ch1", "Is the phone getting power?"

'Child for ch1

TreeView1.Nodes.Add "ch1", tvwChild, "ch1.1", "Yes"
TreeView1.Nodes.Add "ch1", tvwChild, "ch1.2", "No"

'Child for ch1.1

TreeView1.Nodes.Add "ch1.1", tvwChild, "ch1.1.1", "Do you see any buttons lit up, what are they?"

A: So, try the next scenario, please:

*

*Declare a Private Variable on top of form module (in the declarations area):

    Private strWiew As String

*Your TraverseTree Sub will become:

Private Sub TraverseTree(objNode As Node)
   Do
        If objNode.Checked Then
            If strWiew = "" Then
               strWiew = objNode.Text
            Else
               strWiew = strWiew & vbCrLf & vbTab & objNode.Text
            End If
        End If
        If Not objNode.Child Is Nothing Then
            Call TraverseTree(objNode.Child)
        End If
        Set objNode = objNode.Next
   Loop While Not objNode Is Nothing
End Sub

*You need the function to put the resulted string in clipboard:

    Dim clipboard As New MSForms.DataObject

    clipboard.SetText strNode
    clipboard.PutInClipboard
End Sub

*Your Copy button Click event will become:

    Private Sub CommandButton1_Click()
     Dim objNode As Node

     Set objNode = TreeView1.Nodes("P1")
     strWiew = ""
     TraverseTree objNode
     CopyToClipboard strWiew
    End Sub

*Run your application. Check the tree node you want their text to be returned and press Copy button. Open Notepad, Wordpad, Word (any text editor) and try Ctrl + V...


text:
Q: Writing the output of a command to specific columns of a csv file, unix I wanted to write the output of command to specific columns (3rd and 5th) of the csv file.
#!/bin/bash
echo -e "Value,1\nCount,1" >> file.csv
echo "Header1,Header2,Path,Header4,Value,Header6" >> file.csv
sed 'y/ /,/' input.csv >> file.csv

input.csv in the above snippet will look something like this
1234567890 /training/folder
0325435287 /training/newfolder

Current output of file.csv
Value,1
Count,1
Header1,Header2,Path,Header4,Value,Header6
1234567890,/training/folder
0325435287,/training/newfolder

Expected Output of file.csv
Value,1
Count,1
Header1,Header2,Path,Header4,Value,Header6
,,/training/folder,,1234567890,
,,/training/newfolder,,0325435287,

A: All the operations can be done in a single awk:
awk -v OFS=, -v pre="Value,1\nCount,1" -v hdr="Header1,Header2,Path,Header4,Value,Header6" '
   BEGIN {print pre; print hdr}
   {print "", "", $1, "", $2, ""}
' input.csv

Value,1
Count,1
Header1,Header2,Path,Header4,Value,Header6
,,i1234567890,,/training/folder,
,,0325435287,,/training/newfolder,

A: With sed you could try following code. Which is using sed's capability of back reference.
sed -E 's/(^[^ ]*) +(.*$)/,,\2,,\1,/' Input_file

Explanation: Using -E option of sed to enable ERE(extended regular expressions) first. Then in main program using s option to perform substitution operation. In 1st part of substitution creating 2 back references(capability to catch values by using regex and keep them in temp buffer memory to be used later on while substituting it with in 2nd part of substitution). In 2nd part of substitution substituting whole line with 2 commas followed by 2nd capturing group\2 followed by 2 commas followed by 1st capturing group \1 following by ,.

A: You can use awk instead of sed
cat input.csv | awk '{print ",," $1 "," $2 ","}' >> file.csv

awk can process a stdin input by line to line. It implements a print function and each word is processed as a argument (in your case, $1 and $2). In the above example, I added ,, and , as an inline argument.

A: You can trivially add empty columns as part of your sed script.
sed 'y/ /,/;s/,/,,/;s/^/,,/;s/$/,/' input.csv >> file.csv

This replaces the first comma with two, then adds two up front and one at the end.
Your expected output does not look like valid CSV, though. This is also brittle in that it will fail for any file names which contain a space or a comma.


text:
Q: vector::clear() causing a seg fault I have a std::vector that is causing some very strange seg faults
//A.h
class A{
private:
  std::vector<float> data;
public:
  void set(const std::vector<float>& data);
};
//A.cpp
void A::set(const vector<float>& data){
  this->data.clear(); // crashes on this line
  for(float f : data) this->data.push_back(f);
}

Under what possible circumstances could vector::clear() cause a seg fault? I initially had
void A::set(const vector<float>& data){
  this->data = data;
}

and had the same problem. I switched to the above to debug.
This is on gcc 4.7.2, x86_64

A: IF it crashes precisely at the call to 'data.clear' (I mean, at exactly this line, not somewhere inside the clear), then be sure to check your this pointer at the faulting line.
If somehow your $this is null or trash-value due to accumulated effects of previous bugs, then this line might behave similarily.
On the (almost) other hand, if it actually crashes somewhere inside the clear and you just have cut the stacktrace to make the problem description more succint, then still it is possible to be the same cause.
You may check the 'this' pointer for NULL easily in the debugger. Also, detecting trashvalues is not hard: add some testfields to the A class, fill them in constructor with some predictable BUT NOT CONSTANT values, and when the app crashes, check if the this->mytestvalue is ok. If the $this is trashed, then the pointed test values will very often be almost random.

A: Likely this is due to stack/memory corruption occurring somewhere else. You should run your program with a memory checker, such as Valgrind using the memcheck tool to see what's going on.


text:
Q: Syntax in FROM Clause private void DeleteQuestion_Click(object sender, EventArgs e)
{
    try
    {
        using (OleDbConnection conn = new OleDbConnection(access7ConnectionString))
        {
            conn.Open();

            using (OleDbCommand cmd = new OleDbCommand("DELETE FROM Questions" + "WHERE ID=@ID", conn))
            {
                cmd.Parameters.AddWithValue("@ID", currentRecord);
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (OleDbException ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

I get this error:
Syntax in FROM Clause
Where am I going wrong? Still learning C#
access7ConnectionString is a string path to the database, I've cut it out to shorten down the post, but the connection to the database is established and it all works.

A: There is no space between Table Name and WHERE, Place a space like:
"DELETE FROM Questions" + " WHERE
                        ///^^^

Not really sure why you have to use string concatenation. It all can be par to of a single string. like:
using (OleDbCommand cmd = new OleDbCommand("DELETE FROM Questions WHERE ID=@ID", conn))

A: You are missing a space, change
"DELETE FROM Questions" + "WHERE ID=@ID"

to
"DELETE FROM Questions WHERE ID=@ID"


text:
Q: If a function $f$ is is differentiable and oscillatory, then is its derivative $f'$ also oscillatory? I know this is true but I'm trying to figure out a proof for it.
To clarify what oscillatory means:
Oscillatory means that a function $f$ has an unbounded set of roots.


text:
Q: Python file not debugging in vscode docker container Opened VSCode. Started container by docker extension. Attached visual studio code with container. Start debugging but nothing shows on terminal. Added break points, debugging not started. Debugging palette appears for a while.Start debugging but nothing shows on terminal. Added break points, debugging not started. Debugging palette appears for a while.
Tried reinstall, restart laptop, remote python extension in prerelease version.
**VScode**
Version: 1.69.1 (user setup)
Commit: b06ae3b2d2dbfe28bca3134cc6be65935cdfea6a
Date: 2022-07-12T08:21:24.514Z
Electron: 18.3.5
Chromium: 100.0.4896.160
Node.js: 16.13.2 V8: 10.0.139.17-electron.0
OS: Windows_NT x64 10.0.19044

Python Extension in docker container: v2022.10.1

A: Problem is caused by python extension(microsoft) in container. Downgraded python extension from v2022.10.1 to v2022.8.0 in container extensions. Problem solved.

A: Had the same problem
I solved it by opening my folder in VS Code.

*

*File -> Open Folder

*A window will pop up, navigate to your project folder

*After that, start debugging, it should be wokring now.
If debugging is working, it will pop up a window like this.


text:
Q: iOS Landscape and Portrait orientation with sibling subviews How can I achieve the desired output as per the below screen shots.
Just to let you know I am not comfortable to size classes and stack views but has little knowledge on Autolayout.

Please let me know can I achieve that only with autolayout ?
I have an idea to add horizontally center constraints and removing vertically center constraints  in landscape mode, and vice versa in portrait mode when orientation changes with delegate method. -viewWillTransitionToSize:withTransitionCoordinator:
I will post further information if required.

A: Center your stackview.  When the orientation changes change the UIStackView.axis to either .verticle or .horizontal


text:
Q: OData support two routes which returns a single entity and a collection I'd like to define two routes so I can access my entities. The code example below however returns an exception whenever I try to access my swagger.json file.

Bad Request - Error in query syntax.

There are a total of 2 routes I need;

*

*/EventLog(MeetingId={keyMeetingId},Id={keyId}) -> Returns a single entity

*Search(MeetingId={keyMeetingId} -> Returns multiple records

Builder;
var eventLog = builder.EntitySet<EventLog<object>>(nameof(EventLog<object>)).EntityType;
eventLog.HasKey(x => new { x.MeetingId, x.Id });

var eventLogSearch = eventLog.Collection
   .Action("Search")
   .ReturnsCollectionFromEntitySet<EventLog<object>>(nameof(EventLog<object>));

eventLogSearch.Parameter<string>("MeetingId")
.Required();

Startup:
 app.UseMvc(
                builder =>
                {
                    builder.ServiceProvider.GetRequiredService<ODataOptions>()
                    .UrlKeyDelimiter = Parentheses;
                    builder.Count();
                    builder.Expand()
                        .Select()
                        .OrderBy()
                        .Filter();
                    builder.MapVersionedODataRoutes("odata", "api", modelBuilder.GetEdmModels());

                    builder.EnableDependencyInjection();
                });

I've tried several other solutions, but they result in either a 404 or the error like above. Any suggestions on how to support both routes?
I'm using asp.net core 2.2