text:
Q: WP7 - Using RX, Subscribe only triggering once but OnNext() always triggering? Ok im having another play with reactive extentions, specifically with wp7.
I'm looking at the GeoCoordinateWatcher positon changed event like so
var subject = new BehaviorSubject<GeoCoordinate>(GeoCoordinate.Unknown);
var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default) { MovementThreshold = 0 };

watcher.PositionChanged += (o, args) =>
{
   var newLocation = args.Position.Location;

   if ((DateTime.Now - args.Position.Timestamp.DateTime) < locationTimeout)
   {
        subject.OnNext(newLocation);
    }
};

I am subscribing like so
MyLocation.StartGettingLocations()
 .Subscribe(pos =>
 {
       // Do something with the position
       PlotLine.Locations.Add(pos);
       bingMap.SetView(pos, 15);
 });

The app runs but the problem is the code in side the Subscribe only happens once yet if I put a break point in the subject.OnNext(newLocation), I see its constantly getting triggered.
What am I doing wrong?
[EDIT]
Ok I can see what was wrong, the code (which is not mine im just learning from it), uses DistinctUntilChanged(). I am assuming, from briefly reading, that this stops the same value pumping out to the subscriber? so interms of what I was using it for, location tracking, if the phone was in the same position and the GeoCoordinate was unchanged then it would be pointless sending it to the subscriber so it just prevents it?

A: I suspect the question has been answered in the comments (ie remove DistinctUntilChanged if you want locations even though the user isn't moving). However, there was something bothering about this question - it's using Rx, but not particularly effectively.
First, there's a much simpler way to turn the events into observables (which in turns makes them simpler to work with):
var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default) { MovementThreshold = 0 };
var geo = Observable.FromEventPattern<GeoPositionChangedEventArgs<GeoCoordinate>>(
                               ev => watcher.PositionChanged += ev,
                               ev => watcher.PositionChanged -= ev)
                    .Select(ev => ev.EventArgs.Position);

Then, to get the changes, no need for that imperative bit of code. Just do this:
var changes = geo.Where(pos => (DateTime.Now - pos.Timestamp.DateTime) < locationTimeout)
                 .Select(pos => pos.Location)
                 .DistinctUntilChanged();

