text:
Q: How to add a second condition in Linq Query I have this linq query in my controller and it is working fine,
var Engineers = dbcontext.Employees.Where(i => i.Department == "Engineers");

but I would like to add a second condition to the query to filter out the results,
var Engineers = dbcontext.Employees.Where(i => i.Department == "Engineers" && i.UserStatus = 1);

Thanks for your help.

A: You made a typo, just need to use comparison operator (==) instead of assignation (=)
So it would be like that:
var Engineers = dbcontext.Employees.Where(i => i.Department == "Engineers" && i.UserStatus == 1);


text:
Q: How to check background image I have a few buttons in my application that can have different background images.
Now, at the OnClick function, I need to check if the Background Image is the image name "williboese" in drawable.
I tried like this:
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            //b.setBackgroundColor(R.color.redwue);
            count++;
            if(arg0.getResources().equals(R.drawable.williboese)){
                Toast.makeText(MainActivity.this, "heeeee", Toast.LENGTH_SHORT).show();
            }
        }
    });

I know at this moment that b has this background image but the Toast isn´t shown. What do I make wrong?

A: Probably the easiest way to do this is to use tags like this:
btn.setTag(R.drawable.williboese);

then compare with
view.getTag().equals(R.drawable.williboese);

because R.drawable is a primitive, this code won't work exactly but you get the idea...
What's wrong with your code is that you are comparing the resource ID of the drawable to the "resources" object of the view. You could try:
arg0.getResources().getDrawable(R.drawable.williboese).equals(arg0.getBackground())

A: Here you are trying to compare Resources with int which will be never true...
and this trick may help you..
When setting the background resource id, set the that ID as tag for the View.
b.setBackgroundResource(R.drawable.williboese);
b.setTag(R.drawable.williboese);

and in OnClickListener you can check which is the current background drawable...
b.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        int resId = (Integer) view.getTag();
        if(resId == R.drawable.williboese) {
            // background is R.drawable.williboese image
        }
    }
});

A: getResources doesnt return what you think, as you can see in the source of the function
private final Resources mResources;

public View(Context context) {
    mContext = context;
    mResources = context != null ? context.getResources() : null;
    ...
}

public Resources getResources() {
    return mResources;
}

it just returns the same as context.getResources(), an abject for accesing the resources in the app.
You cannot retrieve the id of the background of a view. You will have to save it elsewhere. For that you can use the setTag function of the view, where you can save anything that you can retrieve later. http://developer.android.com/reference/android/view/View.html#setTag(java.lang.Object)
b.setBackgroundResource(R.drawable.williboese);
b.setTag(R.drawable.williboese);