(You can remove the DistinctUntilChanged of course, that wasn't in your posted code).
Now you can work with changes directly:
changes.Subscribe(loc =>
{
   PlotLine.Locations.Add(pos);
   bingMap.SetView(pos, 15);
});

There's no need to manage a subject that is really just shadowing a set of events. Just turns the events into Observables. Then because you're using Observables all the way through, you have access to a number of combinators that will allow you to do a lot more than you currently are.


text:
Q: Simple java-wx webservice using javaee tutorial Im trying to build a simple webservice following this tutorial but unable to access the WSDL once I deploy the code in tomcat -
Here are the steps I followed -

*

*Create a Dynamic web project in Eclipse.

*Created a package and class..Here is the below code
package helloservice.endpoint;

import javax.jws.WebService;
import javax.jws.WebMethod;

@WebService
public class Hello {
   private String message = new String("Hello, ");

   public void Hello() { }

   @WebMethod
   public String sayHello(String name) {
      return message + name + ".";
   }
}

*Deployed the code in tomcat and ran it but unable to access the WSDL. I went to the tomcat manager and see the "helloservice" application.

**http://localhost:8080/helloservice/HelloService?wsdl**

From the document, what is HelloService after the helloservice. Is it the class name?
How can I debug it?

redpajama_set_name: RedPajamaStackExchange


text:
Q: JAX-B - Create @XmlElement for one resource method and not for other method from same class I'm new to JAX-RS and JAX-B and I having problems with the following situation:
I have an entity class and it's resource class.
My resource class has two methods. Both method "uses" the same entity class, but theres a field I need only in one method.
public class Item {
    ....
    @XmlElement(name="fieldName")
    public void getFieldName(){
        return fieldName;
    }
    ...
}

@Path("items")
public class ItemResource {
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public public Response methodA(@Context UriInfo uriInfo) {
        //this method will use fieldName
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public public Response methodB(@Context UriInfo uriInfo) {
        //this method will not use fieldName
    }
}

How can I solve this problem? Is there a way to "choose the context" I can use a field annotated with @XmlElement ?
I'm using jersey-media-json-jackson...


text:
Q: Python: Assert that all objects in a list have a specific attribute values I am working for a web-app using django-1.6 where there will be application(s) coming in and going through various stages of scrutiny. On satisfying criteria(s), they get approved and promoted to the next stage or get deferred. I was testing the approval transition. And landed up in situation where I need to assert if approvable application(s) have their status changed to pending for the next stage. So, this is how I do it right now:
self.assertEqual('stage2.pending', stage1_approved_mentor_applications[0].status)

what I am looking for is something like
self.assertEqual('stage2.pending', stage1_approved_mentor_applications.status)

which would assure that all the objects in the list stage1_approved_mentor_applications have their status as 'stage2.pending'. One way would be to pass it to a function taking a list and returning True on all status being 'stage2.pending' and False if otherwise. This function will be called in assertTrue. Wondering if there's already a workaround for this that would save me from reinventing the wheel.
Can anyone help me with that? Thanks in advance.

A: what about this:
for s in stage1_approved_mentor_applications:
   self.assertEqual('stage2.pending', s.status)

so you know what status is different

A: How about this?
self.assertFalse(
    any(obj.status != 'stage2.pending' for obj in stage1_approved_mentor_applications)
)

A: self.assertTrue(
    all([x is 'stage2.pending' for x in stage1_approved_mentor_applications]
))


text:
Q: Why are newline characters stored in Android SQLite database not shown in TextView? my App is reading insert sql, using BufferReader.readLine().
my sql is like this:
INSERT INTO TBL_EXAMPLE (COL_A, COL_B, COL_C) VALUES('1', '2', '- THIS IS EXAMPLE.\n- THIS IS EXAMPLE.');

and output that I want:
- THIS IS EXAMPLE.
- THIS IS EXAMPLE.

but, actual output is :
- THIS IS EXAMPLE.\n- THIS IS EXAMPLE.
:(
I don't know why new_line character("\n") is not work.
how can I do that? I should be very grateful to you if you might help me :) (Sorry for short English, because I'm foreigner :| )
here is my code:
InputStream is = ctx.getResources().openRawResource(R.raw.db);

    try{

        BufferedReader br = new BufferedReader(new InputStreamReader(is, "EUC_KR"));

        while(true){

            String sql = br.readLine();
            if(sql!=null){
                db.execSQL(sql); // INSERT INTO TBL_EXAMPLE (COL_A, COL_B, COL_C) VALUES('1', '2', '- THIS IS EXAMPLE.\n- THIS IS EXAMPLE.');

            } else{
                break;
            }

        }
        is.close();

A: Use Html.fromHtml to support new lines:
textView.setText(Html.fromHtml("- THIS IS EXAMPLE.<br/>- THIS IS EXAMPLE."));


text:
Q: performance is degraded with -m64 flag I wrote a simple filter program to see if performance improvement is there with -m64 compiler option over -m32.
Here is my whole code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#include<sys/time.h>
#define __STDC_FORMAT_MACROS 1
#include<inttypes.h>

#define tap_size 5
int luma_stride=640;
int luma_ht=480;
int croma_stride=320;
int croma_ht=240;

int filter[tap_size]={-3,2,3,2,-3};

struct timeval tv1, tv2,tv3;
uint64_t  ui1;
uint64_t total_time=0;

uint64_t GetTimeStamp();
void process_frame(unsigned char *ip_buffer, unsigned char * op_buffer, int ip_buf_size, int op_buf_size);

int main()
{

    int ip_buf_size;
    int op_buf_size;

    unsigned char * ip_buffer;
    unsigned char * op_buffer;
    unsigned char * temp;

    ip_buf_size=luma_stride*luma_ht + 2*croma_stride * croma_ht;
    op_buf_size=ip_buf_size; //

    ip_buffer = (unsigned char *)malloc(ip_buf_size*sizeof(char));
    op_buffer = (unsigned char *)malloc(ip_buf_size*sizeof(char));;
    temp=ip_buffer;
    for(int i=0;i<ip_buf_size;i++)
    {
        *temp=rand();
    }

    for(int i=0;i<100;i++)
    {
        ui1=GetTimeStamp();
        process_frame(ip_buffer, op_buffer, ip_buf_size, op_buf_size);//process
        total_time+=GetTimeStamp()-ui1;
    }
    free(ip_buffer);
    free(op_buffer);
    printf("\nTotal time=%" PRIu64 " us\n", total_time);
    return 0;
}

uint64_t GetTimeStamp()
{
    struct timeval tv;
    gettimeofday(&tv,NULL);
    return tv.tv_sec*(uint64_t)1000000+tv.tv_usec;
}

void process_frame(unsigned char *ip_buffer, unsigned char * op_buffer, int ip_buf_size, int op_buf_size)
{

    int i,j;
    unsigned char *ptr1,*ptr2;
    unsigned char *temp_buffer=(unsigned char *) malloc(op_buf_size*sizeof(unsigned char));

    ptr1=ip_buffer;
    //ptr2=temp_buffer;
    ptr2=op_buffer;

    //Vertical filter

    //Luma
    /*  for(j=0;j<tap_size/2;j++)
     {
     for(i=0;i<luma_stride;i++)
     {
     *ptr2++=*ptr1++;
     }
     } */

    memcpy(ptr2,ptr1,2*luma_stride*sizeof(unsigned char));
    ptr1=ip_buffer+2*luma_stride;
    ptr2=op_buffer+2*luma_stride;

    for(i=0;i<luma_ht-tap_size+1;i++)
    {

        for(j=0;j<luma_stride;j++)
        {
            int k;
            long int temp=0;
            for(k=0;k<tap_size;k++)
            {
                temp+=filter[k]**(ptr1+(k-tap_size/2)*luma_stride);
            }
            //temp=temp>>4;
            if(temp>255) temp =255;
            else if(temp<0) temp=0;
            *ptr2=temp;
            ++ptr1;
            ++ptr2;
        }

    }

    memcpy(ptr2,ptr1,2*luma_stride*sizeof(unsigned char));
    ptr1=ptr1+2*luma_stride;
    ptr2=ptr2+2*luma_stride;

    //Copy croma values as it is!
    for(i=luma_ht*luma_stride;i<ip_buf_size;i++)
    {
        op_buffer[i]=ip_buffer[i];
    }
}

I compiled it with these two options
g++ -O3 program.c -o filter64 -m64

and
g++ -O3 program.c -o filter32 -m32

Now,
outputs of ./filter32 is
Total time=106807 us

and that of ./filter64 is
Total time=140699 us

My question is shouldn't it be other way ? i.e time taken by filter64 should be less than that of filter32 as with 64 bit architecture we have more registers? How can I achieve that ? or is there any compiler option which takes care of that ?
Please help.
I am using ubuntu on intel 64 bit machine.

A: There are various trade-offs when you switch from 32 bit to 64 bit. On the down-side all pointers become twice the size, and it can take a longer instruction sequence to load an immediate address into a register. Unless your application is register-starved or needs > 4 GB address space then you might want to keep it 32 bit.
Also note that your timing method is somewhat suspect - you may just be seeing the effect of page faults etc - you should put your test code in a loop, with memory allocation outside the loop and the processing code inside the loop. Ignore the first iteration for timing purposes. That way all memory is wired and the caches are warmed before you start timing.
One further problem: you seem to have a memory leak in process_frame, which as well as being a bug may also may make the timing unreliable.

A: Why are you using a C++ compiler to compile C? It makes your C code worse, since you must do horrible things like having to cast the return value of malloc() and such.
Also, are you certain that your program's performance is limited by available registers? You need to profile your program to figure out exactly where time is spent, to figure out if/how moving to 64-bit can make it faster.
It's not as simple as "all code is faster when built for for 64-bit, because there are more registers".


text:
Q: Exporting cordova jar for Android I have been trying to follow the direction in here to get the jar.
https://cordova.apache.org/docs/en/latest/guide/platforms/android/webview.html
So far here is the error I have been getting.
Buildfile: /Users/Thays/Source/corAPK/node_modules/cordova-android/framework/build.xml
BUILD FAILED
/Users/Thays/Source/corAPK/node_modules/cordova-android/framework/build.xml:42: You need to create the file 'local.properties' by running 'android update project -p .' here.
Move on and tried to run the required command more errors

The "android" command is deprecated.
For manual SDK, AVD, and project management, please use Android Studio.
For command-line tools, use tools/bin/sdkmanager and tools/bin/avdmanager

Invalid or unsupported command "update project -p ."
I move on and open it in android studio open up the file there let it do the work.
Ran ant again.
got
BUILD FAILED
/Users/Thays/Source/corAPK/node_modules/cordova-android/framework/build.xml:124: Cannot find /Users/thays/Library/Android/sdk/tools/ant/build.xml imported from /Users/Thays/Source/corAPK/node_modules/cordova-android/framework/build.xml
Any help would great.


text:
Q: Can I connect my Mid 2011 Mac to a second monitor? How can I connect my mid 2011 iMac to a second monitor to extend my screen? The monitor is an HP L1950. The ports my mac has can be seen here:

A: Your iMac has a Thunderbolt 2 connector which also acts as a Mini DisplayPort.
Since your Monitor supports (15-Pin D-Sub) VGA or DVI-D you either need a Mini-DisplayPort to VGA or to DVI-D cable. I would recommend getting a DVI-D (e.g from Amazon, your local store might have one of the mentioned options as well), since it is the newer and slightly better standard, though VGA is (for old) equipment more common.
In general though, this is old Hardware and HDMI is more or less standard now.


text:
Q: MPI buffer communication in C int SIZE, bsize;
SIZE = 6;

/*the space needed to send data with the number of SIZE and type of MPI_DOUBLE*/
MPI_Pack_size( SIZE, MPI_DOUBLE, MPI_COMM_WORLD, &bsize );

/*the space needed for MPI_Bsend*/
tmpbuffer = (double *) malloc( bsize + 2*MPI_BSEND_OVERHEAD );

MPI_Buffer_attach( tmpbuffer, bsize + MPI_BSEND_OVERHEAD );

My question is:
(1)the memory assigned for tmpbuffer is bsize + 2*MPI_BSEND_OVERHEAD, when it comes to MPI_Buffer_attach, why its size changes to bsize + MPI_BSEND_OVERHEAD?
(2)what does 'MPI_BSEND_OVERHEAD' mean? And why does it times by 2?


text:
Q: How to retrieve references from group Checkbox name arrays using JS or jQuery I have a hard JS/jQuery riddle ! Hard because I couldn't find it on Google nor here, neither now, nor months ago when I was looking for it previously.
A large framework is using checkboxes in a table:

    <input name="blnChecked[70_20]" type="checkbox" value="1" id="some_unusable_gobbledy_gook" />
    	...

    <input name="blnChecked[71_20]" type="checkbox" value="1" id="some_more_unusable_gobbledy_gook" />
    	...

    <input name="blnChecked[70_25]" type="checkbox" value="1" id="some_further_unusable_gobbledy_gook" />
    	...

I now need to collect all checkbox name references into an array: 70_20, 71_20 and 70_25 in the above example. Then join them up, and submit them as a URL parameter to a different page (although this joining is not essential to my question).
Question: Using JS/jQuery on the same page, how do I get these references from the name strings in these (checked) checkboxes in an array ?
I prefer not to use regexes (a bit messy, or 'overkill' for such a seeming trivial matter imho), although such a solution is not off my table.
(If someone asks why the table is structured as such: This is not my doing. But I can see that when such a form, in which this table is submitted to a PHP page, the PHP stores all such checkboxes into a single array, which is very nice, and I wanted to achieve a similar effect with JS/jQuery.)

A: A way to create on client side the array is based on using:

*

*.map()

*string .replace()

$('#btn').on('click', function(e) {
    var retVal = $('table.ListTable :checkbox[name^="blnChecked["]:checked').map(function(idx, ele) {
        //
        // if the name value has always the same format...
        //
        return ele.name.replace('blnChecked[', '').replace(']', '');
        //
        // or....
        //
        // return ele.name.split('[').pop().replace(']', '');
        // return ele.name.substr(11, 5);
        //return ele.name.replace(/blnChecked\[(.*?)\]/g, '$1')
    }).get();
    var param = $.param({'param': retVal.join(',')});
    console.log('Array: ' + retVal);
    console.log('URL param: ' + param);
})

        <input name="blnChecked[7125_2355]" type="checkbox" value="1" id="some_unusable_gobbledy_gook" />

        <input name="blnChecked[71_20]" type="checkbox" value="1" id="some_more_unusable_gobbledy_gook" />

        <input name="blnChecked[70_25]" type="checkbox" value="1" id="some_further_unusable_gobbledy_gook" />

<button type="button" id="btn">Click Me</button>


text:
Q: How to catch exceptions of copytree in python The documentation of shutil.copytree states:

If exception(s) occur, an Error is raised with a list of reasons.

And the link refers to:

exception shutil.Error
This exception collects exceptions that are raised during a multi-file operation. For copytree(), the exception argument is a list of 3-tuples (srcname, dstname, exception).

What is this shutil.Error exception? I tried to catch this type of exception:
try:
  shutil.copytree(source, dest) # this throws a FileExistsError for example
except shutil.Error:
    # error handling

But this kind of error wasn't raised..

A: The documentation first states

dirs_exist_ok dictates whether to raise an exception in case dst or any missing parent directory already exists.

Unless you specify dirs_exist_ok=True a FileExistsError is raised. You're right that later on the documentation states that (presumably in other cases) a shutil.Error may be raised.
In the end I think it's a matter of interpretation, but if the code raises a FileExistsError you should catch a FileExistsError:
try:
  shutil.copytree(source, dest)
except FileExistsError:
    # error handling

>>> shutil.copytree("ws", "workshop")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/robin/.pyenv/versions/3.8.6/lib/python3.8/shutil.py", line 554, in copytree
    return _copytree(entries=entries, src=src, dst=dst, symlinks=symlinks,
  File "/home/robin/.pyenv/versions/3.8.6/lib/python3.8/shutil.py", line 455, in _copytree
    os.makedirs(dst, exist_ok=dirs_exist_ok)
  File "/home/robin/.pyenv/versions/3.8.6/lib/python3.8/os.py", line 223, in makedirs
    mkdir(name, mode)
FileExistsError: [Errno 17] File exists: 'workshop'
>>> shutil.copytree("ws", "workshop", dirs_exist_ok=True)
'workshop'

The part of shutil.Error that you quoted could be interpreted as:

This exception collects exceptions that are raised during a multi-file operation. For copytree(), [when a shutil.Error is raised] the exception argument is a list of 3-tuples (srcname, dstname, exception).

It does not mean that all exceptions during copytree() will be of type shutil.Error.


text:
Q: Storing summed values I'm trying to create a database to store values for Profit & Loss statements and I'm wondering what the best way to structure this would be. Specifically, amounts that are are equated from other numbers such as: operating income = gross income - operating expenses, and also operating expenses = wages + rent.
Should there be a field for each value, even if it is a result of an equation, or should I only keep the non-equated values, and equate the others when querying or pulling the data into a report?
In the former I would have to more fields and there's potential for the summed numbers to be entered incorrectly, the latter seems like it would have a complex structure, and would need complex queries. Keep in mind that the P&L statement I'm actually working with has many more accounts and summed accounts.
Is there a best practice for this, or place to get more info on this? I really appreciate the help

A: The correct answer is:  it depends.  Here are factors you should take into account:

*

*is there any possibility of the figures changing?  Accounts are sometimes restated.  If you had a summary table you would have to change that as well if there was a restatement.

*you say you are trying to create a database.  Does this mean you already have an OLTP (online transaction processing) database and the new one would a data warehouse?  If so then you need to research data warehouse schemas like the snowflake design and, more importantly, decide the key values you are tracking.  One way of describing a data warehouse is one huge summary table.  Reporting and analysis are often easier with summarized data.

*or maybe you just want to add some tables to summarize the data and keep it in the same database as the source material.  If so there are many other tools like views, materialized views that could be used that are dynamic.

*there is a trade off between summarizing data.  Once you take a snapshot you have to make sure it stays in sync with the real data.  Or you can build a structure on top of the original data with views.

*if the amount of data is small or can be broken into smaller parts you could fill a summary table with a procedure that marks each entry when it was created.  Then if fiscal 2011 is restated due to whatever you just delete all fiscal 2011 entries from the summary table and rebuild with your procedure.  This may or may not pass auditor standards depending on your location, your industry and your companies practices.

A:
Is there a best practice for this?

This is a classic time vs space trade-off.
You either calculate the values up front, storing them permanently, taking up extra space in your database, but are able to retrieve the values more quickly. Or you only store base values in the database, and have to perform calculations on the values whenever you need them, which may take more time, but requires less space.
I'm not sure that there's a best practice for this, it all depends on how your company operates.
FWIW, we do the latter.
We have a database that stores the base values.
We also have a reporting database that pulls the base values in and performs calculations on them to produce reports.
The values are held in a table temporarily whilst the report is being produced.
When the next report is produced, the table is wiped and the next set of values is calculated. Which can take time depending on the amount of data being processed i.e. YTD etc.
Previously calculated figures can change sometimes due to rate fluctuations and back valuations etc, so the business teams prefer to know that the values are recalculated each time.

A: Since your question has been addressed, I want to bring up the benefits of clustered index views when dealing with these design issues.  We have a system where we collect billing information every 5 minutes for over 20,000 customers.  At the end of the month the reports have to aggregate all this data to run billing reports.  With a clustered index view you can aggregate the data up ahead saving SQL Server the need to do it every time a query is ran.  You might want to look into this.  It reduces hours to seconds if done properly.
I know this wasn't directly what you asked for, but I'm really excited about the time these views save and it fell in line with what you were asking.


text:
Q: Rails error finding actionmailer template despite email sending correctly I have a rails app running on passenger with a mailer. I have it so the page following the action shows the email content but I get this error:
Missing template rfis/mail, application/mail with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :slim, :jbuilder]}. Searched in: * "/var/www/rqm3/app/views" * "/usr/local/rvm/gems/ruby-2.1.5/gems/devise-3.5.1/app/views" * "/usr/local/rvm/gems/ruby-2.1.5/gems/twitter-bootstrap-rails-3.2.0/app/views"

despite this, the email does correctly load the template when being sent.  It's only showing it in a view that causes issues.
rfis_controller.rb:
  def mail
    @mail_message = RfiMailer.send_rfi(current_user, @rfi).deliver
  end

rfi_mailer.rb:
class RfiMailer < ApplicationMailer
    default from:"testemail@mail.com"
    def send_rfi(user, rfi)

        mail(to:"other@test.com")
    end
end

send_rfi.html.erb:
test

A: Issue is due to you are not redirecting anything inside your method "mail" define inside controller
 def mail
   @mail_message = RfiMailer.send_rfi(current_user, @rfi).deliver
   redirect_to @user, notice: "Message sent successfully ."
 end

you can also define render nothing


text:
Q: Is this a good way to lock a loop on 60 loops per second? I have a game with Bullet Physics as the physics engine, the game is online multiplayer so I though to try the Source Engine approach to deal with physics sync over the net. So in the client I use GLFW so the fps limit is working there by default. (At least I think it's because GLFW). But in the server side there is no graphics libraries so I need to "lock" the loop which simulating the world and stepping the physics engine to 60 "ticks" per second.
Is this the right way to lock a loop to run 60 times a second? (A.K.A 60 "fps").
void World::Run()
{
    m_IsRunning = true;

    long limit = (1 / 60.0f) * 1000;
    long previous = milliseconds_now();

    while (m_IsRunning)
    {
        long start = milliseconds_now();
        long deltaTime = start - previous;
        previous = start;

        std::cout << m_Objects[0]->GetObjectState().position[1] << std::endl;

        m_DynamicsWorld->stepSimulation(1 / 60.0f, 10);

        long end = milliseconds_now();
        long dt = end - start;

        if (dt < limit)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(limit - dt));
        }
    }
}

Is it ok to use std::thread for this task?
Is this way is efficient enough?
Will the physics simulation will be steped 60 times a second?
P.S
The milliseconds_now() looks like this:
long long milliseconds_now()
{
    static LARGE_INTEGER s_frequency;
    static BOOL s_use_qpc = QueryPerformanceFrequency(&s_frequency);
    if (s_use_qpc) {
        LARGE_INTEGER now;
        QueryPerformanceCounter(&now);
        return (1000LL * now.QuadPart) / s_frequency.QuadPart;
    }
    else {
        return GetTickCount();
    }
}

Taken from: https://gamedev.stackexchange.com/questions/26759/best-way-to-get-elapsed-time-in-miliseconds-in-windows

A: If you want to limit the rendering to a maximum FPS of 60, it is very simple :
Each frame, just check if the game is running too fast, if so just wait, for example:
while ( timeLimitedLoop )
{
    float framedelta = ( timeNow - timeLast )
    timeLast = timeNow;

    for each ( ObjectOrCalculation myObjectOrCalculation in allItemsToProcess )
    {
        myObjectOrCalculation->processThisIn60thOfSecond(framedelta);
    }

    render(); // if display needed
}

Please note that if vertical sync is enabled, rendering will already be limited to the frequency of your vertical refresh, perhaps 50 or 60 Hz).
If, however, you wish the logic locked at 60fps, that's different matter: you will have to segregate your display and logic code in such a way that the logic runs at a maximum of 60 fps, and modify the code so that you can have a fixed time-interval loop and a variable time-interval loop (as above).  Good sources to look at are "fixed timestep" and "variable timestep" ( Link 1 Link 2 and the old trusty Google search).
Note on your code:
Because you are using a sleep for the whole duration of the 1/60th of a second - already elapsed time you can miss the correct timing easily, change the sleep to a loop running as follows:
instead of
if (dt < limit)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(limit - dt));
        }

change to
while(dt < limit)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(limit - (dt/10.0)));
            // or 100.0 or whatever fine-grained step you desire
        }

Hope this helps, however let me know if you need more info:)


text:
Q: Simulate a label for command similar to GOTO I have read that in JavaScript there is no GOTO command or label tags as in other programming languages.
For this, some have used while or for loops and others have used switch.
In my particular case I want to simulate a label called for example A: and then simulate a GOTO to that label.
I share the code outline so you can see what I mean.
I don't want to go to the this.refreshHistoric function but to the XMLHttpRequest
this.refreshHistoric = function (info, n) {

        //Here label A:

        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState === 4) {

                if (this.status === 200) {
                //do some things
                } else if (this.status === 404) {
                     //define some variables and GOTO label A:

                }

            }
        }
        xhttp.open('GET', proxy_URL + itunes_api + urlencode(artistHist) + ' ' + urlencode(songHist) + '&media=music&limit=1.', true);
        xhttp.send();
}

Actually I want to do something more complex without having to create a new function.
If a 404 error occurs what I want to do is send GET again without proxy_URL variable
In other words, the new GET would be like this:
xhttp.open('GET', itunes_api + urlencode(artistHist) + ' ' + urlencode(songHist) + '&media=music&limit=1.', true);

I can do this perfectly by creating a new function, but to save code I want to see if it is possible to redefine GET and in passing I learn to simulate a GOTO - Label in JavaScript. :)

A: You need to think in terms of asynchronous code, where these functions run at different times, and not in terms of linear, sequential code like you might be used to.
That function executes at a distant point in the future and the surrounding scope is long gone save for what ends up captured by the various closure(s) involved.
The general approach to have a "retry" in code like this is to define a function you can call again:
this.refreshHistoric = (info, n) => {
  const makeRequest = () => {
    let xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function () {
      if (this.readyState === 4) {
        switch (this.status) {
          case 200:
            //do some things
            break;
          case 404:
            // Define some variables...

            // Schedule a retry a moment later to avoid flooding the service
            setInterval(makeRequest, 1000);
            break;
        }
      }
    }

    xhttp.open(`GET ${proxy_URL}${itunes_api}${urlencode(artistHist)}  ${urlencode(songHist)}&media=music&limit=1.`, true);
    xhttp.send();
  }

  makeRequest();
}

Note that I've cleaned this up to use template strings, avoiding a lot of messy concatenation, and to use the new arrow-style function definition, which results i reduced clutter.