and then in the listener you compare
        Integer i = (Integer) view.getTag();

        if(i!= null && i == R.drawable.williboese) {
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How create loop in twig template? I want made loop like of this on twig template:
for($i=1;$i<100;$i++) {
 echo $i;
}

I solved this problem as:
{% if k > 0 %}
 {% for i in 0..k - 1 %}

 {% endfor %}
{% endif %}

if k = 0 -> no loop
if k = 1 -> 1 loop
if k = 100 -> 100 lopp

May be is other solve?

A: You can use range to reproduce loop output similar to the first php example
{% for i in range(1, 100-1) %}
    {{ i }}
{% endfor %}

A: You can add the if inside the loop
{% for i in 0..k if k > 0 %}
 {{ i }}
{% endfor %}

demo

edit: This doesn't work anymore in twig 3.X. You have to place the if inside the codeblock


text:
Q: How to close correctly a WINAPI Thread pool cancelling pending tasks I have a question about closing a WINAPI ThreadPool.
Suppose i have initialized a thread pool with a cleanup group and pushed some tasks to the thread pool with the SubmitThreadpoolWork.
I'm calling the CloseThreadPoolTask in the task's callback function.
Currently there are tasks that executing and others that pending in the thread-pool's queue.
Now, for closing the thread pool I want to use CloseThreadpoolCleanupGroupMembers function without pending for the queued tasks to finish, but I still want to get a callback to the pending task to release its user allocated resources (some that come with the task's parameters).
I saw in this thread:
Cancelling scheduled work/io/timer items in WIN32 thread pool
that the callback that i have passed to the cleanup group (PTP_CLEANUP_GROUP_CANCEL_CALLBACK)  will also call to work objects that are currently executing (because they still tied to cleanup group during the execution) - obviously i don't want it to happen... Is there a way that the cleanup cancel callback will not get invoked on currently executing tasks?
Thanks!

A: if callback for CreateThreadpoolWork begin executed, cleanup callback for it will be not called. or if cancel callback for item will be called - PTP_WORK_CALLBACK will be never called for this item (before and after). so here really no any problem. or will be called your PTP_WORK_CALLBACK or will be called cancell callback for this item. this is mutually exclusive. so reply in topic Cancelling scheduled work/io/timer items in WIN32 thread pool containing very serious errors. i can suggest you for test insert MessageBox call in begin of PTP_WORK_CALLBACK and also another MessageBox before CloseThreadpoolCleanupGroupMembers. and you can make sure if PTP_WORK_CALLBACK begin executed - cancell callback for this item already not called.


text:
Q: Kafka GroupTable tests generating extra messages when using ProcessorTopologyTestDriver I've written a stream that takes in messages and sends out a table of the keys that have appeared.  If something appears, it will show a count of 1.  This is a simplified version of my production code in order to demonstrate the bug.  In a live run, a message is sent out for each message received.
However, when I run it in a unit test using ProcessorTopologyTestDriver, I get a different behavior.  If a key that has already been seen before is received, I get an extra message.
If I send messages with keys "key1", then "key2", then "key1", I get the following output.
key1 - 1
key2 - 1
key1 - 0
key1 - 1

For some reason, it decrements the value before adding it back in.  This only happens when using ProcessorTopologyTestDriver.  Is this expected?  Is there a work around?  Or is this a bug?
Here's my topology:
final StreamsBuilder builder = new StreamsBuilder();
    KGroupedTable<String, String> groupedTable
            = builder.table(applicationConfig.sourceTopic(), Consumed.with(Serdes.String(), Serdes.String()))
            .groupBy((key, value) -> KeyValue.pair(key, value), Serialized.with(Serdes.String(), Serdes.String()));

    KTable<String, Long> countTable = groupedTable.count();

    KStream<String, Long> countTableAsStream = countTable.toStream();
    countTableAsStream.to(applicationConfig.outputTopic(), Produced.with(Serdes.String(), Serdes.Long()));

Here's my unit test code:
TopologyWithGroupedTable top = new TopologyWithGroupedTable(appConfig, map);
    Topology topology = top.get();
    ProcessorTopologyTestDriver driver = new ProcessorTopologyTestDriver(config, topology);
    driver.process(inputTopic, "key1", "theval", Serdes.String().serializer(), Serdes.String().serializer());
    driver.process(inputTopic, "key2", "theval", Serdes.String().serializer(), Serdes.String().serializer());
    driver.process(inputTopic, "key1", "theval", Serdes.String().serializer(), Serdes.String().serializer());

    ProducerRecord<String, Long> outputRecord = driver.readOutput(outputTopic, keyDeserializer, valueDeserializer);
    assertEquals("key1", outputRecord.key());
    assertEquals(Long.valueOf(1L), outputRecord.value());
    outputRecord = driver.readOutput(outputTopic, keyDeserializer, valueDeserializer);
    assertEquals("key2", outputRecord.key());
    assertEquals(Long.valueOf(1L), outputRecord.value());
    outputRecord = driver.readOutput(outputTopic, keyDeserializer, valueDeserializer);
    assertEquals("key1", outputRecord.key());
    assertEquals(Long.valueOf(1L), outputRecord.value()); //this fails, I get 0.  If I pull another message, it shows key1 with a count of 1

Here's a repo of the full code:
https://bitbucket.org/nsinha/testtopologywithgroupedtable/src/master/
Stream topology: https://bitbucket.org/nsinha/testtopologywithgroupedtable/src/master/src/main/java/com/nick/kstreams/TopologyWithGroupedTable.java
Test code: https://bitbucket.org/nsinha/testtopologywithgroupedtable/src/master/src/test/java/com/nick/kstreams/TopologyWithGroupedTableTests.java

A: It's not a bug, but behavior by design (c.f. explanation below).
The difference in behavior is due to KTable state store caching (cf. https://docs.confluent.io/current/streams/developer-guide/memory-mgmt.html). When you run the unit test, the cache is flushed after each record, while in your production run, this is not the case. If you disable caching in your production run, I assume that it behaves the same as in your unit test.

Side remark: ProcessorTopologyTestDriver is an internal class and not part of public API. Thus, there is no compatibility guarantee. You should use the official unit-test packages instead: https://docs.confluent.io/current/streams/developer-guide/test-streams.html

Why do you see two records:
In your code, you are using a KTable#groupBy() and in your specific use case, you don't change the key. However, in general, the key might be changed (depending on the value of the input KTable. Thus, if the input KTable is changed, the downstream aggregation needs to remove/subtract the old key-value pair from the aggregation result, and add the new key-value pair to the aggregation result—in general, the key of the old and new pair are different and thus, it's required to generate two records because the subtraction and addition could happen on different instances as different keys might be hashed differently. Does this make sense?
Thus, for each update of the input KTable, two updates two the result KTable on usually two different key-value pairs need to be computed. For you specific case, in which the key does not change, Kafka Stream does the same thing (there is no check/optimization for this case to "merge" both operations into one if the key is actually the same).


text:
Q: Inverse Laplace Transform isn't A Contour Integral I've learned about and used the Laplace transform in several signal processing classes and the inverse transform has always been defined as an integral like this:
$$ \mathcal{L}^{-1}\{F(s)\} = \frac{1}{2\pi j} \int_{\sigma_0 - j\infty}^{\sigma_0+j\infty}
F(s)e^{st}ds \quad \quad \sigma_0 \in \text{ROC}$$
I'm now taking a supplementary class on functions of a complex variable, so I've been learning more about integration in the complex plane. I'm a bit confused as to how the above integral should be interpreted. Is it a contour integral along the line \$s = \sigma_0\$ parallel to the imaginary axis? Does using an integral with endpoints rather than along a defined contour imply that \$F(s)\$ has an antiderivative so the contour doesn't matter?


text:
Q: Haskell tuple of duple type error i have this data type in haskell
type Coordinate = (Int,Int)
type Skyline = [Coordinate]

And im trying to do:
combina :: (Skyline, Skyline) -> Skyline
combina ([], x) = x
combina (x, []) = x
combina ((ii, ia):ri, (di, da):rd) = subcombina(((ii, ia):ri,0), (((di, da):rd),0), 0)
    where subcombina(((ii, ai):ri,uai), (((id, ad):rd),uad), uaa)
            | ai < ad && max(uai uad) /= uaa                      = (ii, max ai uad) : subcombina((ri,ai), ((id, ad):rd, uad), max(ai uad))
            | ai < ad && max(uai uad) == uaa                      =                    subcombina((ri,ai), ((id, ad):rd, uad), uaa)
            | ((ai > ad) || (ai == ad)) && max(uai uad) /= uaa    = (id, max uai ad) : subcombina(((ii, ai):ri,uai),(rd, ad), max (uai ad))
            | ((ai > ad) || (ai == ad)) && max (uai uad) /= uaa   =                    subcombina(((ii, ai):ri,uai),(rd, ad), uaa)

So, im trying to call to subcombina with
(((leftElementOfFirstLeftListTuple,rigthElementOfFirstLeftListTuple):restOfList,anyInteger),((leftElementOfFirstRigthListTuple,rigthElementOfFirsttRigthLListTuple):restOfList,anyInteger),
anyInteger)

And im getting this errors:
:l Skyline
[1 of 1] Compiling Skyline          ( Skyline.hs, interpreted )

Skyline.hs:26:38:
    Couldn't match type 't0 -> a0' with 'Int'
    Expected type: Skyline
      Actual type: [(Int, t0 -> a0)]
    In the expression:
      subcombina (((ii, ia) : ri, 0), (((di, da) : rd), 0), 0)
    In an equation for 'combina':
        combina ((ii, ia) : ri, (di, da) : rd)
          = subcombina (((ii, ia) : ri, 0), (((di, da) : rd), 0), 0)
          where
              subcombina (((ii, ai) : ri, uai), (((id, ad) : rd), uad), uaa)
                | ai < ad && max (uai uad) /= uaa
                = (ii, max ai uad)
                  : subcombina ((ri, ai), ((id, ad) : rd, uad), max (ai uad))
                | ai < ad && max (uai uad) == uaa
                = subcombina ((ri, ai), ((id, ad) : rd, uad), uaa)
                | ((ai > ad) || (ai == ad)) && max (uai uad) /= uaa
                = (id, max uai ad)
                  : subcombina (((ii, ai) : ri, uai), (rd, ad), max (uai ad))
                | ((ai > ad) || (ai == ad)) && max (uai uad) /= uaa
                = subcombina (((ii, ai) : ri, uai), (rd, ad), uaa)

Skyline.hs:26:55:
    Couldn't match expected type 't0 -> a0' with actual type 'Int'
    In the expression: ia
    In the first argument of '(:)', namely '(ii, ia)'

Skyline.hs:26:59:
    Couldn't match type 'Int' with 't0 -> a0'
    Expected type: [(Int, t0 -> a0)]
      Actual type: [Coordinate]
    In the second argument of '(:)', namely 'ri'
    In the expression: (ii, ia) : ri

Skyline.hs:26:73:
    Couldn't match expected type 't0 -> a0' with actual type 'Int'
    In the expression: da
    In the first argument of '(:)', namely '(di, da)'

Skyline.hs:26:77:
    Couldn't match type 'Int' with 't0 -> a0'
    Expected type: [(Int, t0 -> a0)]
      Actual type: [Coordinate]
    In the second argument of '(:)', namely 'rd'
    In the expression: ((di, da) : rd)

Skyline.hs:28:103:
    Occurs check: cannot construct the infinite type: t1 ~ t1 -> a
    Expected type: (t1 -> a) -> a
      Actual type: t1 -> a
    Relevant bindings include
      uaa :: a -> a (bound at Skyline.hs:27:62)
      uad :: t1 -> a (bound at Skyline.hs:27:56)
      rd :: [(t, t1 -> a)] (bound at Skyline.hs:27:52)
      ad :: t1 -> a (bound at Skyline.hs:27:48)
      uai :: (t1 -> a) -> a (bound at Skyline.hs:27:35)
      ri :: [(t, t1 -> a)] (bound at Skyline.hs:27:32)
      (Some bindings suppressed; use -fmax-relevant-binds=N or -fno-max-relevant-binds)
    In the expression: ai
    In the expression: (ri, ai)
Failed, modules loaded: none.

I think i'm mixing types but i cannot found where.

A: You are attempting to call max using (among other things)
max(ai uad)

This says "Apply the function ai to the value uad and apply max to the result." You probably meant to use
max ai uad

A: You have something like
max (ai uad)

in your code. This applies ai to uad
But I guess what you wanted was simply:
max ai uad


text:
Q: Play Framework: how to submit a form from a modal window using a POST route I have a Play Framework app that I would like to have the function of clicking a button from the form that will open a modal window.  Once the modal window opens, the user selects a value and clicks a button which would close the modal and call the POST route (submit the form) to save the form.
For example, if I use the following route:
GET /openrecord controllers.MyController.openRecord(key: String)

To open the form, then I would like to call this one below from the modal when I close that modal:
POST /openrecord controllers.MyController.saveRecord(key: String)

I have tried using JavaScript to change the URL, but it just uses the GET route, not the POST route:
HTML:

Approve

JS:
function wkflwApproveDeny(action, recordKey) {
    // Set the action field...
    var e = document.getElementById("workflowAction");
    e.value = action;
    // Now, process the record...
    window.location.href = "/openRecord/" + recordKey;
}

How would I accomplish this?  Is there a standard to use to get this done?

A: You need create a form for submit post.
function send_post(recordKey) {
    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", "http://url/openRecord/" + recordKey);
    document.body.appendChild(form);
    form.submit();
}

But you should rather use a JavaScript framework such as jQuery...


text:
Q: designing an app with multiple pages with different app bar and a single drawer I am trying to build an app in Flutter in which I have multiple pages, each with their specific actions in the app bar. I would like to add a Drawer to the app which contains a list of page names that take them to the respective pages. I learnt that both AppBar and Drawer widgets have to be part of a Scaffold widget. Currently, all my pages are basically StatefulWidgets with the build method returning a complete Scaffold widget. If I want to include a Drawer, I think I will have to add the drawer object in each of my page. Is there a better way/pattern to do this?

A: Write the code for the drawer once and enclose it in a function. Then just call the function each time for that drawer.
eg)
drawer: myDrawer()

A: In one of my Apps, I have something similar. My Drawer is in the app class which is called in the main. This app class calls the home classes. My app class is also Stateful.
Each home class has his own Appbar and Search function.
The Drawer is called only in the app class.
Tell me if this explanation is okay for you or if you need a sample code.


text:
Q: Split hash request into separate strings rails How would I go about splitting this hash request into two different strings?
I want to split it at #<ActionDispatch, which marks the beginning of the next image selected in the request.  How do I accomplish this in ruby?
Request
{"image"=>{"picture"=>[#<ActionDispatch::Http::UploadedFile:0x10c986d88 @tempfile=#<File:/var/folders/bx/6z1z5yks56j40v15n43tjh1c0000gn/T/RackMultipart20130404-53101-3c2whv-0>,
 @headers="Content-Disposition: form-data; name=\"image[picture][]\"; filename=\"background-pic.jpg\"\r\nContent-Type: image/jpeg\r\n",
 @content_type="image/jpeg",
 @original_filename="background-pic.jpg">,
 #<ActionDispatch::Http::UploadedFile:0x10c986d60 @tempfile=#<File:/var/folders/bx/6z1z5yks56j40v15n43tjh1c0000gn/T/RackMultipart20130404-53101-bvdysw-0>,
 @headers="Content-Disposition: form-data; name=\"image[picture][]\"; filename=\"bible-banner.png\"\r\nContent-Type: image/png\r\n",
 @content_type="image/png",
 @original_filename="bible-banner.png">],
 "album_id"=>"10"},
 "authenticity_token"=>"dr8GMCZOQo4dQKgkM4On2uMs8iORQ68vokjW0e4VvLY=",
 "commit"=>"Submit",
 "utf8"=>"✓",
 "album_id"=>"10"}

Controller
class Admin::ImagesController < ApplicationController
    respond_to :html, :json
    def index
        @album = Album.find(params[:album_id])
        @images = @album.images.all
    end
    def new
        @album = Album.find(params[:album_id])
        @image = @album.images.new
        #@image.picture.size.times {@image.build}
    end
    def create
        @album = Album.find(params[:album_id])
        @image = @album.images.new(params[:image])
        if @image.save
            flash[:notice] = "Successfully added image!"
            redirect_to [:admin, @album, :images]
        else
            render 'new'
        end
    end
    def show
        @album = Album.find(params[:album_id])
        @image = @album.images.find(params[:id])
    end
    def edit
        @album = Album.find(params[:album_id])
        @image = @album.images.find(params[:id])
    end
    def update
        @album = Album.find(params[:album_id])
        @image = @album.images.find(params[:id])
        if @image.update_attributes(params[:image])
            flash[:notice] = "Successfully updated Image"
            redirect_to [:admin, @album, :images]
        else
            render "edit"
        end
    end
    def destroy
        @album = Album.find(params[:album_id])
        @image = @album.images.find(params[:id])
        @image.destroy
        @albumid = @album.id
        @id = @image.id
        FileUtils.remove_dir("#{Rails.root}/public/uploads/image/picture/#{@albumid}/#{@id}", :force => true)
        redirect_to admin_album_images_path(@album)
    end
end

Model
class Image < ActiveRecord::Base
  attr_accessible :title, :description, :picture, :image_id, :album_id, :albumcover, :image
  belongs_to :album
  accepts_nested_attributes_for :album
  mount_uploader :picture, PictureUploader
end

Form View
<%= form_for([:admin, :album, @image], :html => {:multipart => true}) do |f| %>
  <%= f.hidden_field :album_id, :value => @album.id %>
  <%= f.file_field :picture, :multiple => true %>
  <%= f.submit "Submit" %>
<%end%>

Uploader Carrierwave
class PictureUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

  # Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
  # include Sprockets::Helpers::RailsHelper
  # include Sprockets::Helpers::IsolatedHelper

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.album_id}/#{model.id}"
  end
end

A: As a few commenters said above, what you have is a hash (key/value pair) with the key picture where the value is already an array, which by its nature is split up into discrete objects.
In order to access the array you need to ask for the picture key, then you can access each UploadedFile with Array methods.
So starting with your initial hash:
hash_with_stuff = { "picture" => [#<UploadedFile1>,#<UploadedFile2>]}
  #=> { "picture" => [#<UploadedFile1>,#<UploadedFile2>]}

In order to get the array:
array_of_pictures = hash_with_stuff["picture"]
  #=> [#<UploadedFile1>,#<UploadedFile2>]

Now that you have the array, you can operate on it as you would any array:
# to get single elements out
array_of_pictures[0] # where the number is the index of the object in the array (starting with 0)
  #=> #<UploadedFile1>   #this is an UploadedFile object and will respond to its own methods

# to operate on each element with some method
array_of_pictures.each do |picture|
  picture.create_thumbnail
end

Does this make sense or were there other questions about working with this?

A: Lets take a look at this hash h={"strings"=>["stirng_object_1","string_object_2"]} which is almost similar to the hash that you posted except that the objects in the array are strings instead of ActionDispatch::Http::UploadedFile Objects.
So from my example hash that I cited if I have to get first string object I would do

h["string"][0]

Similarly if you would like to access the first ActionDispatch::Http::UploadedFile Objects you  can do ( assuming that your hash name is h )

h["picture"][0]

A: I figured out how to split this hash request into its separate strings.
Image Controller
def new
    @album = Album.find(params[:album_id])
    @image = @album.images.new
    end
    def create
        params[:image][:picture].each do |image|
            @album = Album.find(params[:album_id])
            @params = {}
            @params['picture'] = image
            @image = @album.images.create(@params)
       end
        if @image.save
            if params[:image][:picture].size > 1
                flash[:notice] = "Successfully added images!"
            else
                flash[:notice] = "Successfully added image!"
            end
            redirect_to [:admin, @album, :images]
        else
            render "new"
            flash[:notice] = "Did not successfully add image :("
        end
    end


text:
Q: How to debug - Python CTypes causing *glibc detected* I've compiled a C++ program into a dynamic library, which I'm now calling in python via ctypes. However, I get the following error:
*** glibc detected *** ../../bin/python: free(): invalid pointer: 0x00007fbdf8ae3500 ***

How do I figure out if this is an error in the C++ code, or in how I'm using ctypes?
The C++ library runs succesfully when it is linked with a C program, or if I compile it as a standalone program. When combined with ctypes it always crashes at this C++ line:
// ... A bunch of code
if(tempBuffer) {
    delete[] tempBuffer;
    // More code below that never runs...

Python code that fails:
def test(fileName):
    feedbackLib = cdll.LoadLibrary("./libpitch.so")

    # Set return type to a character pointer
    feedbackLib.getPitchString.restype = c_char_p
    feedbackLib.getPitchString.argtypes = [c_char_p]

    # Crashes Here!
    feedbackStr = feedbackLib.getPitchString(fileName)
    return feedbackStr

For some reason, I can get the python program to work successfully if I change things around like so:
def test(fileName):
    # I've only changed this line
    feedbackLib = CDLL("./libpitch.so")

    # Set return type to a character pointer
    feedbackLib.getPitchString.restype = c_char_p
    feedbackLib.getPitchString.argtypes = [c_char_p]

    # No longer crashes!
    feedbackStr = feedbackLib.getPitchString(fileName)
    return feedbackStr

However, if I start adding things to the above function (which I need to do) it'll give me other glibc errors.

Here's information on how I compiled the C++ in case it's relevant.
Header of function I'm calling, using extern "C" seems to be how to get C++ code working with CTypes:
extern "C" char* getPitchString(char* filename);

g++ commands:
$(CXX) $(LDFLAGS) -fPIC -c $(SRCS) $(LIBS)
$(CXX) -shared -Wl,-soname,libpitch.so -o libpitch.so $(OBJS) $(LIBS)

A: Turns out there was an error in the C++ portion of the code. I managed to get that part to segfault independently of Python/CTypes, and after debugging it seems to work.


text:
Q: look down at vs. look down on Are look down on and look down at synonymous? They are when referring to dictionaries, but I'd like to know the subtle difference between them.

The ancient Greeks used to describe two very different ways of
thinking — logos and mythos. Logos roughly referred to the world
of the logical, the empirical, the scientific. Mythos referred to
the world of dreams, storytelling and symbols. Like many rationalists
today, some philosophers of Greece prized logos and looked down
at mythos. Logic and reason, they concluded, make us modern;
storytelling and mythmaking are primitive. But lots of scholars then
and now — including many anthropologists, sociologists and
philosophers today — see a more complicated picture, where mythos
and logos are intertwined and interdependent. Science itself,
according to this view, relies on stories. The frames and metaphors we
use to understand the world shape the scientific discoveries we make;
they even shape what we see. When our frames and metaphors change, the
world itself is transformed. The Copernican Revolution involved more
than just scientific calculation; it involved a new story about the
place of Earth in the universe.

Useful Delusions: The Power and Paradox of the Self-Deceiving Brain

A: As with so many questions like these, the answer is "it depends." If you are standing on a hill, you can look down on or look down at a village in the valley. This ngram viewer shows that both look down at the scene and look down on the scene are used, although look down on is more common.
But in a figurative rather than a literal sense, if you look down on someone, you are thinking less of that person than of yourself. To use look down at someone to mean this is very rare at best; if you look down at someone, you're generally doing it in the literal sense of, say, looking down the stairs at someone standing in the hall.
The example you give is the only time I've ever seen at used in this way. An ngram viewer of look down at/on the idea has no examples using at, and quite a few examples using on. This gives me the idea that as an editor, I would correct the passage from at to on.
Now, there's an idiomatic expression look down one's nose at something, which has a similar meaning to look down on. Maybe that's where this comes from.
Doing some more research, I see your excerpt comes from a book authored by one Shankar Vedantam. Perhaps this is a peculiarity of Indian English speakers, but it is not otherwise standard.

A: To 'look down at' can mean, literally, to observe or see from a higher place, e.g. from the top floor of my house, I can look down at the tops of cars in the street below. It doesn't really have a figurative meaning.
To 'look down on' can mean, literally, the same thing, but it also has a figurative meaning: 'despise' or 'regard with a feeling of superiority'.
It is clear from the context you gave that the authors intended the second, figurative meaning (some philosophers of Greece prized logos and regarded mythos with a feeling of superiority).
There are certain signs in the text that it was possibly poorly edited prior to publication, and maybe prepared by non-native or unskilled English speakers. I find 'philosophers of Greece' awkward when 'Greek philosophers' is so obviously more appropriate.


text:
Q: Scrapy - Missing data after request form I'm using this website to get latitude and longitude of different cities: https://www.latlong.net/.
Here is my code:
import scrapy
import json

with open('C:/Users/coppe/tutorial/cities.json') as json_file:
    cities = json.load(json_file)

class communes_spider(scrapy.Spider):
    name = "geo"
    start_urls = ['https://www.latlong.net/']

    def parse(self, response):
        for city in cities:
            yield scrapy.FormRequest.from_response(response, formid='place', formdata={'place': city['city']}, callback=self.get_geo)

    def get_geo(self, response):
        yield {'coord': response.css('input::text').get()}

The code run totally fine but the output I get is not correct. The default output value is (0,0) and should be something like (50.643909, 5.571560) after the form. However the crawler still gathers (0,0) as an answer. I guess the issue comes from the website but I cannot identify it.
JSON sample:
[{"city": "Anvers, BE"},
{"city": "Gand, BE"},
{"city": "Charleroi, BE"},
{"city": "Li\u00e8ge, BE"},
{"city": "Ville de Bruxelles, BE"},
{"city": "Schaerbeek, BE"},
{"city": "Anderlecht, BE"},
{"city": "Bruges, BE"},
{"city": "Namur, BE"},
{"city": "Louvain, BE"},
{"city": "Molenbeek-Saint-Jean, BE"}]

A: You can try this code, this is working in my side:
# -*- coding: utf-8 -*-
import re
import json

import scrapy

class communes_spider(scrapy.Spider):
    name = "geo"
    allowed_domains = ["www.latlong.net"]
    start_urls = ['https://www.latlong.net/']

    custom_settings = {
        'COOKIES_ENABLED': True,
    }

    # This regex is not perfect and can be improved
    LAT_LONG_REGEX = 'sm\((?P<lat>-?\d+\.?\d+),(?P<long>-?\d+\.?\d+)'

    def start_requests(self):
        FILE_PATH = 'C:/Users/coppe/tutorial/cities.json'
        with open(FILE_PATH) as json_file:
            cities_data = json.load(json_file)
        for d in cities_data:
            yield scrapy.Request(
                url='https://www.latlong.net/',
                callback=self.gen_csrftoken,
                meta={'city': d['city']},
                dont_filter=True, # Allow to request multiple time the same URL
            )

    def gen_csrftoken(self, response):
        city = response.meta['city']
        yield scrapy.FormRequest.from_response(
            response,
            formid='frmPlace',
            formdata={'place': city},
            callback=self.get_geo,
            meta={'city': city}
        )

    def get_geo(self, response):
        lat_long_search = re.search(self.LAT_LONG_REGEX, response.body.decode('utf-8'))
        if lat_long_search:
            yield {
                'coord': (lat_long_search.group('lat'), lat_long_search.group('long')),
                'city': response.meta['city']
            }
        else:
            # Something is wrong, you can investigate with `inspect_response`
            from scrapy.shell import inspect_response
            inspect_response(response, self)

The reason why you find (0, 0) is because the lat/long coordinates are displayed trough javascript (they are populated from the backend inside the template).
Scrapy cannot execute javascript without Splash.
So basically what we are doing, is parsing the JS Script with Regex in order to find the lat/long values.


text:
Q: How to calculate diff in quantity some value between months? CREATE TABLE month_c (
                     id int not null primary key,
                     quantity int not null,
                     created TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL
);

INSERT INTO month_c
(id, quantity, created)
VALUES
(1, 2, '2020-01-03 11:01:01'),
(2, 1, '2020-01-03 14:23:33'),
(3, 1, '2020-02-03 14:23:33'),
(4, 2, '2020-02-03 14:23:33'),
(5, 4, '2020-02-03 14:23:33'),
(6, 4, '2020-03-03 14:23:33'),
(7, 5, '2020-04-03 14:23:33'),
(8, 5, '2020-05-03 14:23:33'),
(9, 6, '2020-05-03 14:23:33');

and this query can calculate how much quantity was per each month
select
    sum(m.quantity),
       EXTRACT(MONTH FROM created) as month
FROM month_c as m
GROUP BY month

there is result:
sum, month
4   3
11  5
5   4
3   1
7   2

But main goall calculate diff between mont and next month, between january and february, february and macrh, march and april and result should will be like that:
sum, month
4   3
+7  5
-6  4
-2  1
+4  2

does it possible to execute it in pg query ?

A: This doesn't match your output, but your output doesn't appear to be sorted by month, which I am hoping is a mistake.
I believe what you want can be achieved with the lag analytic function:
with cte as (
  select
    sum(m.quantity) as qty,
    EXTRACT(MONTH FROM created) as month
  FROM month_c as m
  GROUP BY month
)
select
  month, qty,
  qty - lag (qty, 1, 0::bigint) over (order by month) as delta
from cte

Results:
Month     Qty    Delta
1           3       3
2           7       4  (delta between 3 and 7)
3           4      -3  (delta between 7 and 4)
4           5       1
5          11       6

LAG(expression [,offset [,default_value]])  OVER (
[PARTITION BY partition_expression, ... ]
ORDER BY sort_expression [ASC | DESC], ... )

A: All you need to do in your query is to subtract the previous month's sum which you can get with LAG() window function:
SELECT SUM(quantity) - LAG(SUM(quantity)::int, 1, 0) OVER (ORDER BY EXTRACT(MONTH FROM created)) AS "sum",
       EXTRACT(MONTH FROM created) AS month
FROM month_c as m
GROUP BY month

If the table contains data for more than 1 year, you should group by to_char(created, 'YYYY-MM') instead of EXTRACT(MONTH FROM created).
See the demo.
Results:

sum
month

3
1

4
2

-3
3

1
4

6
5


text:
Q: CordovaError: Failed to fetch platform cordova-android // Error: cmd: Command failed with exit code ENOENT I installed cordova and create a new project.
But when I use this command to add android platform, this error appears.

Can someone help me with this? I've no idea of where to start, I've tried to use all the android APIs but nothing solves this, besides there's a ENOENT error code.

A: I don't think there's a cordova platform android "6.0", as the Cordova versions usually have 3 digits. Try either of these:
cordova platform add android /* get latest version */
cordova platform add android@6.3.0 /* get 6.3.0 */

Also, version 6.0(.0) is too old, cordova-android is now in version 7.1.0 or 8.0.0 if I remember correctly. If you use obsolete cordova or cordova-android versions, some plugins could fail to install/work properly.


text:
Q: How can I send a file using to a HTTP server and read it? So, I created the following HTTP server tunneled via ngrok, and I am trying to send a file to the server, to then read it and display it on the web page of the server.
Here's the code for the server:
import os

from http.server import HTTPServer, BaseHTTPRequestHandler
from pyngrok import ngrok
import time

port = os.environ.get("PORT", 80)

server_address = ("127.0.0.1", port)

class MyServer(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write(bytes("<title>https://pythonbasics.org</title>", "utf-8"))
        self.wfile.write(bytes("
Request: %s
" % self.path, "utf-8"))
        self.wfile.write(bytes("", "utf-8"))
        self.wfile.write(bytes("
This is an example web server.
", "utf-8"))
        self.wfile.write(bytes("", "utf-8"))

    def do_POST(self):
        '''Reads post request body'''
        self._set_headers()
        content_len = int(self.headers.getheader('content-length', 0))
        post_body = self.rfile.read(content_len)
        self.wfile.write("received post request:
{}".format(post_body))

    def do_PUT(self):
        self.do_POST()

httpd = HTTPServer(server_address, MyServer)

public_url = ngrok.connect(port).public_url
print("ngrok tunnel \"{}\" -> \"http://127.0.0.1:{}\"".format(public_url, port))

try:
    # Block until CTRL-C or some other terminating event
    httpd.serve_forever()
except KeyboardInterrupt:
   print(" Shutting down server.")

   httpd.socket.close()

And I have been trying to send a file using POST as follow
>>> url = 'https://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}

>>> r = requests.post(url, files=files)
>>> r.text

I imported requests of course, and here's what I get
Exception occurred during processing of request from ('127.0.0.1', 60603)
Traceback (most recent call last):
  File "C:\Program Files\Python39\lib\socketserver.py", line 316, in _handle_request_noblock
    self.process_request(request, client_address)
  File "C:\Program Files\Python39\lib\socketserver.py", line 347, in process_request
    self.finish_request(request, client_address)
  File "C:\Program Files\Python39\lib\socketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:\Program Files\Python39\lib\socketserver.py", line 720, in __init__
    self.handle()
  File "C:\Program Files\Python39\lib\http\server.py", line 427, in handle
    self.handle_one_request()
  File "C:\Program Files\Python39\lib\http\server.py", line 415, in handle_one_request
    method()
  File "C:\Users\pierr\OneDrive\Desktop\SpyWare-20210104T124335Z-001\SpyWare\Ngrok_Test.py", line 28, in do_POST
    content_len = int(self.headers.getheader('content-length', 0))
AttributeError: 'HTTPMessage' object has no attribute 'getheader'

Could someone please help me fix this error ? I don't get where it comes from.

A: Syntax has changed. You need to use
content_len = int(self.headers.get('Content-Length'))

Instead of
content_len = int(self.headers.getheader('content-length', 0))

The rest should be the same


text:
Q: How to configure Rails 3 for JavaScript development I'm moving an app from Rails 2 to Rails 3. I have a bunch of JavaScript files in the app, most of which are for working with Google Maps. Previously, my JS files were in public/javascripts/*.js. I noticed that they were not being loaded by any of the pages that used javascript_include_tag, which writes a JavaScript tag that tries to load the JS file from /assets/*.js. (e.g. /assets/application.js).
I read that Rails 3 expects JS files to be located in app/assets/javascripts/*.js. So I moved my JS files there, but they still won't be accessible at /assets/application.js, unless I run bundle exec rake assets:precompile first.
I can't have my JS development cycle be:

*

*Make change to JS

*Run bundle exec rake assets:precompile

*Reload browser

Thats just too long. My question is how can I configure my app so that the development cycle is as follows?

*

*Make change to JS

*Reload browser

So far I've tried:

*

*Enabling the line that reads "Bundler.require(:default, :assets,
Rails.env)" in config/application.rb

*Setting config.assets.enabled = false (and true) in config/application.rb

Thanks in advance.

A: The Rails asset pipeline should be used with a manifest file. This allows Rails to concatenate all of your javascript when in production. In order to do this, you should have an application.js file that looks something like.
//= require jquery
//= require jquery_ujs
//= require_tree .

The important part here is the require_tree part. This tells Rails to include all of the other javascript files in the same folder. This means that you want both the manifest version of application.js and all of your custom javascript files to live in app/assets/javascripts.
A good guide for transitioning to the asset pipeline from Rails 2 can be found in this RailsCast: http://railscasts.com/episodes/282-upgrading-to-rails-3-1

A: recently i have this issues
I change file config/environments/development.rb

config.assets.digest = false

then that working


text:
Q: How to assign icon/image to a tbbuttoninfo? How can I assign a new image for my TBBUTTONINFO button? help me..

A: Check this out:
    TBBUTTONINFO tbButtonInfo;
    ::ZeroMemory(&tbButtonInfo, sizeof(TBBUTTONINFO));
    tbButtonInfo.cbSize = sizeof(TBBUTTONINFO);
    tbButtonInfo.dwMask = TBIF_IMAGE;
    tbToolbar.GetButtonInfo(nId, &tbButtonInfo);
    tbButtonInfo.iImage = I_IMAGENONE;
    tbToolbar.SetButtonInfo(nId, &tbButtonInfo);

For detailed information, please check the MSDN documentation for TBBUTTONINFO.


text:
Q: Unable to convert string to Timestamp I'm trying to convert a sample 12 hour date with AM/PM into a timestamp, however, Snowflake is throwing an error that it's not parsable:
SELECT TO_TIMESTAMP('7/16/2021 4:52:25 AM', 'MM/dd/yyyy HH12:mm:ss AM')
The error message returned:

Can't parse '7/16/2021 4:52:25 AM' as timestamp with format 'MM/dd/yyyy HH12:mm:ss AM'

I've tried the hours as both HH and HH12 to no avail.

A: If you want to extract only the time part you can use the below statement:
SELECT TO_TIME(TO_TIMESTAMP('7/16/2021 4:52:25 AM', 'MM/dd/yyyy HH12:mi:ss AM'))
If you want to convert it to a timestamp format, you can use the below statement:
SELECT TO_TIMESTAMP('7/16/2021 4:52:25 AM', 'MM/dd/yyyy HH12:mi:ss AM')
PFB the documentation links for date extract:
https://docs.snowflake.com/en/sql-reference/functions/date_part.html
https://docs.snowflake.com/en/sql-reference/functions/date_trunc.html


text:
Q: Angular 2 Http request does not send credentials I am working with Angular 2 and I am trying to send HTTP request with credentials:
This Angular 1 code works well, it includes the credentials:
$http.get("http://some.com/user",{ withCredentials: true})

According to the API preview I have implemented this Angular 2 code but it does not include credentials:
    http.get("http://some.com/user", {
        headers: myHeaders,
        credentials: RequestCredentialsOpts.Include
    }).toRx()
        .map(res => res.json())
        .subscribe(
        // onNext callback
            data => this.successHandler(data),
        // onError callback
            err  => this.failure(err)
    );

I am working with Angular 2.0.0-alpha.37.

A: I'm using angular2@2.0.0-alpha.37;
If you add code in xhr_backed.js, You can send 'credentials' to server
this._xhr.withCredentials = true;

angular2@2.0.0-alpha.37/src/http/backends/xhr_backed.js
var XHRConnection = (function() {
  function XHRConnection(req, browserXHR, baseResponseOptions) {
    ........
    this._xhr = browserXHR.build();
    this._xhr.withCredentials = true;
    ........

:)


text:
Q: what is the diffrence between facebook canvas url and secure canvas url diffrence between facebook canvas url and secure canvas url?
In Iframe always secure canvas url content opens,then what is the need of canvas ?

A: The secure canvas URL is used by users browsing Facebook over HTTPS
The canvas URL is used by users browsing Facebook over HTTP
This is documented here: https://developers.intern.facebook.com/docs/games/canvas


text:
Q: Why did my key got stored in home instead of .ssh? I created an RSA key pair, and during the process, I got the message:
Enter file in which to save the key (/home/pedro/.ssh/id_rsa):

So I supposed that after giving it a name, it would store the key in the .ssh folder. However, the only thing inside the .ssh folder is the known_hosts and my key got stored in home. Did I misunderstand how this process works?

A: The example - /home/<user>/.ssh/id_rsa - provides the default key name id_rsa and the default path /home/<user>/.ssh/ where it will be stored. So analogically you should provide a path and a filename. In case you don't provide a path the key will be generated within the current directory.


text:
Q: Set WooCommerce product attribute via query string parameter I have a product that needs to include a referral token in an attribute of the product. The referral code will be in a query string parameter. The idea is to have this referral token captured in the product data so that it can at least be viewed in the order details that an admin has access to. For example..
Product URL is: test.com/product/my-product?referral_token=12345
I already have an attribute created that is named Referral Token and is set to 000 by default.
Using print_r($product->get_attributes()); returns the following..
Array
(
    [referrer-token] => WC_Product_Attribute Object
        (
            [data:protected] => Array
                (
                    [id] => 0
                    [name] => Referrer Token
                    [options] => Array
                        (
                            [0] => 000
                        )

                    [position] => 0
                    [visible] =>
                    [variation] =>
                )

        )

)

When viewing the URL above how can I set the referrer-token attribute to be the value from the referral_token query string parameter that equals 12345? I'm also open to any other suggestions as to how to attach this referral token to the product.

A: Following up from my comments on your question you can do them like this.
Set Session value when query parameter is present
// Run this on product page and when the query parameter is there
$woocommerce->session->set( '_referral_token', '1234XYZ' );

Use woocommerce_thankyou action hook to trigger the save the token.
add_action( 'woocommerce_thankyou','save_referal_after_order_completion', 10, 1 );

function save_referal_after_order_completion($order_id) {
   global $woocommerce;
   $order = wc_get_order( $order_id );
   $referral= $woocommerce->session->get( '_referral_token' );

   if($referral) {
     $order->update_meta_data( '_referral', $referral);
     $order->save();
     $woocommerce->session->__unset( '_referral' ); // Remove session when done.
   }

}


text:
Q: update column by specific old and new value in 1 column enter image description here
this is a log table all cards changed values saved in this table now i add column  to insert the old values for the the card the problem is i want to do in code is a procedure scan the table and but the old value in the new column.  what is old value the old value is the same value one the card is not duplicate then its have no old values but if it duplicate so there is an old value the image i upload Identifies what i want to do  thank you for help :)

A: This should point you in the right direction to see how a previous value can be tracked (I am assuming a timestamp field called TS to track the order of instances for a given card_code. You will need to adjust to meet your data model). you just need to base an update around it, setting total_number_o for the given card_Code and TS.
with tab as (
          select 101012172583 card_code, '005' total_number, sysdate ts from dual
union all select 101012172583 card_code, '006' total_number, sysdate-1/12 ts  from dual
union all select 101012172583 card_code, '003' total_number, sysdate-2/12 ts  from dual
union all select 101012172583 card_code, '003' total_number, sysdate-3/12 ts  from dual
union all select 101012172583 card_code, '005' total_number, sysdate-4/12 ts  from dual
union all select 101012172583 card_code, '004' total_number, sysdate-5/12 ts  from dual
            )
select card_Code
     , total_number
     , lag(total_number) over ( partition by card_code order by ts) total_number_o
     , ts
from tab order by card_Code, ts desc;

CARD_CODE                              TOTAL_NUMBER   TOTAL_NUMBER_O   TS
101012172583                           "005"          "006"            01/12/2015 3:16:35 PM
101012172583                           "006"          "003"            01/12/2015 1:16:35 PM
101012172583                           "003"          "003"            01/12/2015 11:16:35 AM
101012172583                           "003"          "005"            01/12/2015 9:16:35 AM
101012172583                           "005"          "004"            01/12/2015 7:16:35 AM
101012172583                           "004"                           01/12/2015 5:16:35 AM


text:
Q: Fill UL Space with 2nd to last Li? I have been trying to get this to work for about 2 days now, but i can get nothing. Here is my layout. I have a navbar with some elements, and the last one is floating right. This leaves a lot of space left between the last and the second to last li. How can i make that second to last li fill up the ul? I already tried to treat it as a table, but that did not work. Here is some of my css:
.NavBar > ul {
list-style:inside none;
margin:0;
padding:0;
display: table;
width:100%;
}

.NavBar > ul > li {
list-style:inside none;
display:block;
float:left;
position:relative;
margin:0;
padding:0;
}

.NavBar > ul > li > a:hover {
background:#111;
}

.NavBar > ul > li:nth-last-child(2) {
list-style:inside none;
display:table-cell;
}

If there is any more code you need, just tell me and i will post it. Thanks.
Here is what i need to happen.
The News li need to grow to fill up space in between it and the login li.

A: Is there a reason you are floating the last li right instead of left?  If you keep the floats left you shouldn't have the spacing problem.
If this doesn't help, I think you're going to need to give more details as to what you want to accomplish.

Okay, I suspect there's more that you haven't yet told us, but take a look at this quick and dirty sample and let me know how close it comes to your goal:

Widgets</>

Boojuns</>

Snarf</>

Xyzzy</>

Plugh</>

The background colors are just to help us see what's happening.


text:
Q: Is there a software like Nokia Ovi Suite for syncing Nokia symbian phones with GNU/Linux? I have been looking unsuccessfully for many days for a nice linux software similar to the Nokia Ovi Suite or Nokia PC Suite for syncing Messages, Contacts etc in Ubuntu/Fedora.
There were rumors about a 'Nokia Ovi Suite for linux' in Nokia Beta Labs. But it didn't exist last time I checked.
It is really inefficient to switch to windows time and again just to sync my phone.
Any suggestions?

A: Gammu and Gnokii have support for some Symbian phones - mostly older ones.

A: I too tried many different options with no joy.
I use the ovi sync feature (pre installed) on my nokia c7, this is done through my wireless connection at home (no charge).  All of my contacts, calendar, and notes can then be accessed through normal browser (Firefox) on Ubuntu.
It does require sign in and so registration is needed.


text:
Q: How to include empty values using in a query to create relationship between column and row I have a query who returns the next results
+-----------+--------+-------+
| idPeriodo | codigo | valor |
+-----------+--------+-------+
|     1     |   7    |  1000 |
|     1     |   8    |  1000 |
|     1     |   9    |  1000 |
|     2     |   7    |  1000 |
|     2     |   8    |  1000 |
|     3     |   7    |  1000 |
|     3     |   9    |  1000 |
+-----------+--------+-------+

I need to organize the query because I'm creating a text plain file with the results, so in the first row I need to put each "codigo" split by tab, something like this.
--This is the first row, is like a head
    7   8   9

Afther this, I need to put the column "valor" associated with its respective codigo and idPeriodo. The final result must be something like this:
    7       8       9
1   1000    1000    1000
2   1000    1000
3   1000            1000

Now I have two queries, the first one is to obtain the first row(head with codigo values) and second one I'm doing a query to obtain all values from column "valor" grouped by idPeriodo.
These are my queries looks like.
-------Query to return head(codigo values)---------------
SELECT DISTINCT CONCAT(conjunto.codigo, central.confterm_id) as codigo_central
FROM   mantenimiento_central_termica mantenimiento
JOIN   configuracion_central_termica central
ON     central.confterm_id = mantenimiento.confterm_id
JOIN   conjunto_centrales conjunto
ON     central.id_conjuntocentral = conjunto.id

-------Query to return valor grouped by idPeriodo---------------
SELECT id_periodo ,
       valor_mantenimiento = string_agg(valor_mantenimiento, CHAR(9))
       WITHIN GROUP (ORDER BY codigo_central)
FROM(
SELECT CONCAT(conjunto.codigo, central.confterm_id) as codigo_central,
       per_id                          AS id_periodo ,
       mantenimcentraltermica_potencia AS valor_mantenimiento
FROM   mantenimiento_central_termica mantenimiento
JOIN   configuracion_central_termica central
ON     central.confterm_id = mantenimiento.confterm_id
JOIN   conjunto_centrales conjunto
ON     central.id_conjuntocentral = conjunto.id
WHERE  cas_id = 2) main_thermal
GROUP BY id_periodo

The problem I have is the second query returns only the values from column valor who is not null and when I'm going to split the first query with the second one I obtain something like this:
    7       8       9
1   1000    1000    1000
2   1000    1000
3   1000    2000    --The error is here, because the 2000 value must be in the third column, with the 9(codigo) value.

I need the query put a blank space when find a null valor in a relation between codigo and idPeriodo.
How Can i do that ?

A: The answer was provided in stackoverflow.
This is the link to the answer.
https://stackoverflow.com/a/59737671/3865734


text:
Q: Как выбрать одну ссылку в навигации для стилизации? Есть такая проблема: есть навигация, пункты меню и ссылки в них, хочу выбрать первую ссылку для стилизации, испробовал - first-child и nth-child(1) - ничего не работает.
Подскажите, как это можно справить, хочу применить border-radius для первой ссылки.
Мой код:

.menu__link {
     display: block;
     padding: 10px 40px;
     color: #fff;
     text-transform: uppercase;
     letter-spacing: 2px;
     text-shadow: 4px 4px 5px black;
     transition: background .25s;
     background: rgba(255, 255, 255, .4);
}
.menu__link:hover{
     background: rgba(0, 0, 0, .4);
}

.menu__link:nth-child(1){
     border-radius: 10px 0 0 10px;
}

.menu__link:nth-child(6){
     border-radius: 0 10px 10px 0;
}

 <menu class="menu">

Секция 1

Секция 2

Секция 3

Секция 4

Секция 5

Секция 6

 </menu>

A: В таком виде все работает.
Чтобы был виден результат border-radius, нужно задать border.

.menu__item:first-child .menu__link {
  border: 1px solid black;
  border-radius: 5px;
}

  <menu class="menu">

Секция 1

Секция 2

Секция 3

Секция 4

Секция 5

Секция 6

  </menu>

A: :first-child нужно применять для элемента списка li, а не для a
.menu > .menu__item:first-child > .menu__link {
    border-radius: 5px;
}


text:
Q: List Of String not inserting data Running into an issue where i am trying to Insert() data into a list Of String but for some reason it is not inserting the data.
Private Sub Build(param 1, param 2, param 3,)
  Dim dataList As New List(Of String)
  Dim charcode as String = ""
  Dim index As Integer = 0

  For i As Integer = 0 To rowCount - 1
    dataList.Add("data" & i)
  Next

  'dataNum is of int value (zero based) from 0 - whatever number
  For Each Item As String In root.Subfields
    charcode = GetChar(Item, 2)
    If Not charCodes.Contains(charcode) Then
      dataList(dataNum).Insert(index, Item)
      index += 1
    End If
  Next
End Sub

Using Visual Studio debugger i can see that the dataList is being populated

But when we get down to the For Each the data is not being populated into the list under the appropriate collection (data1, data2)

What's going on here? Surely this should work (right?).
thank you.
EDIT:
Here is an image of what i am trying to accomplish:

as you can see i have a main collection with collections or sub fields inside that one.

A: It sounds from the question text like you're trying to insert a whole new string as a new entry in your list. Look carefully at this line:
dataList(dataNum).Insert(index, Item)

When this code executes, it first retrieves the List(Of String) object referred to by the dataList variable, and then looks up the specific string object at index dataNum. Now you have a single string (not a List anymore) and you call the string's Insert() method. It's not the Insert() method for the list.
To fix this, I'd need to know more about how you're using the index variable that's not referred to or declared anywhere else in the code or the question text. It's not clear how you expect this to be used.
Or maybe you really wanted just a string. If so, that's not what your question text is asking for. But if you're really trying to insert additional text into that specific string, you still have a problem. String objects in .Net don't change (we say they are "immutable"). When you use a method like Insert(), rather than changing that string instance, it produces and returns a new string object. With that in mind, you need to assign that new string somewhere. That would look like this:
dataList(dataNum) = dataList(dataNum).Insert(index, Item)

But, again, that's not what the text of your question is asking for. I'm including it here because it better matches the code sample.

A: Strings are immutable. If you call Insert on a string you need to catch the return value of the insert where the change is returned. The original string is not changed. By the way, do you realize that you are Inserting into a string and not into the list?
If you want to insert a string inside the current list you need something like this (It is not very clear from the code above if you need to use the variable datanum or the variable index to choose the appropriate position in the list)
For Each Item As String In root.Subfields
  charcode = GetChar(Item, 2)
  If Not charCodes.Contains(charcode) Then
    dataList.Insert(index, Item)
    index += 1
  End If
Next

From your comment below it seems that you want only replace an element of the list with a new value. In this case you can treat the list like it was an array and write something like
dataList(0) = newItem;


text:
Q: ASP.NET to AS/400 Communication Error When trying to access an AS/400 server from an ASP.NET webservice, I'm getting the following log message:

0x00000D98 0x00000001 10/14/2009
  16:16:08.734375 :
  iDB2ConnectionFailedException(9119245).Void
  .ctor(System.String) :
  iDB2ConnectionFailedException thrown
  0x00000D98 0x00000001 10/14/2009
  16:16:08.750000 :
  iDB2ErrorCollection(14964341).Void
  Add(IBM.Data.DB2.iSeries.iDB2Error) :
  MESSAGE: The connection cannot be
  opened because an error occurred.
  MESSAGE DETAILS: A system policy has
  been set preventing connections to a
  data source through this provider.
  MESSAGE CODE: 0

Note:  The user can ping the AS/400 from the webserver.
Any thoughts?

A: I've never run into this situation myself, but I found a post on a different message board that may help.  It's at: http://forums.systeminetwork.com/isnetforums/showthread.php?t=48786
To summarize, the individual with the problem had to go into iSeries navigator and customize the setting in application administration.  To access application administration, start iSeries navigator and connect with a security officer profile.  Then right-click on your system and choose application administration.  Select the Client Applications tab.  Navigate to ODBC support and click on customize.  See if the user in question is blocked.
Here is a link to the IBM iSeries Infocenter for V5R4's documentation on application administration.  It may help to review it before trying to change anything: http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=/rzaj3/rzaj3overview.htm
Here is a really good Four Hundred Guru article on application administration: http://www.itjungle.com/fhg/fhg070809-story03.html
Granted, this only helps if the iSeries application administration settings are such that ODBC is blocked for this user.  There could very well be other Windows system policies that are blocking access to the iSeries data source.  In which case, this answer will not help you at all.

A: being able to ping the server and being able to connect to a database service are two different things. Have you checked the policies and permissions on the AS/400?


text:
Q: change thead tags created by HtmlTextWriter I am using C#'s HtmlTextWriter to create a HTML table.
When I loop trough creating my table header it creats it in this format

colname	colname	colname	colname

I want the
 to say
 and the  to say .
How do I program HtmlTextWriter to change the tag values?
Here's my loop for creating the header.
public void BuildHTMLTable(DataTable dt)
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter w = new HtmlTextWriter(sw);

    Table tbl = new Table();
    tbl.ID = "example";
    tbl.CssClass = "display";
    tbl.CellSpacing = 0;

    TableHeaderRow thr = new TableHeaderRow();
    foreach (DataColumn col in dt.Columns)
    {
        TableCell th = new TableCell();
        th.Text = col.Caption;
        thr.Controls.Add(th);
    }
    tbl.Controls.Add(thr);

    foreach (DataRow row in dt.Rows)
    {
        TableRow tr = new TableRow();
        foreach (var value in row.ItemArray)
        {
            TableCell td = new TableCell();
            td.Text = value.ToString();
            tr.Controls.Add(td);
        }
        tbl.Controls.Add(tr);
    }

    TableFooterRow tfr = new TableFooterRow();
    foreach (DataColumn col in dt.Columns)
    {
        TableCell th = new TableCell();
        th.Text = col.Caption;
        tfr.Controls.Add(th);
    }
    tbl.Controls.Add(tfr);
    tbl.RenderControl(w);
    tableString = sw.ToString();
}


text:
Q: Reading from messages properties in spring boot controller I have a messages.properties file in my spring boot application:
mymessage = this message

Now, is there a way to get this value from one of my controller methods in spring boot?

A: I don't know what a message.properties file is in relation to spring boot but I know you can have a service.properties file and/or an application.properties file. To read from either of these you can use @Value please see documentation here https://www.baeldung.com/spring-value-annotation
This will allow you to inject your value from your .properties file into your controller


text:
Q: TeamCity does not catch failing tests in minitest I have TeamCity up and running in a mac environment. A trigger is also setup to to run a rake task containing a number of test cases on every git commit. The rake command successfully pulls the code and runs the test cases. The passing test cases are shown correctly in the TeamCity interface, however, the failing test cases do not show up and the build is marked as successful. When I look at the error Build Log, failing tests are shown as errors. The question is why TeamCity is interpreting failing tests as errors and not as actual failing tests?
The assertions are as simple as the following (obvious failure):
test 'simple_test' do
    a = 14
    ssert_equal 341, a
ends

PS: the check box to fail the build upon at least one test fail is turned on in Failure Conditions(i.e. at least one test failed)
Ruby version = 2.2.2,
Rails version = 4.2.1,
TeamCity version =  9.1.1,
Testing framework = minitest,

Here is the build log output

A: Teamcity is not picking up failed tests because mini-test reporter is not up and running. To fix this, following gems must be present in the Gemfile:
gem "minitest", :group => :test
gem 'minitest-reporters', :group => :test

Also minitest reporter must be called. The best place to call it is test_helper.rb
require 'minitest/reporters'
MiniTest::Reporters.use!


text:
Q: Multiple statements in a where clause I'm trying to create a where clause that has 2 statements that work together and then a separate statement that works by itself if it meets a certain criteria
I've tried CASE statements, AND's, OR's and still nothing works
WHERE HB.CreatedByDate = @ReportDateN AND HB.Date = @ReportDateN - 1

So this code is my current where clause that get's me results that have the CreatedByDate equal to the variable @ReportDateN but also have the regular date equal to the variable @ReportDateN except it minuses one day.
This by itself does what I want it to do but I'd like to add some more.
I want to make it so if a variable called @WeekDay = 'Monday' then to subtract 3 from @ReportDateN in the second part instead of just 1.
Any help will be appreciated, thanks!

A:    WHERE HB.CreatedByDate = @ReportDateN
     AND HB.DATE = CASE
        WHEN @Weekday = 'Monday'
            THEN (@ReportDateN - 3)
        ELSE (@ReportDateN - 1)
         END

This can also be done by combining OR Statements
WHERE HB.CreatedByDate = @ReportDateN AND
      (
       @Weekday = 'Monday' AND HB.Date = (@ReportDateN - 3)
      )
   OR
      (
        @Weekday != 'Monday' AND HB.Date = (@ReportDateN - 1)
      )

Just for Reference, note that the following will not work:
 WHERE CASE @Weekday = 'Monday' THEN .... ELSE ..... END

EDIT: Per op's comment below:
WHERE HB.CreatedByDate = @ReportDateN AND
      (
       @Weekday = 'Monday' AND (
                                HB.Date = (@ReportDateN - 3) OR
                                HB.Date = (@ReportDateN - 2) OR
                                HB.Date = (@ReportDateN - 1)
                               )
      )
   OR
      (
        @Weekday != 'Monday' AND HB.Date = (@ReportDateN - 1)
      )

A: How about this :
WHERE
     HB.CreatedByDate = @ReportDateN AND
     (
        @WeekDay = 'Monday' AND HB.Date = @ReportDateN - 3
        OR
        HB.Date = @ReportDateN - 1
    )


text:
Q: iOS 7, scope bar becomes black in search mode I use UISearchDisplayController embedded to UiTableViewController to make a search bar in my table view. But if I set the search bar's background image, the scope bar do not show in search mode, but showing a black bar instead. It's very weird because it does not happen in iOS 6.
Note that the image I used to set the search bar's background image is 640x90 px, somehow the scope bar will show if use other image.
Even if I set the scope bar background image, it sill not show depend on the search bar's image setting.
I think it's a bug in iOS 7, and to prevent from other factors, I even use the master-detail template in Xcode 5, and embed the UISearchDisplayController in master view controller, change the search bar background image and scope bar shows black in search mode.
I think it has something to do with iOS 7 auto resize of view controller. Bothers me so much.
Someone please try and help. Thanks a lot a lot.
------------------------------edited--------------------------
Sometimes the scope bar will show if I change search bar background image, but in real device (iPhone5), the scope bar never show.

A: I have just found a solution here: IOS7 Status bar change to black after search is active
Just put these two lines on your table view controller (viewDidLoad):
self.navigationController.view.backgroundColor = [UIColor whiteColor];

self.navigationController.navigationBar.translucent = NO;

Where "whiteColor" is the color that you need for the status Bar.

A: I have resolved this problem by using UISearchBar appearance:
[[UISearchBar appearance] setBackgroundImage:bgImage forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];


text:
Q: What is the correct encoding for Indy Tidhttp for posting XML Files? I notice I have invalid characters for XML files in an application who use Indy Client (I actually use default parameters for IdHttp)
Here is my code :
  ts := TStringList.Create;
  try
    ts.Add('XML=' + AXMLDoc.XML.Text));
    HTTPString := IdHTTPClient.Post('http://' + FHost + ':' + IntToStr(FPort) + FHttpRoot, ts);
  finally
    ts.Free;
  end;

My XML file is UTF-8 encoded.
What I have to do get good encoding on my server (I also use Indy for server) ?

A: UTF-8 is the default charset that TIdHTTP uses for submitting a TStringList object. The real issue is that XML should not be submitted using a TStringList to begin with, even with a proper charset. The reason is because the TIdHTTP.Post(TStrings) method implements the application/x-www-form-urlencoded content type, and thus url-encodes the TStringList content, which can break XML if the receiver is not expecting that.  So unless the receiver is actually expecting a real application/x-www-form-urlencoded encoded request, XML should be transmitted using the TIdHTTP.Post(TStream) method instead so the raw XML bytes are preserved as-is.


text:
Q: Configure the path into properties file I have a JBoss 7 application server and it consists of a file logging.properties.
In the logging.properties file, the path is defined (hard coded) as

com.import.uploadDirectory=C:\progra~2\Demo\test\jboss7\standalone\uploads
  com.export.templateFile=C:\progra~2\Demo\test\jboss7\standalone\templates\GDV_HDI_Format.xls

double slash "\"is needed because it works for windows system.
Now i want to remove the hard coded path and make system's absolute path.
What I tried is:

com.import.uploadDirectory=..\..\..\..\..\standalone\uploads

but still it's not working and I am getting a FileNotFoundException
Currently I'm in the location

C:\Program Files (x86)\Demo\test\jboss7\modules\com\c4i\configuration\main

and logging.properties file exists in the main folder
Is there way to rectify it?


text:
Q: can't open passbook passes when served through an nginx reverse proxy My problem is that I can download passbook passes directly from my api, but with nginx as a reverse proxy in front of my api, safari can no longer open the pass.
I have a system with a ticket-service, an api and an nginx instance that operates as a reverse proxy.
I can request a ticket as a passbook pass file directly from the api through my ios simulator, but when I do the same with nginx between, ios safari returns: "Safari cannot download this file.".
I have tried to do the two requests through chrome on my laptop to check the headers and noticed that nginx adds two; Connection: keep-alive and Server: nginx.
I then tried to add those two to the api as well, just to check that safari don't complain about them and the headers then seem to be the same in chrome.
Headers
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Etag
Connection: keep-alive
Content-Disposition: attachment; filename="JABJcCu42k"
Content-Encoding: gzip
Content-Length: 72312
Content-Type: application/vnd.apple.pkpass
Pragma: no-cache
Server: nginx
Vary: Accept-Encoding
Date: Thu, 09 Jul 2015 10:01:31 GMT

Does anyone have experience or have an idea of what the problem might be?
Thanks!
BR Fredrik


text:
Q: Unrecognized special character with comment package Why are the character with accent not recognized ?
\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[french]{babel}
\usepackage{comment}

\includecomment{withsolution}

\begin{document}
\begin{withsolution}
à
\end{withsolution}
\end{document}

returned error:
! Paragraph ended before \UTFviii@three@octets was complete.

If I put it outside the comment environment, it works.
Thanks for the help.


text:
Q: absolutely continuous functions as a subspace of continuous functions with bounded variation The space of absolutely continuous functions on $[0,1]$ is equipped with norm $\|f\|:=|f(0)|+V_0^1(f)$.
Every AC-function is continuous with bounded variation, so it is a subspace of $C[0,1]\cap BV[0,1]$.
Is this subspace closed?

A: According to a positive answer to an other your question, this space of absolutely continuous functions is complete, so it is closed in a metric space $C[0,1]\cap BV[0,1]$, containing it.


text:
Q: UWP how to make Grid scrollable in XAML I need to make my form in XAML (in UWP app) responsive and also scrollable. I have code like this
 <Grid x:Name="MainGrid">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup>
            <VisualState x:Name="WideState">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="720" />
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="MainGrid.Margin" Value="24"/>
                    <Setter Target="MainGrid.RowDefinitions[1].Height" Value="auto"/>
                    <Setter Target="MainGrid.ColumnDefinitions[1].Width" Value="*"/>
                    <Setter Target="FirstGrid.Margin" Value="0 0 12 0"/>
                    <Setter Target="SecondGrid.Margin" Value="12 0 0 0"/>
                    <Setter Target="SecondGrid.(Grid.Column)" Value="1"/>
                    <Setter Target="SecondGrid.(Grid.Row)" Value="0"/>
                </VisualState.Setters>
            </VisualState>
            <VisualState x:Name="NarrowState">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="0" />
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="MainGrid.Margin" Value="12"/>
                    <Setter Target="FirstGrid.Margin" Value="0 0 0 0"/>
                    <Setter Target="SecondGrid.Margin" Value="0 0 0 0"/>
                    <Setter Target="MainGrid.RowDefinitions[0].Height" Value="auto"/>
                    <Setter Target="MainGrid.RowDefinitions[1].Height" Value="*"/>
                    <Setter Target="MainGrid.ColumnDefinitions[1].Width" Value="auto"/>
                    <Setter Target="SecondGrid.(Grid.Column)" Value="0"/>
                    <Setter Target="SecondGrid.(Grid.Row)" Value="1"/>
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>

    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <Grid x:Name="FirstGrid" Grid.Column="0" Grid.Row="0">

        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>

        <Grid Grid.Column="0" Grid.Row="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="130"/>
                <ColumnDefinition Width="*" MaxWidth="500"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <TextBlock Grid.Column="0" Grid.Row="0" x:Uid="lblName" />
            <my:SfTextBoxExt Grid.Column="1" Grid.Row="0" x:Uid="txtName" />
        </Grid>

    </Grid>
    <Grid x:Name="SecondGrid" Grid.Column="1" Grid.Row="0" >

        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>

        <Grid Grid.Column="0" Grid.Row="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="130"/>
                <ColumnDefinition Width="*" MaxWidth="500"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <TextBlock Grid.Column="0" Grid.Row="0" x:Uid="lblAge" />
            <my:SfTextBoxExt Grid.Column="1" Grid.Row="0" x:Uid="txtAge" />
        </Grid>

    </Grid>

</Grid>

This is responsive, but not scrollable. When I add a ScrollViewer above the MainGrid -> It will be scrollable, but responsivity is not working (           <VisualState x:Name="WideState">)
Do you have any ides how can I make this Grid scrollable? Thx.

A: You need to have VisualStateGroups as a member of the root container.
The structure will be like:
<Grid Name=root>
    VisualStateGroups here....
    <ScrollViewer>
        <Grid Name=MainGrid>
            ...First and Second grid...
        </Grid>
    </ScrollViewer>
</Grid>

A: Putthe VisualState code inside ScrollViewer instead of Grid
 <ScrollViewer>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup>
                <VisualState x:Name="WideState">
                    <VisualState.StateTriggers>
                        <AdaptiveTrigger MinWindowWidth="720" />
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter Target="MainGrid.Margin" Value="24"/>
                        <Setter Target="MainGrid.RowDefinitions[1].Height" Value="auto"/>
                        <Setter Target="MainGrid.ColumnDefinitions[1].Width" Value="*"/>
                        <Setter Target="FirstGrid.Margin" Value="0 0 12 0"/>
                        <Setter Target="SecondGrid.Margin" Value="12 0 0 0"/>
                        <Setter Target="SecondGrid.(Grid.Column)" Value="1"/>
                        <Setter Target="SecondGrid.(Grid.Row)" Value="0"/>
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="NarrowState">
                    <VisualState.StateTriggers>
                        <AdaptiveTrigger MinWindowWidth="0" />
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter Target="MainGrid.Margin" Value="12"/>
                        <Setter Target="FirstGrid.Margin" Value="0 0 0 0"/>
                        <Setter Target="SecondGrid.Margin" Value="0 0 0 0"/>
                        <Setter Target="MainGrid.RowDefinitions[0].Height" Value="auto"/>
                        <Setter Target="MainGrid.RowDefinitions[1].Height" Value="*"/>
                        <Setter Target="MainGrid.ColumnDefinitions[1].Width" Value="auto"/>
                        <Setter Target="SecondGrid.(Grid.Column)" Value="0"/>
                        <Setter Target="SecondGrid.(Grid.Row)" Value="1"/>
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    <Grid x:Name="MainGrid" Background="Green">

        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <Grid x:Name="FirstGrid" Grid.Column="0" Grid.Row="0" Background="Yellow">

            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"/>
            </Grid.RowDefinitions>

            <Grid Grid.Column="0" Grid.Row="0" Height="500">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="130"/>
                    <ColumnDefinition Width="*" MaxWidth="500"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <TextBlock Grid.Column="0" Grid.Row="0" x:Uid="lblName" />

            </Grid>

        </Grid>
        <Grid x:Name="SecondGrid" Grid.Column="1" Grid.Row="0" Height="500" Background="Blue">

            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"/>
            </Grid.RowDefinitions>

            <Grid Grid.Column="0" Grid.Row="0">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="130"/>
                    <ColumnDefinition Width="*" MaxWidth="500"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <TextBlock Grid.Column="0" Grid.Row="0" x:Uid="lblAge" />

            </Grid>

        </Grid>

    </Grid>
    </ScrollViewer>


text:
Q: not able display details in grid using MVC where I have got one textbox and button and when the user entered a value and the press submit button , that values i need to show in Kendo UI Grid in same view  ..
for this purpose i have done like this .....
this is my model..
namespace KendoSampleMVCApp.Models
{
    public class TextBoxGrid
    {
        public string EnteredValue { get; set; }
        public List<EmployeeDetails> employees;
    }
    public class EmployeeDetails
    {
        public string EmployeeId { get; set; }
        public string ManagerId { get; set; }
    }
}

and this is my controller
namespace KendoSampleMVCApp.Controllers
{
    public class EnterValuesGridController : Controller
    {
        public ActionResult Index( TextBoxGrid model)
        {
            return View(GetEmployee());
        }
        [HttpPost]
        public ActionResult PostValues(TextBoxGrid model)
        {
            TempData["enteringValue"] = model.EnteredValue;
            return View(model);
        }
        public  IEnumerable<EmployeeDetails> GetEmployee()
        {
            string enteredValueId =(string) TempData["enteringValue"];
            string managerId = "M" +enteredValueId;
            List<EmployeeDetails> empdtls = new List<EmployeeDetails>();
            EmployeeDetails em1 = new EmployeeDetails();
            em1.EmployeeId = enteredValueId;
            em1.ManagerId = managerId;
            empdtls.Add(em1);
            return empdtls;
        }
        public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
        {
            return Json(GetOrders().ToDataSourceResult(request));
        }
        private  IEnumerable<EmployeeDetails> GetOrders()
        {
            return GetEmployee();
        }
    }
}

and this is my view
@model KendoSampleMVCApp.Models.TextBoxGrid
@{
    ViewBag.Title = "Index";
}

Index

@using (Html.BeginForm("PostValues","EnterValuesGrid",FormMethod.Post))
{

   <fieldset>
        <legend>Enter Textbox Value</legend>

            @Html.TextBoxFor(m=>m.EnteredValue)

            <input type="submit" name="Submitbutton1" value="Submit1" />

    </fieldset>

}
@model IEnumerable<KendoSampleMVCApp.Models.EmployeeDetails> <-----  error at this line

Index

@using (Html.BeginForm())
{
    @(Html.Kendo().Grid<KendoSampleMVCApp.Models.EmployeeDetails>()
    .Name("grid")
    .Columns(columns => {
        columns.Bound(p => p.EmployeeId).Filterable(false).Width(100);
        columns.Bound(p => p.ManagerId).Filterable(false).Width(100);
    })
    .Pageable()
    .Sortable()
    .Scrollable()
    .Filterable()
    .HtmlAttributes(new { style = "height:430px;" })
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Read(read => read.Action("Orders_Read", "EnterValuesGrid"))
     )
  )
}

I am getting error at this line @model IEnumerable<KendoSampleMVCApp.Models.EmployeeDetails>
saying that
Parser Error Message: Only one 'model' statement is allowed in a file.
would any one pls suggest any ideas why i am getting this error ...can't i use two models in same view ....
many thanks ...
EDIT : can i do like this In my model...
 public class ParentViewModel
 {
      public EmployeeDetails EmployeeDetails { get; set; }
       public TextBoxGrid TextBoxGrid { get; set; }
 }

A: The answer is no, you can't use two models in one view. And there is no reason why you should need to. The whole point of a view model is that is designed to store all of the data for the view to which it corresponds.
Create an EnterValuesViewModel class and instantiate it with all of the necessary data from both of your business entities. Then type your view to this class.
public class EnterValuesViewModel
{
    public string EnteredValue { get; set; }
    public List<EmployeeDetailsViewModel> Employees { get; set; }
}

public class EmployeeDetailsViewModel
{
    public string EmployeeId { get; set; }
    public string ManagerId { get; set; }
}

View:
@model EnterValuesViewModel

@Html.TextBoxFor(m=>m.EnteredValue)

@foreach(EmployeeDetailsViewModel emp in Model.Employees)
{
    @* Stuff about each employee goes here *@
}

Alternatively, look at partial views.


text:
Q: glutKeyboardFunc calling function not working I am trying to call a function, only when "spacebar" is pressed. Its key code is 32.
#include <GL/glut.h>
#include <GL/glu.h>
#include <GL/gl.h>
#include <cmath>
#include <iostream>
#include <string.h>

using namespace std;

GLuint window, View1;
void Display_Mid_Ellipse()
{

    double xc=0.0, yc=0.0,  rx=140.0, ry=200.0;
    double rxSq = rx * rx;
    double rySq = ry * ry;
    double x = 0, y = ry, p;
    double px = 0, py = 2 * rxSq * y;
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f( 1 ,0, 0);
     glBegin(GL_POINTS);

     glVertex2d(xc+x,yc-y);
     glVertex2d(xc-x,yc-y);
     glVertex2d(xc-x,yc+y);
    glEnd();

    p = rySq - (rxSq * ry) + (0.25 * rxSq);
    while (px < py)
    {
                    x++;
                    px = px + 2 * rySq;
                    if (p < 0)
                    p = p + rySq + px;
                    else
                    {
                    y--;
                    py = py - 2 * rxSq;
                    p = p + rySq + px - py;
                    }
                     glBegin(GL_POINTS);

                     glVertex2d(xc+x,yc+y);
                     glVertex2d(xc+x,yc-y);
                     glVertex2d(xc-x,yc-y);
                     glVertex2d(xc-x,yc+y);
                    glEnd();

    }

    p = rySq*(x+0.5)*(x+0.5) + rxSq*(y-1)*(y-1) - rxSq*rySq;
    while (y > 0)
    {
            y--;
            py = py - 2 * rxSq;
            if (p > 0)
            p = p + rxSq - py;
            else
            {
            x++;
            px = px + 2 * rySq;
            p = p + rxSq - py + px;
            }
           glBegin(GL_POINTS);

     glVertex2d(xc+x,yc+y);
     glVertex2d(xc+x,yc-y);
     glVertex2d(xc-x,yc-y);
     glVertex2d(xc-x,yc+y);
    glEnd();
    glFlush();

    }
}    //end_MIDPOINT_ELLIPSE

void init () {
    glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.3,0.3,0.3,0.7);
    gluOrtho2D(-500.0,500.0,-500.0,500.0);
}
void View1Display()
{
glutSetWindow(View1);
gluOrtho2D(-500.0,500.0,-500.0,500.0);
Display_Mid_Ellipse();

   }
    void Display()
 {
    glutSetWindow(window);
    glClear(GL_COLOR_BUFFER_BIT);
    //View1Display();
 }

void keyFunc(unsigned char ch, int x, int y){

if(ch==32){
View1Display();
}
}

int main (int argc, char *argv[]) {

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

glutInitWindowSize(750, 750);
glutInitWindowPosition(0, 0);

window=glutCreateWindow("Circle and ellipse");
init();

View1 = glutCreateSubWindow(window,20,40, 340,340);
glutDisplayFunc(Display);
glutKeyboardFunc(keyFunc);
glutMainLoop();

    return 0;
}

When i call the same View1Display from the Display() function, it works well.
I'm confused. I have tried the alternatives I could but could not find a solution. Please help.
Thanks

A: *

*Callbacks are registered for the active window (creating a window implicitly activates it) so you can register separate display callbacks for the toplevel window and your subwindow.

*Don't call your subwindow display function from the keyboard callback.  Toggle a shared variable & use glutPostWindowRedisplay() to force a redraw instead.

*If you're going to use GLUT_SINGLE make sure to glFlush() to force updates out to the framebuffer.

All together:
#include <GL/glut.h>
#include <cmath>

using namespace std;

void Display_Mid_Ellipse()
{
    double xc = 0.0, yc = 0.0, rx = 140.0, ry = 200.0;
    double rxSq = rx * rx;
    double rySq = ry * ry;
    double x = 0, y = ry, p;
    double px = 0, py = 2 * rxSq * y;
    glClear( GL_COLOR_BUFFER_BIT );
    glColor3f( 1, 0, 0 );
    glBegin( GL_POINTS );

    glVertex2d( xc + x, yc - y );
    glVertex2d( xc - x, yc - y );
    glVertex2d( xc - x, yc + y );
    glEnd();

    p = rySq - ( rxSq * ry ) + ( 0.25 * rxSq );
    while( px < py )
    {
        x++;
        px = px + 2 * rySq;
        if( p < 0 )
            p = p + rySq + px;
        else
        {
            y--;
            py = py - 2 * rxSq;
            p = p + rySq + px - py;
        }
        glBegin( GL_POINTS );

        glVertex2d( xc + x, yc + y );
        glVertex2d( xc + x, yc - y );
        glVertex2d( xc - x, yc - y );
        glVertex2d( xc - x, yc + y );
        glEnd();

    }

    p = rySq*( x + 0.5 )*( x + 0.5 ) + rxSq*( y - 1 )*( y - 1 ) - rxSq*rySq;
    while( y > 0 )
    {
        y--;
        py = py - 2 * rxSq;
        if( p > 0 )
            p = p + rxSq - py;
        else
        {
            x++;
            px = px + 2 * rySq;
            p = p + rxSq - py + px;
        }
        glBegin( GL_POINTS );

        glVertex2d( xc + x, yc + y );
        glVertex2d( xc + x, yc - y );
        glVertex2d( xc - x, yc - y );
        glVertex2d( xc - x, yc + y );
        glEnd();
        glFlush();

    }
}    //end_MIDPOINT_ELLIPSE

bool displayEllipse = false;
void View1Display()
{
    glClearColor( 0.3, 0.3, 0.3, 0.7 );
    glClear( GL_COLOR_BUFFER_BIT );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluOrtho2D( -500.0, 500.0, -500.0, 500.0 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    if( displayEllipse )
        Display_Mid_Ellipse();

    glFlush();
}

void Display()
{
    glClearColor( 0.0, 0.0, 0.0, 1.0 );
    glClear( GL_COLOR_BUFFER_BIT );

    glFlush();
}

GLuint window;
GLuint View1;
void keyFunc( unsigned char ch, int x, int y )
{
    if( ch == 32 )
    {
        displayEllipse = !displayEllipse;
        glutPostWindowRedisplay( View1 );
    }
}

int main( int argc, char *argv[] )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB );

    glutInitWindowSize( 750, 750 );
    glutInitWindowPosition( 0, 0 );

    window = glutCreateWindow( "Circle and ellipse" );
    glutDisplayFunc( Display );
    glutKeyboardFunc( keyFunc );

    View1 = glutCreateSubWindow( window, 20, 40, 340, 340 );
    glutDisplayFunc( View1Display );

    glutMainLoop();
    return 0;
}


text:
Q: How to tell whether a Mac Cocoa application has been launched normally or as a login item? Is there any way of telling whether a Cocoa application has been launched as a log item rather than by double clicking it?

A: The Chromium project has some code to do this. Follows the approach spelled out here, checking the parent process and the login item list.

A: As far i'm aware there is no proper way to check this, but there are some thoughts:
Best solution:
Create two different applications, for example TheApp and TheAppLauncher.
Add TheApp to the applications folder and TheAppLaucher to the startup items.
Simply launch TheApp with a specific flag when TheAppLauncher is launched.
I hope this is clear :)
Other 'ugly' option:
Check whether the application is actually listed in the login items:
https://github.com/carpeaqua/Shared-File-List-Example/
Make the application log the exact time it launched.
Then compare it with the last time the user logged-in.
The finger command provides this information (use NSTask).
Good change it's launched as log-in item when the difference is small.
But yes, this is not completely reliable :)

A: When an application is launched without a document to open or print, it receives an 'oapp' (a.k.a. kAEOpenApplication) Apple Event. That event may have a property data (keyAEPropData) parameter. For an ordinary launch, that parameter is absent or 0. For a launch from a login item, it's keyAELaunchedAsLogInItem. (When your app is launched to provide a service, it's keyAELaunchedAsServiceItem.)
https://developer.apple.com/legacy/library/documentation/Carbon/Reference/Apple_Event_Manager/index.html#//apple_ref/doc/constant_group/Launch_Apple_Event_Constants
You can check for this with the following code in your -applicationWill/DidFinishLaunching: method:
NSAppleEventDescriptor* event = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent];
if ([event eventID] == kAEOpenApplication &&
    [[event paramDescriptorForKeyword:keyAEPropData] enumCodeValue] == keyAELaunchedAsLogInItem)
{
    // you were launched as a login item
}

Swift 3:
let event = NSAppleEventManager.shared().currentAppleEvent
let launchedAsLogInItem =
    event?.eventID == kAEOpenApplication &&
    event?.paramDescriptor(forKeyword: keyAEPropData)?.enumCodeValue == keyAELaunchedAsLogInItem

A: Maybe you could start the application with an option if started as a login item. For example call it MyApp.app --startupItem when used as a startup item and call it without that option when it is launched regularly.
The command line options can be check the classic C way, as they are passed to the main function as arguments.

A: Set up the login item so that "Hide" is checked then whenever your app is launched (awakeFromNib or init) check if the app is hidden or not.

A: Depending on exactly what you're doing, NSApplicationLaunchIsDefaultLaunchKey may be useful here. This is a key included in the NSNotification sent to applicationDidFinishLaunching:.  From the documentation:

The value for this key is an NSNumber containing a Boolean value. The value is NO if the application was launched to open or print a file, to perform a Service action, if the application had saved state that will be restored, or if the application launch was in some other sense not a default launch. Otherwise its value will be YES.

In addition to the cases mentioned, it is also set to NO if the app is automatically launched on login. So if you're deciding whether to show some interface element, for example, this may be enough information to do what you're after.
Checking [[NSApplication sharedApplication] isHidden] may also be useful if you want to know whether the app was launched with the "hide" box checked.
Edit: On further testing, I'm not sure this is actually true. When the app is opened normally, NSApplicationLaunchIsDefaultLaunchKey is usually YES. When it's launched automatically, it seems to usually be NO, in the testing I've done so far. But neither is always true, so it seems this key may not be useful after all.


text:
Q: MongoDB query connection error failing silently due to no connection How do I handle a mongodb query going unanswered? In my current situation it was as stupid as failing to fire up my local database instance after rebooting my machine, but I could see this happening in the wild.
Ex:The user tries to login, the browser fires an ajax request to the server, the server does it's authentication thing and tries to find the user but... no database, so there is no response. The user stares at their browser in frustration.

A: If i understand correctly, then simply add Mongod as a service. That way if the server goes down it will restart automatically. For instance in Linux you would issue "sudo chkconfig mongod on". As to the Mongodb just going down first set up your Mongod.conf file with the right parameters for your OS and your requirements (sometimes not as simple as it sounds). Also have your server email you when a critical error happens.
Hope this helps.