text:
Q: Merge of sorted lists with sized types Suppose we have a datatype of sorted lists, with proof-irrelevant sorting witnesses. We'll use Agda's experimental sized types feature, so that we can hopefully get some recursive functions over the datatype to pass Agda's termination checker.
{-# OPTIONS --sized-types #-}

open import Relation.Binary
open import Relation.Binary.PropositionalEquality as P

module ListMerge
   { ℓ}
   (A : Set )
   {_<_ : Rel A ℓ}
   (isStrictTotalOrder : IsStrictTotalOrder _≡_ _<_) where

   open import Level
   open import Size

   data SortedList (l u : A) : {ι : _} → Set ( ⊔ ℓ) where
      [] : {ι : _} → .(l < u) → SortedList l u {↑ ι}
      _∷[_]_ : {ι : _} (x : A) → .(l < x) → (xs : SortedList x u {ι}) →
               SortedList l u {↑ ι}

Now, a classic function one would like to define over such a data structure is merge, which takes two sorted lists, and outputs a sorted list containing exactly the elements of the input lists.
   open IsStrictTotalOrder isStrictTotalOrder

   merge : ∀ {l u} → SortedList l u → SortedList l u → SortedList l u
   merge xs ([] _) = xs
   merge ([] _) ys = ys
   merge (x ∷[ l<x ] xs) (y ∷[ l<y ] ys) with compare x y
   ... | tri< _ _ _ = x ∷[ l<x ] (merge xs (y ∷[ _ ] ys))
   merge (x ∷[ l<x ] xs) (.x ∷[ _ ] ys) | tri≈ _ P.refl _ =
      x ∷[ l<x ] (merge xs ys)
   ... | tri> _ _ _ = y ∷[ l<y ] (merge (x ∷[ _ ] xs) ys)

This function seems innocuous enough, except that it can be tricky to convince Agda that it's total. Indeed, without any explicit size indices, the function fails to termination-check. One option is to split the function into two mutually recursive definitions. This works, but adds a certain amount of redundancy to both the definition and associated proofs.
But equally, I'm not sure whether it is even possible to give size indices explicitly so that merge has signature that Agda will accept. These slides discuss mergesort explicitly; the signature given there suggests that the following should work:
   merge′ : ∀ {l u} → {ι : _} → SortedList l u {ι} →
                      {ι′ : _} → SortedList l u {ι′} → SortedList l u
   merge′ xs ([] _) = xs
   merge′ ([] _) ys = ys
   merge′ (x ∷[ l<x ] xs) (y ∷[ l<y ] ys) with compare x y
   ... | tri< _ _ _ = x ∷[ l<x ] (merge′ xs (y ∷[ _ ] ys))
   merge′ (x ∷[ l<x ] xs) (.x ∷[ _ ] ys) | tri≈ _ P.refl _ =
      x ∷[ l<x ] (merge′ xs ys)
   ... | tri> _ _ _ = y ∷[ l<y ] (merge' (x ∷[ _ ] xs) ys)

Here what we're doing is allowing the inputs to have arbitrary (and different) sizes, and specifying that the output has size ∞.
Unfortunately, with this signature, Agda complains that .ι != ∞ of type Size, when checking the body xs of the first clause of the definition. I don't claim to understand sized types very well, but I was under the impression that any size ι would unify with ∞. Perhaps the semantics of sized types have changed since those slides were written.
So, is my scenario a use-case for which sized type were intended? If so, how should I should use them? If sized types aren't appropriate here, why does the first version of merge above not termination-check, given that the following does:
open import Data.Nat
open import Data.List
open import Relation.Nullary

merge : List ℕ → List ℕ → List ℕ
merge (x ∷ xs) (y ∷ ys) with x ≤? y
... | yes p = x ∷ merge xs (y ∷ ys)
... | _     = y ∷ merge (x ∷ xs) ys
merge xs ys = xs ++ ys

A: Interestingly enough, your first version is actually correct. I mentioned that Agda enables few extra rules considering Size, one of them being ↑ ∞ ≡ ∞. By the way, you can confirm it via:
↑inf : ↑ ∞ ≡ ∞
↑inf = refl

Well, this led me to investigate what the other rules are. I found the rest of them inside Andreas Abel's slides on sized types (can be found here):

*

*↑ ∞ ≡ ∞

*i ≤ ↑ i ≤ ∞

*T {i} <: T {↑ i} <: T {∞}
The <: relation is the subtyping relation, which you might know from object oriented languages. There's also a rule associated with this relation, the subsumption rule:
Γ ⊢ x : A   Γ ⊢ A <: B
────────────────────── (sub)
      Γ ⊢ x : B

So, if you have a value x of type A and you know that A is a subtype of B, you can treat x as being of type B as well. This seemed strange, because following the subtyping rule for sized types, you should be able to treat a value of type SortedList l u {ι} as SortedList l u.
So I did bit of a digging and found this bug report. And indeed, the problem is just that Agda doesn't correctly recognize the size and the rule doesn't fire. All I needed to do was to rewrite the definition of SortedList to:
data SortedList (l u : A) : {ι : Size} → Set ( ⊔ ℓ) where
  -- ...

And that's it!

As an addendum, here's the code I used for testing:
data ℕ : {ι : _} → Set where         -- does not work
-- data ℕ : {ι : Size} → Set where   -- works
  zero : ∀ {ι} →         ℕ {↑ ι}
  suc  : ∀ {ι} → ℕ {ι} → ℕ {↑ ι}

test : ∀ {ι} → ℕ {ι} → ℕ
test n = n


text:
Q: Wordpress - How do I check if a user is logged in? I want to show unpublished posts for some reasons for not logged in users on some parameters.
Can I configure this functionality from WP admin panel or if not, where can I change this logic in code?

A: Use the built in function is_user_logged_in() for that:
<?php
if ( is_user_logged_in() ) {
    //show the post
} else {
   //continue as normal
}
?>


text:
Q: Searching the element using predicate condition How could I find a framework element in VisualTree by a predicate?
Something like that :
public static FrameworkElement FindChild(FrameworkElement root, Predicate<> predicate)
{
   ...
}

I'm goint to use it something like that:
Button btn = FindChild(MainForm, element => element is Button);

Thanks for help in advance!

A: So the real question then is how to iterate throug all the children of the given "root" element.
Because then you'll be able to call your predicate for that element and choose those you want.
So I suppose you should distinguish here two different workflows - one - when the element is Panel, you should first pass it in, and then iterate over it's Children property and pass in every of those (both recursion and non-recursion will work, but you should go deeper into tree, and come back through levels in both cases). And in case of non panel element, just pass in that one to the predicate.
Also you should think about the elements, which have "Content" property (I suppose this is defined in some base type, which I don't remember which one is), so check for the content element the same way. And that's all.
Regards,
Artak

A: You may use LINQ to find out the controls of particular type, maybe like this:
List<Button> btns = Controls.OfType<Button>().ToList();

A: Answers to this SO question describes many ways to look for controls in visual tree.
The predicate version is given there as link to this.


text:
Q: Que falhas de segurança foram encontradas no OAuth 2.0? Ontém li esse texto falando que foram encontradas falhas graves de segurança no OAuth. O teor do texto, em particular, faz parecer que não da pra usar o OAuth nem pensar. O problema com isso, é que estou desenvolvendo um projeto que o único modelo de autenticação e autorização plausível era o fornecido pelo OAuth.
Dessa forma, existem realmente falhas tão graves no OAuth como o texto afirma? Especificamente, quais são essas falhas que o texto se refere? Existe alguma forma de proteger contra elas?

A: A falha não existe no protocolo mas sim na implementação de muitos servidores de OAuth.
O que se passa é que o protocolo OAuth redireciona o browser do usuário para a página de autorização do servidor, por exemplo o Facebook. Aí é passado um URL de retorno.
O Facebook pede permissão ao usuário para o aplicativo poder acessar a API do Facebook em nome do usuário. Depois que o usuário autoriza, o Facebook redirectiona para o URL de retorno.
Para evitar abusos do usuário ser redirecionado para um site não autorizado, o Facebook verifica se o URL de retorno é do domínio configurado para aquele aplicativo.
No entanto, existem situações de abuso que indicam como URL de retorno um de uma página que redireciona para outra que não é o do domínio tinha autorizado configurado, conseguindo assim burlar a verificação.
Quem tem de corrigir o problem é principalmente o servidor de OAuth, por exemplo Facebook, pois em alguns modos de uso do protocolo já retorna o token de autorização direto para a página de retorno sem uma devida verificação.
No entanto, se você tem um aplicativo que usa OAuth para acessar a API de outro site em nome de seus usuários, pode ser que alguém abuse do seu aplicativo para acessar contas do usuários no servidor de OAuth como se fosse o seu aplicativo.
Para evitar esse problema, evite ter páginas no seu site que redirecionem para sites arbitrários definidos como parâmetro no URL da página que redireciona.
O problema é mais complicado, mas esta é a versão simplista que acredito já dá para entender que precauções deve ter.


text:
Q: Anaconda environment as an folder I want to have a special environment for a customer of a company. Therefore
I have some kind of requirements.txt file, in which the costumer can install the environment with an .bat file like:
conda create -env -name -req.txt ...
My question is if its also possible to drop the environment I use as a folder inside the software. I mean, can his Anaconda detect the environment inside the folder then or can he even ran it without having Anaconda on his computer, as the python kernel seems to be in any environment folder?
Thank you and best regards!


text:
Q: How do I scroll the iPhone UIPickerView from the last item to the first and continue forever? I want my UIPickerView to rotate to the beginning of the list when it is scrolled past the bottom. How do I do this? Basically, I want the functionality of the UIDatePicker when it scrolls the hours/minutes/seconds continuously.
I'm assuming I could just return an extremely large number from the numberOfComponentsInPickerView and then the actual titleForRow with a modulus of the number, but I think there must be a better way. Plus, I'm not sure how it is handled when the wheel starts since I can't return a negative number and it doesn't normally scroll backwards.
Any thoughts on how to do this?

A: Maybe this idea would work - just keep the user in the middle of the wheel so it has the sensation of staying on the same wheel.


text:
Q: Why I could not serialize a tuple in C#?
Possible Duplicate:
Why XML-Serializable class need a parameterless constructor

I'm trying to serialize a tuple in my code:
List<List<Tuple<String, CodeExtractor.StatementNode>>> results = null;
results = extractor.ExtractSourceCode(sourceCode);
FileStream fs = new FileStream(@"C:\Projects\Test\ast.xml", FileMode.Create);

XmlSerializer formatter = new XmlSerializer(
    typeof(List<List<Tuple<String, CodeExtractor.StatementNode>>>));

formatter.Serialize(fs, results);

fs.Close();

but it was failed and catch the exception like this:

System.Tuple`2[System.String,CodeExtractor.StatementNode] cannot be serialized because it does not have a parameterless constructor.

and I'm do sure the CodeExtractor.StatementNode could be serialized.

A: For XmlSerializer to be able to do its job it needs a default contructor. That is a constructor that takes no arguments. All the Tuple<...> classes have a single constructor and that constructor takes a number of arguments. One for each value in the tuple. So in your case the sole constructor is
Tuple(T1 value1, T2 value2)

The serializer is looking for a constructor with no arguments and because it can't find it, you get the exception.
you could create a mutable class, that could be substituted for tuples for the purpose of serialization
class MyTuple<T1, T2>
{
    MyTuple() { }

    public T1 Item1 { get; set; }
    public T2 Item2 { get; set; }

    public static implicit operator MyTuple<T1, T2>(Tuple<T1, T2> t)
    {
         return new MyTuple<T1, T2>(){
                      Item1 = t.Item1,
                      Item2 = t.Item2
                    };
    }

    public static implicit operator Tuple<T1, T2>(MyTuple<T1, T2> t)
    {
        return Tuple.Create(t.Item1, t.Item2);
    }
}

You could then use it the following way
XmlSerializer formatter = new XmlSerializer(
    typeof(List<List<MyTuple<String, CodeExtractor.StatementNode>>>));

formatter.Serialize(fs, results.SelectMany(
                              lst => lst.Select(
                                        t => (MyTuple)t
                                     ).ToList()
                              ).ToList());

A: As the exception tells you: The Tuple<T1, T2> has NO parameterless constructor which is needed by the serializer.


text:
Q: Mysql Join - Filter results based on two max values I am having the following data set:
+----+------------+------+-------+----------+
| id |    date    | week | time  |  price   |
+----+------------+------+-------+----------+
|  1 | 2015-05-01 |   24 | 13:25 | 1.251325 |
|  2 | 2015-05-01 |   24 | 14:25 | 1.251256 |
|  3 | 2015-05-02 |   24 | 15:25 | 1.251715 |
|  4 | 2015-05-02 |   24 | 16:25 | 1.251588 |
|  5 | 2015-05-10 |   25 | 17:25 | 1.251347 |
+----+------------+------+-------+----------+

I used the following code to get the latest price at the end of each day, which delivers perfect results:
SELECT t.id, t.date, t.time, t.balance
FROM db1 t JOIN
(SELECT tt.date, MAX(tt.time) as 'maxtime'
FROM db1 tt
GROUP BY tt.date
) m
ON m.maxtime = t.time AND t.date = m.date;

However, now I would also like to have a query delivering the latest price of each week. Hence, I would need to look for the latest date within each week and then for the maximum time. I tried something like this, but this is clearly not the right syntax:
SELECT t.id, t.date, t.time, t.balance
FROM db1 t JOIN
(SELECT tt.date, MAX(tt.time) as 'maxtime'
FROM db1 tt
GROUP BY tt.date
AND
SELECT tt.week, MAX(tt.date) as 'maxdate'
FROM db1 tt
GROUP BY tt.week
) m
ON m.maxtime = t.time AND m.week = t.week AND m.maxdate = t.date;

The question is how I can link the two conditions based on two different "Group by". The result I am looking for should look like that:
+----+------------+------+-------+----------+
| id |    date    | week | time  |  price   |
+----+------------+------+-------+----------+
|  4 | 2015-05-02 |   24 | 16:25 | 1.251588 |
|  5 | 2015-05-10 |   25 | 17:25 | 1.251347 |
+----+------------+------+-------+----------+

Thank you very much for your help in advance.

A: It is strange to see that you have separate columns for date and time, but maybe this is necessary to store repeated times (11:00 daily) or dates without times. Otherwise you should use a datetime instead.
What you are looking for is the latest datetime or timestamp in a week. You get this when you combine date and time.
SELECT t.id, t.date, t.time, t.balance
FROM db1 t JOIN
(SELECT tt.week, MAX(timestamp(tt.date,tt.time)) as 'maxtime'
FROM db1 tt
GROUP BY tt.week
) m
ON m.maxtime = timestamp(t.date,t.time) AND t.week = m.week;

A: What I recommend doing, if it's not an option to combine your date and time objects into one DATETIME column, is first research the TIMESTAMP() function which can be used to convert both columns into one datetime object like this:
SELECT TIMESTAMP(dateColumn, timeColumn) AS fullDate
FROM myTable;

Once you have that, you can write a query to get the max DateTime for each week, and join back to your original table to get all values like this:
SELECT m.*
FROM myTable m
JOIN(
  SELECT week, MAX(TIMESTAMP(dateColumn, timeColumn)) AS latestDate
  FROM myTable
  GROUP BY week) mt ON mt.week = m.week AND mt.latestDate = TIMESTAMP(m.datecolumn, m.timecolumn);

Here is an SQL Fiddle example.

A: You could concatenate the date and time into one value and apply max on that like this:
SELECT t.id, t.date, t.week, t.time, t.price
FROM db1 t
JOIN (
  SELECT tt.week, MAX(concat(tt.date, ' ', tt.time)) as 'maxtime'
  FROM db1 tt
  GROUP BY tt.week
) m ON m.maxtime = concat(t.date, ' ', t.time) and t.week = m.week;

Sample SQL Fiddle


text:
Q: Is it possible to use an assert or a raise in a conditional expression? I want to use a conditional expression as follows:
young_animal = 'puppy' if animal == 'dog' else ('kitten' if animal == 'cat' else (assert False))

i.e., I only expect animal to be dog or cat, but I want to assert this in my code.
This is not valid python because assert is a statement, and not an expression. Similarly, raise is also a statement. What would be the best way to do this? I could of course do something as follows:
assert animal in ['dog', 'cat']
young_animal = 'puppy' if animal == 'dog' else 'kitten'

But this seems both less idiomatic, and also less safe (e.g., the lines might get separated in a refactor).


text:
Q: How to access value from a QML combo box which is fetching values from table/model? I have a combobox which gets value from a table. I get the combobox object using:
QObject * object=engine->rootObjects().at(0)->findChild<QObject* >("comboobjectname");

Now, how do I set a value from the combobox list and set it on GUI using C++?

A: I always recommend the same: update your GUI using the model if you have one.
I don't know your whole project, but if you have the model in C++, you should have a class with methods to add, remove and get data.
In this example, I'm going to show you a very simple model, Animal, with two values: type and size.
animal.h
#ifndef ANIMAL_H
#define ANIMAL_H

#include <QString>

class Animal
{
public:
    Animal(const QString &type, const QString &size);

    QString type() const;
    QString size() const;

private:
    QString m_type;
    QString m_size;
};

#endif // ANIMAL_H

animal.cpp
#include "animal.h"

Animal::Animal(const QString &type, const QString &size)
    : m_type(type), m_size(size)
{
}

QString Animal::type() const
{
    return m_type;
}

QString Animal::size() const
{
    return m_size;
}

animalmodel.h
#ifndef ANIMALMODEL_H
#define ANIMALMODEL_H

#include <QAbstractListModel>
#include <QStringList>
#include "animal.h"

class AnimalModel : public QAbstractListModel
{
    Q_OBJECT
public:
    enum AnimalRoles {
        TypeRole = Qt::UserRole + 1,
        SizeRole
    };

    AnimalModel(QObject *parent = 0);

    Q_INVOKABLE void addAnimal(const QString &type, const QString &size);

    void addAnimal(const Animal &animal);

    Q_INVOKABLE void removeAnimal(int row);

    int rowCount(const QModelIndex & parent = QModelIndex()) const;

    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;

protected:
    QHash<int, QByteArray> roleNames() const;
private:
    QList<Animal> m_animals;
};

#endif // ANIMALMODEL_H

animalmodel.cpp
#include "animalmodel.h"
#include <QDebug>
#include <QListIterator>

AnimalModel::AnimalModel(QObject *parent)
    : QAbstractListModel(parent)
{
}

void AnimalModel::addAnimal(const QString &type, const QString &size)
{
    addAnimal(Animal(type, size));
}

void AnimalModel::addAnimal(const Animal &animal)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_animals << animal;
    endInsertRows();
}

void AnimalModel::removeAnimal(int row)
{
    beginRemoveRows(QModelIndex(), row, row);
    m_animals.removeAt(row);
    removeRow(row, QModelIndex());
    endRemoveRows();
}

int AnimalModel::rowCount(const QModelIndex & parent) const {
    Q_UNUSED(parent);
    return m_animals.count();
}

QVariant AnimalModel::data(const QModelIndex & index, int role) const {
    if (index.row() < 0 || index.row() >= m_animals.count())
        return QVariant();

    const Animal &animal = m_animals[index.row()];
    if (role == TypeRole)
        return animal.type();
    else if (role == SizeRole)
        return animal.size();
    return QVariant();
}

QHash<int, QByteArray> AnimalModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[TypeRole] = "type";
    roles[SizeRole] = "size";
    return roles;
}

Thanks to this model, we can use it in QML to show, for example, a TableView and a ComboBox:
import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.4

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480
    title: qsTr("")

    toolBar: ToolBar {
        id: toolbar
        width: parent.width

        style: ToolBarStyle {
            padding {
                left: 20
                right: 20
                top: 15
                bottom: 15
            }
            background: Rectangle {
                implicitWidth: 100
                implicitHeight: 40
                border.color: "#999"
                gradient: Gradient {
                    GradientStop { position: 0 ; color: "#fff" }
                    GradientStop { position: 1 ; color: "#aaa" }
                }
            }
        }
        ColumnLayout{
            spacing: 2
            RowLayout {
                Button {
                    id: addButton
                    anchors.verticalCenter: parent.verticalCenter

                    text: "Add item"

                    onClicked: {
                        if (typeBox.text || sizeBox.text) {
                            myModel.addAnimal(typeBox.text, sizeBox.text)
                        }
                    }
                }
                TextField {
                    id: typeBox
                    placeholderText: "type"

                    anchors.verticalCenter: parent.verticalCenter
                    anchors.left: addButton.right
                    anchors.leftMargin: 5
                }

                TextField {
                    id: sizeBox
                    placeholderText: "size"

                    anchors.verticalCenter: parent.verticalCenter
                    anchors.left: typeBox.right
                    anchors.leftMargin: 5
                }
            }

            RowLayout {
                Button {
                    id: deleteButton
                    anchors.verticalCenter: parent.verticalCenter

                    text: "Delete item"

                    onClicked: {
                        if(tableView.currentRow != -1)
                        {
                            myModel.removeAnimal(tableView.currentRow)
                        }
                    }
                }
            }
            ColumnLayout{
                spacing: 2
                RowLayout {
                    ComboBox {
                        id: myCombobox
                        currentIndex: 2
                        model: myModel
                        textRole : "type"
                    }

                    Button {
                        id: printvaluesButton
                        anchors.verticalCenter: parent.verticalCenter

                        text: "Print values"

                        onClicked: {
                            console.debug(myCombobox.currentIndex)
                            comboboxManagement.printValues(myModel,
                                                           myModel.index(myCombobox.currentIndex, 0))
                        }
                    }
                }
            }
        }
    }

    TableView {
        id: tableView

        frameVisible: false
        sortIndicatorVisible: true

        anchors.fill: parent

        Layout.minimumWidth: 400
        Layout.minimumHeight: 240
        Layout.preferredWidth: 600
        Layout.preferredHeight: 400

        TableViewColumn {
            role: "type"
            title: "Type"
            width: 100
        }

        TableViewColumn {
            role: "size"
            title: "Size"
            width: 200
        }

        model: myModel
    }
}

As you can see, we have some buttons to add and remove items. When a button is clicked, both TableView and ComboBox are updated.
In the particular case of our ComboBox, we have a C++ class to print the selected element. To have or not a class like this to perform these kind of tasks is up to you and depends on your requirements.
comboboxmanagement.h
#ifndef COMBOBOXMANAGEMENT_H
#define COMBOBOXMANAGEMENT_H

#include <QObject>
#include <QDebug>
#include "animalmodel.h"

class ComboboxManagement : public QObject
{
    Q_OBJECT
public:
    explicit ComboboxManagement(QObject *parent = 0);

    Q_INVOKABLE bool printValues(AnimalModel* model,
                               const QModelIndex &modelIndex);

};

#endif // COMBOBOXMANAGEMENT_H

comboboxmanagement.cpp
#include "comboboxmanagement.h"

ComboboxManagement::ComboboxManagement(QObject *parent) : QObject(parent)
{

}

bool ComboboxManagement::printValues(AnimalModel* model,
                       const QModelIndex &modelIndex) {
    qDebug() << model->data(modelIndex, AnimalModel::TypeRole);
    return true;
}

Finally, the main.cpp
#include "animalmodel.h"
#include "comboboxmanagement.h"

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <qqmlcontext.h>
#include <qqml.h>
#include <QtQuick/qquickitem.h>
#include <QtQuick/qquickview.h>

int main(int argc, char ** argv)
{
    QGuiApplication app(argc, argv);

    AnimalModel model;
    model.addAnimal(Animal("Wolf", "Medium"));
    model.addAnimal(Animal("Polar bear", "Large"));
    model.addAnimal(Animal("Quoll", "Small"));

    ComboboxManagement comboboxManagement;
    QQmlApplicationEngine engine;

    QQmlContext *ctxt = engine.rootContext();
    ctxt->setContextProperty("myModel", &model);
    ctxt->setContextProperty("comboboxManagement", &comboboxManagement);

    engine.load(QUrl(QStringLiteral("qrc:/view.qml")));

    return app.exec();
}


text:
Q: How to force 1G speed for Juniper QFX5100 10G ports? I have available a Juniper QFX5100-48S switch (48 SFP 10G ports, 6 QSFP ports) that I cannot join into our network since an SFP DAC 10G cable connecting it to an SFP port on a HP V1810-48G switch does not work (the web panel on the HP switch says that on the connected port the link is down).
The very same cable successfully negotiates a connection between the HP switch and a server with a 10G Ethernet port once the server port is forced via OS to 1G so my idea was to somehow force the SFP port on the QFX5100 to 1G speed (unsetting the auto-negotiation on the HP switch for the SFP ports is not allowed from the web panel).
The only instructions I could find to do that (here) on the Juniper switch state that, once logged in the management console and entered the CLI context, then configure, then edit interface, there should be possible to issue set xe-0/0/0 speed 1g to force 1G negotiation for the 10G port 0, which I cannot - there is not any speed subcommand available.
Can someone tell me what I am doing wrong or it is simply not possible?

A: DACs use 10G SFP+ modules which are not compatible with the V1810's SFP ports. In theory, they could work between SFP ports when the switch ignores the SFP+ properties - but a 10G port tries to link using 10GBASE-R which cannot work. SFP ports use 1000BASE-X.
The proper syntax for forcing a QFX's port speed to gigabit is link-speed 1g, see https://www.juniper.net/documentation/us/en/software/junos/interfaces-ethernet-switches/topics/ref/statement/link-speed-interfaces-qfx-series.html
If that doesn't work you should use a fiber link, e.g. with 1000BASE-SX modules for multi-mode fiber.


text:
Q: Move files into an existing folder in GitHub I want to move my HTML, CSS, and JavaScript files into the sortable-list folder.

I intended to push the files of my sortable-list project into a folder named sortable-list in my javascript-projects repository. However, when I pushed the files using the cli, it added all the files directly to my zaidazim/javascript-projects repo.
I wish to move the files into the sortable-list folder, so that in the future I can add more project folders here.
How can I achieve that?
P.S.~ I've read some of the previously asked questions but they haven't really helped me much.

A: If you have that repository cloned locally, simply use git mv
cd /path/to/repo
git mv script.js  sortable-list
git commit -m "move file"
git push


text:
Q: How well do relays handle brief overcurrents? Unlike solid-state devices, relays often (in my limited experience) do not come with maximum peak current draw, only maximum continuous current draws. In general, how well do relays take pulses of current over their rated continuous current draws?
Is this different between 'traditional' relays (like this one: http://shop.ciseco.co.uk/jqc-3f-t73-5v-pcb-relay/) and reed relays?

A: The maximum current rating considers both current carrying capacity, and arcing during disconnects, which is also why you have separate AC and DC ratings (arcing is less of a problem with AC, as the arc would be interrupted during the zero crossing).
Short pulses that exceed the DC, but not the AC rating should be fine, but if you turn off at an inopportune time, that may shorten the lifespan a bit.
Exceeding the AC rating means warming up the conductors, especially at the point where the moving parts touch as that is going to be the narrowest point of the connection. If you weld the connectors together, the relay may fail closed.
If this is about inrush current after turning on, you can probably also add an inductor in series after the relay to give it a slow start, but keep in mind the inductor needs a flyback diode (so this can be used for DC only).


text:
Q: How did Captain Jack Harkness become immortal? In Torchwood (the series), Captain Jack Harkness gives some information on how he became immortal and what it means to him. This may be considered spoily to people who haven't seen Torchwood yet.

 He says he's waiting for a doctor to 'cure' him. He says something happend to him long ago that made him unable to die.

Is that answered anywhere in the Doctor Who or Torchwood series?

A: In the 9th Doctor episode The Parting of the Ways,

 Jack was killed (exterminated!) defending Satellite 5 against a Dalek invasion fleet.

After this,

 Jack was resurrected by Rose (who had the powers of the Time Vortex at this point).

Although we know that he survived at that stage, we don't know that he cannot be killed (this is revealed in later episodes), but it's presumably the cause.  This was probably an accident caused by inexperience and wielding powers that are not meant to be used.

A: Just thought I would throw my 2 cents in. He's not immortal, he just ages super super super super-slow.
In the season 3 episode "Last of the Time Lords", Jack says when he was a Time Agent he used to be called "the Face of Boe", so we know he does die in the earlier season 3 episode "Gridlock".
Please see this link for the clip:

So to end, he's not immortal per se, he is just super and filled with time vortex.

A: In addition to Tony's answer, more information about Jack's immortality is given in the Doctor Who season 3 episode Utopia, where Jack finally catches up with the Doctor again and they are transported to the year 100 trillion (!). In that episode

 Jack talks about being filled with the Time Vortex and being brought back to life, and how he gradually discovered he could not be killed. The Doctor in turn reveals that he considers Jack's immortal status to be unnatural, which is why he'd been avoiding him ever since.

At the end of the following episode, Last of the Time Lords, it's hinted that...

 Jack eventually becomes the Face of Boe.

A: Captain Jack Harkness became immortal in season 1 on Doctor Who (2005) in the last episode.  He died and resurrected thanks to Rose.

A: Jack was contaminated with the nano genes during his first two appearances.  Thus when he dies they resurrect him back to that version. The fact that it is not instantaneous means it is not a time vortex phenomena as well as the fact that he is always the same.  The incident with Rose and the time vortex was coincidental and may have confused the Doctor or the Doctor may simply be lying.  Spoiler:  The Character Nancy was also exposed to the nano genes when they examined her and determined her DNA and the DNA of her child was the pattern they should use for humans.  Nancy can not die as well, and each time she is killed she returns in a 21 year old body of a woman.  Now she has returned to the episodes and has finally found the doctor again.


text:
Q: regexp: match everything beginning from second dot including dot I want to match everything beginning from second ., including .
Regexp: /(?<=\d\.\d+)\..*/g. Playground regex101
It does not work for strings 1232..233232.

A: Update
as @WiktorStribiżew points out the regex don't test for 1212.2e1.121212 os this might be a better solution.
/(?<=^[^.]*\.[^.]*)\..*/ since it will also test for this
old answer.
You can do this regex101, this will begin including from the second . including it.
Regexp: /(?<=\d?\.\d*)\..*/g
You need to use * (include 0 to x elements of this character) instead of + (include 1 to x of this character)
I have added a ? after your first \d to handle the case if it starts with a . and not a digit.

A: When reading your question literally.

I want to match everything beginning from second ., including .

This would do the trick:
[.][^.]*([.].*)

Leaving the resulting answer in group 1. Keep in mind that [^.] also matches newline characters, if you don't want this add \n to the character negation class.


text:
Q: How to request CMake to be not verbose? Every time I launch make (generated from CMake), each build step is introduced with multiple lines formatted this way:
[100%] Built target foobar
Linking CXX executable ../../bin/foobar
make[2]: quittant le répertoire « /home/me/git/master/build/debug »

That goes from 0% up to 100%. So every time I launch make, it outputs a lot of lines. A lot. That's very verbose and warnings get lost in the process.
How can I ask CMake to remove all that, and generate Makefiles that will get make to output only the compiler output?

A: Just do:
make > /dev/null

You still get compiler error messages printed out since they go to stderr.


text:
Q: wrong size and positon of UITextView after creating Box for its contours I was trying wrap test into enclosing box by means of boundingrectwithsize function.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if let messageText = messages?[indexPath.item].text {
        let size = CGSize(width:view.frame.width,height: 1000)
        let options = NSStringDrawingOptions.usesLineFragmentOrigin.union(.usesFontLeading)
        let estimatedFrame = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 18)], context: nil)
        return CGSize(width: view.frame.width,height: estimatedFrame.height)
    }

    return CGSize(width:view.frame.width,height: 100)
}

}
But the output was something weird and  i am very confused

why it did always cutting last string? It seemed to me i was using right NSString.DrawingOptions and especially usesFontLeading calculates the size but why it cut the last string?

A: UITextView adds padding by default. Sizing using NSString sizing methods don't take this into account. You can either turn off the padding using:
myTextView.textContainerInset = UIEdgeInsets.zero
myTextView.textContainer.lineFragmentPadding = 0

Or add them to your size:
CGSize(width: view.frame.width,height: estimatedFrame.height + myTextView.textContainerInset.top + myTextView.textContainerInset.bottom)


text:
Q: WCF Service hosted in a WinForm is not working I want to create a very simple WebService (WCF) inside a Winforms application. To test this I created a WCF Service called Calculator inside my Winforms application. On the other side I created a simple Winforms application with a button to retrieve the Results of the service.
I  have added the Webservice as a reference to the testproject. It recognizes the two implemented methods and everything just fine. The problem is that I get no response from the webservice (freezing my testapplication). I have most likely forgot something on the Webservice application. What could it be?
Here's the webservice:

[ServiceContract]
public interface ICalculator
{

[OperationContract]
double AddNumbers(double number1, double number2);

[OperationContract]
string TestMethod();

}

public class Calculator : ICalculator
{
    #region ICalculator Member

    public double AddNumbers(double number1, double number2)
    {
        return number1 + number2;
    }

    public string TestMethod()
    {
        return "HELLO WORLD!";
    }

    #endregion
}

This is how I open the Webservice.
this.m_WebService = new ServiceHost(typeof(Calculator));
this.m_WebService.Open();

Here is the App.config
<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Solution.Server.CalculatorBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="Solution.Server.CalculatorBehavior"
        name="Solution.Server.Calculator">
        <endpoint address="" binding="wsHttpBinding" contract="Solution.Server.ICalculator">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8731/Solution/Calculator/" />
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>

If I enter the URL (http://localhost:8731/Solution/Calculator/) in the Webbrowser I get this screen:

A: With self hosting WCF services, the main Things to check are:

*

*Are you running in a Security context that allows you to start a httplistener?

*Are the ports that you are using blocked

*Configuration problem

Try testing With the WCF Test Client. http://msdn.microsoft.com/en-us/library/bb552364(v=vs.110).aspx


text:
Q: mimic linux grep -w in perl grep Grep in perl gives me all the matched lines with the regular expression.
For ex-
{
    my @FAMILY_MAP= ("A2LVLX","LVLX","O2LVLX");
    my $search="LVLX";
    my @match = grep (/ALVL/, @FAMILY_MAP);
    print @match;
 }

Here my expected output is LVLX but i get all the three elements in the array.
Which is expected behaviour in the Linux terminal too(if grep LVLX is done on a file containing the three words). But i have to used grep -w "LVLX" in the terminal to get LVLX as the output.
I need a way to replicate the same using perl grep. Any hints?

A: grep -w matches the string only when it appears as a whole word. For that, you need to use the word boundary (\b) escape sequence in your regex.
my @family_map = ("A2LVLX","LVLX","O2LVLX");
my $search = 'LVLX';
my @match = grep (/\b$search\b/, @family_map);
print "@match";

Update: Alternatively, if you know the elements of your array will all be individual words, then just use eq.
my @match = grep( $_ eq $search, @family_map);

A: If you want an exact match, you need to tell it. Your pattern /LVLX/ matches strings that contain the pattern, because you have not anchored it.
There are two ways to do this. Either you anchor your pattern like this
my @match = grep(/^ALVL$/, @FAMILY_MAP);

or you use the block form of grep and do an equality check, which is faster in older Perls (very new Perls have this optimized, but I don't remember in which version that was introduced)
my @match = grep { $_ eq 'ALVL' } @FAMILY_MAP;

Both will give you the same output.


text:
Q: spring replace bean name in config file with value from property file I have a bean config file as follows
<bean id="myFactory" class="com.public.Factory">
    <property name="dataSourceAdaptor" ref="${value.from.property file}Adaptor" />
</bean>

How do i achieve this.
I added the following to top of the config file
<util:properties id="myProperties" location="classpath:app.properties"/>

and then tried to refer to the value using ${} but i get an error stating ${value.from.property file}Adaptor is not a valid bean
I cannot put the whole name (xyzAdaptor) in the property file as the value in the property file is an institution and there are multiple adaptors for each institution.
for example xzyDisplayAdaptor, xyzProductAdaptor, xyzDatasourceAdaptor
The xyz client can change to say abc client and i want to be able to change the value in property file to abc and all the abc related beans will be injected.

A: The util:properties tag is used to create an instance of java.util.Properties. I think what you need is a PropertyPlaceholderConfigurer.
e.g.,
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" scope="singleton">
           <property name="searchSystemEnvironment" value="true" />
           <property name="ignoreResourceNotFound" value="true" />
           <property name="locations">
                <list>
                    <value>classpath:app.properties</value>
                </list>
            </property>
</bean>

A: Try this with Spel:
    <util:properties id="myProperties" location="classpath:app.properties"/>

    <bean id="myFactory" class="com.public.Factory">
        <property name="dataSourceAdaptor" ref="#{'${value.from.property file}'+'Adaptor'}" />
    </bean>


text:
Q: Overriding a private method with Reflection Is it possible to override a private method by using Reflection in .NET 3.5?

A: Well, it would need to be virtual to be possible to override it (by writing a dynamic type that inherits from the class), and you can't have a private virtual (it makes no sense). You could perhaps override an internal virtual, but I suspect even this may hit security issues. So ultimately, I'd say no.

A: Not by using Reflection alone. Perhaps the best you could do is to use Reflection, combined with Reflection.Emit or the CodeDom to duplicate the class into a new namespace. When you come across the private method you want to replace, you don't copy it, you emit your replacement.
However, there are many techniques a developer can use that make this technique much, much harder. Breaking the implementation of the class into many private or internal classes is one such.
Note: using the CodeDom you'd have to build the graph in memory, compile it, and then load the resulting assembly.
This is probably a LOT more trouble than it is worth.
The other way to do it would be to use Reflector to disassemble the class, take the code and build your own class from it with the method replace. Again there are significant technical and legal hurdles to overcome. You may learn a lot from the disassembled code though.

A: Not by using Reflection. You need to use some sort of AOP.

A: Typemock Isolator is supposed to be able to do this, but does so through the .NET profiler APIs (according to Roy Osherove in The Art of Unit Testing).


text:
Q: Ramified Geometric Langlands Is the following a reasonable formulation of (a part of) the geometric Langlands conjecture for $\mathrm{GL}_n$ over a curve $X$?
(*) Let $\mathcal{L}$ be an irreducible rank $n$ $\ell$-adic local system (=lisse sheaf) on $X-S$, where $S$ is a finite set of points. Then there exists a Hecke eigensheaf on the moduli stack $\mathrm{Bun}_n$, of rank $n$ vector bundles on $X$ equipped with appropriate level structures on $S$, whose Hecke eigenvalue is $\mathcal{L}$.
For $n=1$, this amounts to the global class field theory, so I will restrict to the case $n>1$.
If $S$ is empty then this statement was proved for $n=2$ by Drinfeld and for arbitrary $n$ by Frenkel--Gaitsgory--Vilonen. If $S$ is non-empty (i.e. $\mathcal{L}$ is ramified) then much less is known. For instance, I know of only one case when this statement has been established in presence of wild singularities. This is when $X=\mathbb{P}^1$ and $\mathcal{L}$ is the generalised Kloosterman sheaf (which has wild singularity at $\infty$ and tame singularity at $0$). The above statement in this case was proved by Heinloth--Ngo--Yun.
I appreciate it if somebody can point out a reference where the conjecture is precisely formulated and also if people can list all the known cases.
------------------------ Added in edit:
Here are bolder assertion:
**) The same statement is expected to hold if we consider all local systems (not just irreducible ones).
***) There is a bijection between local systems on open dense subsets of $X$ and (equivalence classes of) Hecke eigensheaves on $\mathrm{Bun}_n$ (equipped with appropriate level structure at the ramified points).
-------------------- Added in further edit:
As David Ben-Zvi points out, ** and *** are not precise enough as they don't take into account Arthur's parameters. How about the following statement:
*+) There is a canonical bijection between irreducible rank $n$ local systems on open dense subsets of $X$ and (equivalence classes of) cuspidal Hecke eigensheaves on $\mathrm{Bun}_n$ (equipped with appropriate level structure at the ramified points).
At the decategorified level, this would give the classical (i.e. non-geometric)  bijection between irreducible Galois representations and cuspidal automorphic representations, proved by Drinfeld and L. Lafforgue.
Of course, to make any of this precise one has to specify what one means by a Hecke eigensheaf in the ramified situation. One place this is (roughly) discussed is in the introduction of Heinloth's PhD thesis. Another place is in Section 4.3 of Yun's CDM paper, though the latter also includes an "automorphic data" in the definition (which we may or may not want).
------------More precise formulation:
As Will and David point out, one needs to specify what one really means by Hecke eigensheaf and by level structures before one can judge if *+ is reasonable. It is not clear to me how to handle this. But here is an attempt.
Let $K$ be a compact open subgroup of $\mathrm{GL}_n(\mathbb{A})$. Then, I believe, we do know what a Hecke eigensheaf on
$\mathrm{GL}_n(k(X))\backslash \mathrm{GL}_n(\mathbb{A})/K$ is. Let us call this a $K$-Hecke eigensheaf. Let us call a $K$-Hecke eigensheaf $E$ and $K'$-Hecke eigensheaf $E'$ equivalent if there exist a subgroup $K''\subset K\cap K'$ such that the pullbacks of $E$ and $E'$ to
$\mathrm{GL}_n(k(X))\backslash \mathrm{GL}_n(\mathbb{A})/{K''}$
are isomorphic.
Now I guess conjecture *+ is that there is a bijection between irreducible local systems and equivalence classes of Hecke eigensheaves.
Note that one could (and perhaps should) define the equivalence using Yun's notion of automorphic data. This means that in addition to $K$, we also a choose a character $\chi$ of $K$.
A further intriguing alternative (suggested by Will Sawin) is to use the conductor. That might remove the ambiguity of this $K$.


text:
Q: Python: Converting multiple files from xls to csv I'm trying to write a script in Python 2.7 that would convert all .xls and .xlsx files in the current directory into .csv with preserving their original file names.
With help from other similar questions here (sadly, not sure who to credit for the pieces of code I borrowed), here's what I've got so far:
import xlrd
import csv
import os

def csv_from_excel(xlfile):
     wb = xlrd.open_workbook(xlfile)
     sh = wb.sheet_by_index(0)
     your_csv_file = open(os.path.splitext(sxlfile)[0], 'wb')
     wr = csv.writer(your_csv_file, dialect='excel', quoting=csv.QUOTE_ALL)
     for rownum in xrange(sh.nrows):
         wr.writerow(sh.row_values(rownum))
     your_csv_file.close()

 for file in os.listdir(os.getcwd()):
      if file.lower().endswith(('.xls','.xlsx')):
         csv_from_excel(file)

I have two questions:
1) I can't figure out why the program when run, only converts one file and doesn't iterate through all files in the current directory.
2) I can't figure out how to keep the original filename through the conversion. I.e. that an output file has the same name as an input.
Thank you

A: One possible solution would be using glob and pandas.
excel_files = glob('*xls*')

 for excel in excel_files:
    out = excel.split('.')[0]+'.csv'
    df = pd.read_excel(excel, 'Sheet1')
    df.to_csv(out)


text:
Q: No me realiza búsqueda correcta, omite algunos registros según la búsqueda - Livewire tengo la siguientes tablas

La tabla category_area se relaciona los ID de otra tabla llamada category y adicionalmente de una tabla llamada área
la tabla categoryAreaUser se relaciona el ID del la tabla usuarios y a la vez el ID de la tabla category_area
La tabla de registeractivities se guarda el ID de usuarios y el ID de la tabla category_area
lo que quiero hacer es según el usuario logueado "en este caso el usuario va ser 478" que pertenece a la tabla categoryAreaUser va a mostrar los registros de la tabla registrosactividades según el id_category_area que este asociado, adicionalmente estoy mostrando los registro que corresponde a cada usuario logueado "478" según el id_user.
Obtengo el id del usuario logeado y se lo paso a una variable id_user
$this->id_user = auth()->user()->id;

Luego realice la siguiente consulta
$this->idcategoryareas = categoryAreaUser::where('id_user', $this->id_user)->pluck('id_category_areas');
$registeractivities = Registeractivity::orwhereIn('id_category_areas', $this->idcategoryareas)->orwhere('id_user', $this->id_user);

luego la pinte en la vista
return view('livewire.registeractivity.live-register-activity-table',[
                'registeractivities' => $registeractivities
                ->where('des_c_activity', 'like', "%{$this->search}%")
                ->orderBy($this->sort, $this->direction)
                ->paginate($this->perPage),
            ]);

como queda el render
public function render()
{
    //ID actual de usuario logeado
    $this->id_user = auth()->user()->id;
    $this->id_area = auth()->user()->id_area;

    $this->idcategoryareas = categoryAreaUser::where('id_user', $this->id_user)->pluck('id_category_areas');
    $registeractivities = Registeractivity::orwhereIn('id_category_areas', $this->idcategoryareas)->orwhere('id_user', $this->id_user);

    return view('livewire.registeractivity.live-register-activity-table', [
        'registeractivities' => $registeractivities
            ->where('des_c_activity', 'like', "%{$this->search}%")
            ->orderBy($this->sort, $this->direction)
            ->paginate($this->perPage),
    ]);
}

las prueba que echo funciona bien, no se si toque cambiar algo
El problema viene es que tengo un buscador ->where('des_c_activity', 'like', "%{$this->search}%"), al realiza una búsqueda me esta omitiendo algunos registros segun la busqueda
Si busco a el me muestra a y b
Si busco b el me muestra solo b
Si busco c el me muestra b y c
No se que hacer ya intente de muchas manera pero el problema creo que esta es al aplicar el or en las consultas

A: Lo pude resolver pasando la consulta a un scope
en controlador deje
public function render()
{

        $registeractivities = Registeractivity::Consulta();

        return view('livewire.registeractivity.live-register-activity-table',[
            'registeractivities' => $registeractivities
            ->where('des_c_activity', 'like', "%{$this->search}%")
            ->orderBy($this->sort, $this->direction)
            ->paginate($this->perPage),
        ]);

}

En el modelo deje
public function scopeConsulta ($query )
{

    $this->id_user = auth()->user()->id;
    $this->idcategoryareas = categoryAreaUser::where('id_user', $this->id_user)->pluck('id_category_areas');
    return $query->orwhereIn('id_category_areas', $this->idcategoryareas)->orwhere('id_user', $this->id_user);
}

por algún motivo al dejar la consultas en el render directamente ocaciona el conflicto


text:
Q: How Do I Keep A Validated Masked US Phone Number Validated With ng-pattern in AngularJS From Invalidating If Too Many Digits Are Entered I have trying to figure out a way to validate an input that is masked to display US based phone numbers as (###) ###-#### I have tried a few things and the closest thing I have found is using
<form name="phone_form" novalidate>
    <input name="phone" class="phone_us" type="tel" ng-model="phone" placeholder="(555) 555-1212" ng-pattern="/^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/" />
    Invalid Phone Number
</form>

I pulled the regex from - Angularjs dynamic ng-pattern validation - This successfully validates the input and matches the use case, it even throws the right error and displays the correct message. However as soon as you enter any digit beyond the 10 digits of the phone number the error is triggered and the input is invalid again. If I backspace one digit and add one digit again then the input validates once more as long as i dont add any more digits. The field is masked so you can not see any extra digits outside the displayed phone number and even if you try to enter 10 digits past the valid phone number all you have to do to re-validate the form successfully is backspace one digit and enter it again.
I've tried a few variations of max-length and min-length or max="#" etc. And I can't figure it out.
I am using Angular 1.5.7
A plunkr of where I am at can be found here:
http://plnkr.co/edit/Ln7SciLSpnLJRZdA0P2N?p=preview

A: I'd recommend you to use ngMask module.. take a look at how simple it's to use below:

angular.module('app', ['ngMask'])
 .controller('mainCtrl', function($scope) {

 });

  <form name="phone_form" novalidate>
    <input type="text" name="text" class="phone_us" ng-model="phone" placeholder="(555) 555-1212" mask="(999) 999-9999" restrict="reject">
  </form>


text:
Q: Timer count throughout the game in Objective c I am creating a game application in which I need to set timer of 2 minutes throughout the app screens in objective c.
I am creating it in viewDidLoad but it is creating a new instance every-time the view loads.
Here is the code which I am using :
@interface SomeViewController ()
{
    int timerCounter;
     NSTimer *timer;
}
@property (strong, nonatomic) IBOutlet UILabel *timerLbl;

@end

@implementation SomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self startCountdown];
}

- (void)startCountdown
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1
                                             target:self
                                           selector:@selector(countdownTimer:)
                                           userInfo:nil
                                            repeats:YES];
}

- (void)countdownTimer:(NSTimer *)timer
{
    timerCounter--;

    int minutes = timerCounter / 60;
    int seconds = timerCounter % 60;

    NSString *string = [NSString stringWithFormat:@"%02d", minutes];
    NSString *string2 = [NSString stringWithFormat:@"%02d", seconds];

    NSString *timeTotal = [string stringByAppendingString:@":"];
    NSString *timeTotal2 = [timeTotal stringByAppendingString:string2];

    _timerLbl.text = timeTotal2;
    if (timerCounter <= 0) {
        [timer invalidate];
    }
}

A: You need to invalidate it whenever the VC deallocates
- (void)dealloc {
    [timer invalidate];
}

//
The second VC may look like this
#import "ggViewController.h"
NSInteger timerCounter = 120;     // declared global to hold the value
@interface ggViewController ()
{
    NSTimer*timer;
}
@end

@implementation ggViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

   // instead of using selector use this inline callback
  timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:true block:^(NSTimer * timer) {

     timerCounter--;

     int minutes = timerCounter / 60;
     int seconds = timerCounter % 60;

     NSString *string = [NSString stringWithFormat:@"%02d", minutes];
     NSString *string2 = [NSString stringWithFormat:@"%02d", seconds];

     NSString *timeTotal = [string stringByAppendingString:@":"];
     NSString *timeTotal2 = [timeTotal stringByAppendingString:string2];

     _timerLbl.text = timeTotal2;
      if (timerCounter <= 0) {
          [timer invalidate];
         }
    }];

}

-(void)viewDidDisappear:(BOOL)animated{

    [super viewDidDisappear:animated];

    [timer invalidate];
}

- (IBAction)gg:(id)sender {

    [self dismissViewControllerAnimated:true completion:nil];
}
@end


text:
Q: split comma separated string by comma Need to split the string containing country names separated by comma(,) and also country name itself contains comma(,) too.
var str = "South Georgia and The South Sandwich Islands,Congo, Democratic Republic,Mauritania,Finland,Spain,Armenia,Mauritius,France,Sri Lanka,Aruba,Mayotte,French Guiana,Suriname,Australia,Mexico,French Polynesia,Svalbard and Jan Mayen,Austria,Micronesia, Federated States,French Southern Territories";

Expected result:
[   "South Georgia and The South Sandwich Islands",
    "Mexico",
    "French Polynesia",
    "Congo, Democratic Republic",
    "Svalbard and Jan Mayen",
    "Micronesia, Federated States",
]

A: Generally you don't want to use a character that could show up in valid countries as the deliminator, aka ,
However if we can assume that , will only show up without spaces around it when its used as a deliminator. Then we could use a regex to split the string:

var str = "South Georgia and The South Sandwich Islands,Congo, Democratic Republic,Mauritania,Finland,Spain,Armenia,Mauritius,France,Sri Lanka,Aruba,Mayotte,French Guiana,Suriname,Australia,Mexico,French Polynesia,Svalbard and Jan Mayen,Austria,Micronesia, Federated States,French Southern Territories";
var res = str.split(/(?<=\w),(?=\w)/i);
console.log(res)

Regex explained:

*

*(?<=\w) is a look behind for any "word" character.

*(?=\w) is a look ahead for any "word" character.

*, will match a comma char if and only if the look ahead and look behind succeeds.

Interactive example: https://regexr.com/42b3e
Edit:
Efter looking into an issue brought up by @BorisSokolov in the comments, its become clear that the regex implementation differs between the major javascript runtimes.
Runtimes tested:

*

*V8(includes Node): Works as intended

*SpiderMonkey: Throws
SyntaxError: invalid regexp group. Turns out Mozilla haven't yet implemented the "possitive look behind" standard.

*ChakraCore: Throws Script error. Same here, turns out microsoft haven't yet implemented the "positive look behind" standard either.

Looking at TC39 we can see that the "possitive look behind" is part of the ES2018 spec. So its expected to be implemented in all major browsers in the near future.

A: If the format of the string is in the same format as above then first you need to split string with comma.
if item in the result array begins with a space then merge that item with previous item in the result array.
In country names with comma, there exists a space after comma while others not

A: There is probably a way to do it by regular expression, but I would suggest the easy way. Looking at your input, you can see that those commas that separate the title of a country from it's name are followed by a space, whereas the listing comma isn't followed by one:
var str = "South Georgia and The South Sandwich Islands,Congo, Democratic Republic,Mauritania,Finland,Spain,Armenia,Mauritius,France,Sri Lanka,Aruba,Mayotte,French Guiana,Suriname,Australia,Mexico,French Polynesia,Svalbard and Jan Mayen,Austria,Micronesia, Federated States,French Southern Territories";
So in order to separate those two, I would suggest replacing ", " by a special character that would not occur in your input - say "$". Afterwards, you can split by ",". Then you can replace your special character back to ", ":
function getCountryList(str) {
  var strWithSpecialCharacterReplaced = str.replace(", ", "$");
  var countryList = strWithSpecialCharacterReplaced.split(",");
  return countryList.map(countryString => countryString.replace("$", ", "));
}

This is of course not the most performant solution. But it is one.

A: Just use Regex!

var str = "South Georgia and The South Sandwich Islands,Congo, Democratic Republic,Mauritania,Finland,Spain,Armenia,Mauritius,France,Sri Lanka,Aruba,Mayotte,French Guiana,Suriname,Australia,Mexico,French Polynesia,Svalbard and Jan Mayen,Austria,Micronesia, Federated States,French Southern Territories";
var res = str.split(/(?<=\w),(?=\w)/i);
console.log(res)

In this example, I use (? = [A-zA-Z0-9]) [,] (? = [A-zA-Z0-9]) to get all the commas surrounded by letters and divide them (the " , "is not divided in this case and return is correct)! Tested and working!


text:
Q: GTLServiceCalendar change listener I'm using GTLServiceCalendar for fetching the event from a specific calendar.
I mention code below
- (void)fetchEventsFromCalendarId:(NSString *)calendarId {

    GTLQueryCalendar *query = [GTLQueryCalendar queryForEventsListWithCalendarId:calendarId];
    query.maxResults = 10;
    query.timeMin = [GTLDateTime dateTimeWithDate:[NSDate date]
                                         timeZone:[NSTimeZone localTimeZone]];;
    query.singleEvents = YES;
    query.orderBy = kGTLCalendarOrderByStartTime;

    [self.serviceCalendar executeQuery:query
                      delegate:self
             didFinishSelector:@selector(displayResultWithTicket:finishedWithObject:error:)];
}

I need to refresh the list asap when new events are added into Google Calendar with calendarId, without including a server side.
My question: is there any delegate method that will be called when new events are added to my calendarId ?


text:
Q: Star Rating in Custom Lightning component I was doing the trailhead
lightning-restaurant-locator And the trailhead is showing how to use Get request so by looping through the response, name and views are in a list.
Now I want to add star for rating in each list so other contacts can also see what a person has rated the restaurant. I put the stars there but if I will refresh or go to other contacts it can remove.

So how can I add the star and post them for others to see the rating in lightning component. I am new to salesforce so facing some troubles.
InTheArea.cmp

          <aura:iteration items="{!v.restaurantList}" var="item" indexVar="i">

{!item.name}

{!item.address}

{!item.city}, {!item.state}

{!item.phone}

                          <ui:button class="slds-button slds-button_success" label="RateTheRestaurant" press="{!c.handleClick}" />

{!item.review}

                              <input type="text" id="text1" class="slds-input" placeholder="Review" />

                                    1
                                    2
                                    3
                                    4
                                    5

                ☆☆☆☆☆

      <ui:inputText label="Name" aura:id="fame" placeholder="First" change="{!c.getInput}"/>

           <ui:button aura:id="outputButton" label="Submit" press="{!c.getInput}"/>

{!v.para}

InTheAreaController.js

handleClick : function(cmp, event) {
        confirm("Do you Really want to save this Form");
},
    bandleClick : function(cmp, event) {
        alert("Thanks for your Feedback!");
},


text:
Q: Difference in Negative forms( also Archaic English) Imagine this, my baby brother was making annoying weird noise to irritate me, so I'd tell him
"Can you NOT do that!" {But here I can't say "CAN'T you do that!"}
Now,imagine my big brother was making me to go to the store just after I entered the house from school,so I'd tell him
"CAN'T you do that!" {But here I can't say "Can you NOT do that!"}
But the grammar rules state that if "not" isn't contracted then it must come after the subject but in these cases it obviously makes notable difference. What are the present rules to this and what should I generally use in modern times? Also I have seen this in archaic/older English, what were the older grammar rules when it came to negatives?