text:
Q: Extracting entity save class I am in a situation where I have 100 tables (entity classes) and 100 screens (1 for each).
Let us take a look at 2 screens: ShipviaTopComponent and RouteTopComponent. RouteTopComponent has the following method:
public static void saveRecord() {
    Route r = resultList.get(currentPos);
    EntityManager entityManager = Persistence.createEntityManagerFactory("EntityLibraryPU").createEntityManager();
    entityManager.getTransaction().begin();
    r = entityManager.find(Route.class, r.getRouteKey());
    r.setRoute(txtRoute.getText());;
    entityManager.persist(r);
    entityManager.getTransaction().commit();
}

Now, if I put that method in each of 100 screens, everything will work; however I am looking at extracting it into its own class. That means that it won't always be Route, but can be Shipvia or any other entity class.
I am expecting my RouteTopComponent to call it with something like the following;
com.demo.viewer.SaveRecord.SaveRecord(r);

That r contains just about everything I will need. Here is the SaveRecord class.
public class SaveRecord {

public static void saveRecord(entity.Route r) {

    EntityManager entityManager = Persistence.createEntityManagerFactory("EntityLibraryPU").createEntityManager();
    entityManager.getTransaction().begin();
    r = entityManager.find(Route.class, r.getRouteKey());
    r.setRoute("01-banana"); //Hardcode this for now
    entityManager.persist(r);
    entityManager.getTransaction().commit();
}

One of the problems I have - it is expecting entity.Route if I pass 'r' to it. But if I pass Shipvia, it will break. What are some ways I can just have it expect something like entity.Anything
Edit: As per suggestion, I am attempting to create a superclass entity.
Superclass AddChg entity - http://pastebin.com/1iW67NVn
Shipvia entity - http://pastebin.com/R53tNHyp (Just original, normal entity)
Route entity - http://pastebin.com/5DCvj340 (Extends AddChg)
The piece of code for SaveRecord (I named it SaveResult) looks like this:
 public static <T extends AddChg> void SaveResult(T r) {
    EntityManager entityManager = Persistence.createEntityManagerFactory(
         "EntityLibraryPU").createEntityManager();
      entityManager.getTransaction().begin();
      r = entityManager.find(Route.class, r.getId());
      r.setSomething("01-banana");
      entityManager.persist(r);
      entityManager.getTransaction().commit();
 }

Now, it seems to work, in a sense that when r. pulls everything form the superclass. There is only one line that seems to be giving me trouble:
      r = entityManager.find(Route.class, r.getId());

Route.class has to also vary based on which entity its trying to access. And the r.getId() has to be the PK of the entity that is being saved.
So for example, if user wants to edit RouteTop Screen, the line should read;
r = entityManager.find(Route.class, r.getRouteKey());

But for ShipviaTopScreen it will be;
r = entityManager.find(Shipvia.class, r.getShipvViaCd());

Am I able to pass those as parameters such as:
 public static <T extends AddChg> void SaveResult(T r, Class c, String PK)

Edit3: The solution above works, and lastly I have one last problem/question.
SaveResult:
public static <T extends AddChg> void SaveResult(T r, Class c, String pk) {
        EntityManager entityManager = Persistence.createEntityManagerFactory(
             "EntityLibraryPU").createEntityManager();
          entityManager.getTransaction().begin();
          r = entityManager.find(c, pk);
          r.setSomething("01-banana");
          entityManager.persist(r);
          entityManager.getTransaction().commit();
 }

RouteTopComponent:
public static void saveRecord() {
    if (r.getRouteKey() != null) {
        r.setRoute(txtRoute.getText());
    }
    SaveResult.SaveResult(r, Route.class, r.getRouteKey());
}

Problem is with the r.setSomething("");
When I type r. my only suggestions are those in the superclass (You will have to refer to the pastebin links for this question).
In RouteTopComponent I am able to do r.setRoute, but not in SaveResult =(
Edit4: I have pursued the approach of saving entity specific data in the TopComponent, while leaving the generic (common) fields to the superclass. Here is what my code looks like now:
RouteTopComponent:
public static void saveRecord() {
        WWEntityManager.entityManager.getTransaction().begin();
        r = WWEntityManager.entityManager.find(Route.class, r.getRouteKey());
        r.setRoute(txtRoute.getText());
        WWEntityManager.entityManager.persist(r);
        WWEntityManager.entityManager.getTransaction().commit();
        SaveResult.SaveResult(r, Route.class, r.getRouteKey());
    }

As you can see, I am now committing a Route.class specific fields first. THEN I call out to the SaveResult method which then saves the generic stuff;
SaveResult
public class SaveResult {

    public static <T extends AddChg> void SaveResult(T r, Class c, String pk) {
        WWEntityManager.entityManager.getTransaction().begin();
        r = (T) WWEntityManager.entityManager.find(c, pk);
        r.setChgDate("2012-05-31");
        WWEntityManager.entityManager.persist(r);
        WWEntityManager.entityManager.getTransaction().commit();
    }
}

I am wondering if that is indeed the way I should handle saving a single record (with 2 commits)? It works, but if there is a better practice on how to handle it, that would be pretty awesome!

A: I'd go for a superclass (let's call it PersistentObject), from which all the entities inherit the basic fields, like an Id for example.
Then, the parameter of your method would be a PersistentObject instead of the parcitular entity Route. You can also define the parameter as any class that extends PersistentObject if you like:
public <T extends PersistentObject> static void saveRecord(T newRecord) {
    //your persistence logic here
}

This site explains the basics in a nice way.
EDIT: Regarding your "EntityManager.find()" issue:
Your option seems ok to me, as the EntityManager.find() method returns an entity by primary key checking if either the first argument is, indeed, a class and checking if the second argument matches with the type of the primary key of the entity. I think you can save yourself some trouble by doing directly r.getClass() instead of having a Class c argument. Still, doing everything in the SaveResult method will require that you provide the PK.
As a suggestion (discard it if it's either tedious or simply impossible), you can extract that find() logic to another method and pass the entity you get as a parameter to the save method, making it independent of object-specific attributes.
There's another option: NamedQueries. You can define a "findById" query on each entity and then you call the entity.createQuery Method which returns the object you're searching. This can be a "NO!" in your particulas case, since you have 100 entities and hence you have to do 100 particular queries (Here, Copy-Paste is a siren calling to you to cause  disaster...).
I've never done this myself, but maybe you can create an unique "findById" NamedQuery in the mapped superclass and pass the corresponding Id, but you're up to some particular cast handling.
EDIT 2: Indeed, since the T type extends AddChg the only methods you know you'll be able to access are the ones on the superclass. With this in mind (and avoiding an overkill) you can define a "setRoute()" in the superclass and override it in your particular classes, giving it the particular behaviour you want.
If you need a more complex approach involving many instance-specific attributes you'll need to prepare your object before saving it. Your save method should only have the persistence-related operations required to store the object. That "setSomething()" seems to be related to object data itself, so it's more appropiate to do it in RouteTopComponent as you're doing it.
EDIT 3: Just use the last persist. The first one persists half of the info and the last one persists everything.

A: Use generics
Make superclass
interface IParent
{
   long getId();

   void setSomething(String smth);
}

each entity implements IParent
public class SaveRecord
{
   public static <T extends IParent> void saveRecord(T r)
   {
      EntityManager entityManager = Persistence.createEntityManagerFactory(
         "EntityLibraryPU").createEntityManager();
      entityManager.getTransaction().begin();
      r = entityManager.find(Route.class, r.getId());
      r.setSomething("01-banana");
      entityManager.persist(r);
      entityManager.getTransaction().commit();
   }


text:
Q: Force uniqueness in JSONB array Let's say I have a table students with a column type jsonb where I store a list with students' additional emails. A student row looks like this

student_id
name
emails

1
John Doe
[j.doe@email.com]

I'm using the following query to update the emails column:
UPDATE students SET emails = emails || '["j.doe@email.com"]'::jsonb
                     WHERE student_id=1
                     AND NOT emails @> '["j.doe@email.com"]'::jsonb;

Once the column emails is filled, if I reuse query above with the parameter ["j.doe@email.com", "john@email.com"], the column emails would be update with repeated value:

student_id
name
emails

1
Student 1
[j.doe@email.com, j.doe@email.com, john@email.com]

Is there a way to make sure that in the column emails I'll always have a jsonb list with only unique values ?

A: Use this handy function which removes duplicates from a jsonb array:
create or replace function jsonb_unique_array(jsonb)
returns jsonb language sql immutable as $$
    select jsonb_agg(distinct value)
    from jsonb_array_elements($1)
$$;

Your update statement may look like this:
update students
set emails = jsonb_unique_array(emails || '["j.doe@email.com", "john@email.com"]'::jsonb)
where student_id=1
and not emails @> '["j.doe@email.com", "john@email.com"]'::jsonb

Test it in db<>fiddle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is boost::mutex faster than std::mutex as of vs2013? Today I wrote some code to test the performance of mutex.
This is the boost(1.54) version, compiled on vs2010 with O2 optimization:
boost::mutex m;
auto start = boost::chrono::system_clock::now();
for (size_t i = 0; i < 50000000; ++i) {
    boost::lock_guard<boost::mutex> lock(m);
}
auto end = boost::chrono::system_clock::now();
boost::chrono::duration<double> elapsed_seconds = end - start;
std::cout << elapsed_seconds.count() << std::endl;

And this is the std version, compiled on VS2013, with O2 optimization too:
std::mutex m;
auto start = std::chrono::system_clock::now();
for (size_t i = 0; i < 50000000; ++i) {
    std::lock_guard<std::mutex> lock(m);
}
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << elapsed_seconds.count() << std::endl;

A bit different but doing just the same thing.
My CPU is Intel Core i7-2600K, my OS is Windows 7 64bit,
and the result is: 0.7020s vs 2.1684s, 3.08 times.
boost::mutex will try _interlockedbittestandset first,
and if it failed, the big cheese WaitForSingleObject will come second,
it's simple to understand.
It seems that std::mutex of VS2013 is much more complex, I have already
tried to understand it but I could not get the point,
why it's so complex ? is there a faster way ?

A: It seems that stl::mutex might only use system calls, which take a LOT of overhead; but boost::mutex implements at least some of its functionality programmatically -- i.e. it tries to avoid system calls whenever possible, which would be the reason for the try _interlockedbittestandset check before WaitForSingleObject.
I don't know the actual internals of MS's stl, but I've seen performance differences like this from examples in an operating systems class.

A: The test is only testing the condition of locking an unlocked mutex without any contentions from other threads.
Let's say the mutex was locked.  After the initial boost try, would it then be better for the thread to spin or block?  It really all depends on the application. And maybe the stl one performs better under heavy load.
When times calls for a highly-efficient mutex, a lock-free alternative to achieve the same goals is worth exploring.


text:
Q: Trigger.IO Facebook hasAuthorised always fails on iOS causing the user to have to re-login every time Every time the user open my app, I call forge.facebook.hasAuthorized to check if the user is already logged-in, and has authorized my app; if that is the case, I automatically log him/her into the app otherwise, I take him/her to a facebook login page.
The expected behaviour is that if the user has the Facebook app installed, and has already authorized my app,  forge.facebook.hasAuthorized will return true (as is the case on Android). For some reason forge.facebook.hasAuthorized always return false on iOS, resulting in the user having to login using Facebook every single time.
I started seeing this behaviour after expending the facebook permission I request the user to authorize.
This is clearly an unacceptable behaviour for apps, which results in a seginficnt decrease in user engagement. Anybody knows how to solve it?

A: Answering my own question just in case somebody made the same silly mistake.
I had trailing spaces if some of my permissions, for example "user_likes " instead of "user_likes". Turns out that for some reason this causes a really weird behaviour.


text:
Q: Highcharts columns(min,max) colors I have a highcharts graph with multiple columns. I want the two columns(min,max) to have different colors. Is that possible?

A: You can set individual color for a point for example in this way:
series: [{
  type: 'column',
  data: [{
    y: 1,
    color: 'purple'
  }, ...]
}]

Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4912/
API Reference: https://api.highcharts.com/highcharts/series.column.data.color


text:
Q: What's the difference between async io and do io in non-main thread? I've read some articles about async IO. But I don't understand the difference between async io and do IO in non-main thread.
I mean, we can do sync IO in a new-born thread, not in the main thread, it will not block the main thread, so why we need async IO?
Thx!

A: The IO subsystem supports multiple concurrent requests. Unless you're doing completely sequential and very large reads and writes you have to use async requests to get the most out of the IO subsystem - blocking the main thread isn't the concern.


text:
Q: Some items are missing when using since parameter I'm facebook graph API user.
Recently found that since parameter works weird.
I'm using that to find all upcoming events and filter out past events for a particular venue.
For instance:
When I use query like this
/v2.5/481931581856759/events?access_token=&limit=5

I getting all events.
But if I add since variable, some events are missing
/v2.5/481931581856759/events?access_token=&limit=5&since=1471468270

In this case can not find an event with start_time "2016-10-28T19:00:00-0700".
Why that happens or I misunderstand something?


text:
Q: Make HTML Button Visible in Email but Invisible in Browser Some background: I have a pre-built system where I can define HTML to notify a user of an event in the system (record created, status change, etc.)  The same notification is sent both as an email and store in the system.  In other words, the same HTML notification is shown in both the browser and the email.  The system is rigid and provides no way for me to define different HTML for the email vs. what is shown in the browser.
Is there a way show a link/button only in the email and not in the browser?  I'm looking for a CSS or HTML way to read the context of where it's being viewed then conditionally display the button.  I do not want to use javascript or a script tag for fear of an email client marking my email as dangerous/spam.
Here's my button for what it's worth:

      Go to incident

A: I don't think that is quite possible with HTML/CSS.
Can send an email and then manipulate/remove button with JavaScript? If you have that option of course.
If I understand you store your content as string or something? Then you can also try to replace button tag with blank before sending an email?


text:
Q: Display bitmap images (.bmp) stored in database on web page I am faced with the task of retrieving image data that was stored as longblob in a MySQL database.
The php script i am using throws errors saying that the image can not be displayed because it contains errors.
Below is my php script:
   $sql = "SELECT Form FROM Forms WHERE id = XXXX";
   $result = mysqli_query($link, $sql) or die (mysqli_error($link));
   $row = mysqli_fetch_assoc($result);
   if(mysqli_num_rows($result) > 0)
   {
       header('Content-Type:image/bmp');
       echo $row['Form'];
   }

Need Help

A: *

*You are missing close quotes on L1 of your SQL.

*In your loop, you are sending the header then sending output and repeating this. That will cause errors. Please send the Content-Type header ONCE and THEN stream your output. Send the header OUTSIDE your loop.


text:
Q: Grunt doesn't update main scss file I have a project that uses GruntJS with grunt-contrib-sass, grunt-contrib-watch and grunt-newer.
My main app.scss file imports a few .scss files with the @import directive like

@import "common/vars.scss";

If I make changes in the main app.scss everything works. The problem is that when I make changes in a file that is being imported (like vars.scss), the app.scss doesn't get updated.
This is my watch task:
    watch: {
      css: {
        files: ['scss/**/*.scss'],
        tasks: ['newer:sass'],
        options: {
          spawn: false,
        }
      }
    }

And this is the sass task itself:
sass: {
      dist: {
        options: {
          style: 'compressed',
          noCache: true
        },
        /* looks for every .scss file in the scss folder (checks nested folders too),
         * compile it and create another file wit the same name in the style folder */
        files: [{
          expand: true,
          cwd: 'scss',
          src: ['**/*.scss'],
          dest: 'style',
          rename: function (dest, src) {
            var folder    = src.substring(0, src.lastIndexOf('/'));
            var filename  = src.substring(src.lastIndexOf('/'), src.length);

            filename  = filename.substring(0, filename.lastIndexOf('.'));

            return dest + '/' + folder + filename + '.css';
          }
        }]
      }
    }

Any idea how to change the Gruntfile.js to cover this scenario too? :) Thanks.

A: Note: This is a minimally modified copy of this comment in an issue on the grunt-newer GitHub page.

I came up with this simple delegation task that does the trick for tasks where you would like to react to changes other than specified in the src property:
grunt.initConfig( {
    delegate: {
        some_other_TASK: {
            src: [ 'some/src/path/**/*.ext' ],
            dest: 'some/dest/path/'
        }
    }
} );

grunt.registerTask( 'delegate', function() {
    grunt.task.run( this.args.join( ':' ) );
} );

A complete example for grunt-contrib-sass would look like the following:
module.exports = function( grunt ) {
    require( 'load-grunt-tasks' )( grunt );

    grunt.initConfig( {
        delegate: {
            sass: {
                src: [ 'scss/**/*.scss' ],
                dest: 'style'
            }
        },

        sass: {
          dist: {
            options: {
              style: 'compressed',
              noCache: true
            },
            files: [{
              expand: true,
              cwd: 'scss',
              src: ['*.scss'],
              dest: 'style',
              ext: '.css'
            }]
          }
        }
    } );

    grunt.registerTask( 'delegate', function() {
        grunt.task.run( this.args.join( ':' ) );
    } );
};

You just have to call newer:delegate:sass (via CLI, or some other task). grunt-newer checks the files given in the according delegate target (where I have the globbing pattern **/ included). If there are new files found (also .scss files in subfolders), the according sass task (with the given target)  will be called.
I'm unsure, though, if making a separate grunt plugin would be of use here.

Edit: I recently released the above code (cleaned up) as separate npm package grunt-delegate.

A: I think your watch tasks variable is backwards, you can check by opening terminal, going to the directory you would normally run grunt watch but try running newer:sass if that doen't work, try sass:newer if the later works change that line in your watch settings.
Also, if you only have one sass task you can just change it to:
watch: {
      css: {
        files: ['scss/**/*.scss'],
        tasks: ['sass']
        options: {
          spawn: false
        }
      }
    }

Just as a side note, it seems that your sass has needlessly complicated rename function, if you're just trying to take scss/**/*.scss and turn them into style/**/*.css you should be able to use this (taken from the grunt-contrib-sass readme):
grunt.initConfig({
  sass: {
    dist: {
      files: [{
        expand: true,
        cwd: 'scss',
        src: ['**/*.scss'],
        dest: 'styles',
        ext: '.css'
      }]
    }
  }
});

if you have files that use multiple dots eg: file.src.scss add extDot: 'last' to the files array


text:
Q: Форма связи JQUERY AJAX $("form").submit(function() {
    var th = $(this);
    $.ajax({
        type: "POST",
        url: "mail.php",
        data: th.serialize()
    }).done(function() {
        alert("Thank you!");
        setTimeout(function() {
            th.trigger("reset");
        }, 1000);
    });
    return false;
});

Есть скрипт для отправки формы, подскажите, как вместо алерта вывести скрытый див с благодарностями?

A: Добавить на страницу тег div

Thank you!

Добавить скрипт
$("form").submit(function() {
    var th = $(this);
    $.ajax({
        type: "POST",
        url: "mail.php",
        data: th.serialize()
    }).done(function() {
        $('#hiddiv').show();
        setTimeout(function() {
            th.trigger("reset");
        }, 1000);
    });
    return false;
});

Добавить в css
#hiddiv {
    display: none;
}


text:
Q: Django is failing to save data related to User table. It says it doesn't have `mymodel_set` attribute I have a model linked to Django User model but when I try saving to that model using User instance, it says 'User' object has no attribute 'mymodel_set'
My models.py:
from django.contrib.auth.models import User
from django.db import models

class MyModel(models.Model):
    user = models.OneToOneField(User, blank=True, null=True, related_name='mymodel')
    name = models.CharField(max_length=14, blank=True, null=True)

My views.py:
from django.contrib.auth.models import User
from myapp.models import mymodel

def register(request):
    #gets data here from template
    user = User(username=reg_username, password=reg_password)
    user.save()
    user.mymodel_set.create(name= display_name)
    return HttpResponse('Success')

A: If the related object existed, you would use mymodel, but it does not exist and the relationship is void, so it cannot be accessed via the user. Create it first and set the relationship to that user:
mymodel = MyModel.objects.create(name=display_name, user=user)
#                                                   ^^^^ set related user

The _set suffix is usually used for reverse ForeignKey relationships and not for OneToOne relationships.
Also note that the related_name on the user field was already specified as mymodel, and the related field can now be accessed from the User model via  user.mymodel


text:
Q: Replace a keyword in a web page with a hyperlink avoiding a and h tags I have the following script that will replace keywords within a website with a hyperlink, but it's screwing up hyperlinks that already contain the keyword. How can I avoid replacing keywords that are within a and h tags?

You can see an example here:  https://slybaldguys.com/keywordtest2.html


text:
Q: Condition of two hyperbolas do not intersect Given two hyperbolas h1(with foci and center) and h2(with foci and center), In what condition these hyperbolas will not intersect to each other?. I can get the condition when h1 and h2 are standard hyperbola (parallel to axis and the center is the origin). I want to find the condition when both of them are not standard hyperbola. Thanks

A: Let $x^2-y^2=1$ be the first hyperbola.

*

*Re-scaling
$$x^2-y^2=c^2 \tag{$c^2 \ne 1$}$$

*Conjugate
$$y^2-x^2=c^2$$

*Translation
\begin{align*}
  (x-h)^2-(y-k)^2 &= 1 \\
  2(ky-hx)+h^2-k^2 &= 0 \\
  x &= \frac{h^2-k^2+2ky}{2h} \\
  (h^2-k^2+2ky)^2-4h^2 y^2 &= 4h^2 \\
  4(h^2-k^2)y^2-4k(h^2-k^2)y+4h^2-(h^2-k^2)^2 &= 0 \\
  \Delta & < 0 \\
  k^2(h^2-k^2)^2-(h^2-k^2)[4h^2-(h^2-k^2)^2] & < 0 \\
  h^2(h^2-k^2)(h^2-k^2-4) &< 0 \\
\end{align*}
$$\fbox{$0<h^2-k^2<4$}$$

A: use the answer of this question to get two equations, set them inequal to each other, then that is your condition, swap them back to focal model.
PS: it might be easier to answer in polar or bipolar coordinates, as they seem more suitable for parabola solving problems

A: Let us consider the reference equilateral hyperbola with equation $xy=1$ (see blue curve on graphics below). Any rectangular hyperbola can be obtained from the reference with a rotation (angle $\theta$) followed by a translation (vector $\binom{a}{b}$). One should obtain the following result :

*

*if $\theta\neq0$, there are intersection points.

*If $\theta=0$, the only translations that give no intersection point are with vector $k\binom{1}{1}$ for $-2<k<2$
(see the example of the magenta curve).
I thought I have a proof but it is not the case.


text:
Q: Keep a printer-history for objects with a specific interface in java I'm making a printer-class where I need to keep track of the print-history of objects with the Employee interface.
public void printDocument(String document, Employee employee) {
        System.out.println(document);

    }

How could I store the history of an employee in a good way, so I can return the print-history of a specific employee with a method like
public List<String> getPrintHistory(Employee employee) {

    }

I have tried storing the print-history of objects in a specific class with the employee interface in a list. The problem is that I want a more general method where I store the information in the Printer class, so I won't have to make a field for print-history for all the classes with the employee interface.


text:
Q: Simple multithreading program with emscripten I am trying to create a simple program with thread support using Emscripten:
#include <stdio.h>
#include <pthread.h>

void *myThreadFun(void *vargp) {
  printf("From Thread \n");
  return NULL;
}

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

    pthread_t tid;
    printf("Before Thread\n");
    pthread_create(&tid, NULL, myThreadFun, NULL);
    printf("Before join\n");
    pthread_join(tid, NULL);
    printf("After Thread\n");

    return 0;
}

I am executed it in Firefox and I compile using -s USE_PTHREADS=1.
This is the output I got in the console:
Before Thread
Preallocating 1 workers for a pthread spawn pool.
Before join

But I expected:
Before Thread
Preallocating 1 workers for a pthread spawn pool.
Before join
After Thread

It is like the thread is not ending. Am I missing something?

A: I had the same issue. I fixed it by compiling with -s PTHREAD_POOL_SIZE=x with x = number of thread created.


text:
Q: Making a Table Row clickable I wonder what the best way to make an entire tr clickable would be?
The most common (and only?) solution seems to be using JavaScript, by using onclick="javascript:document.location.href('bla.htm');" (not to forget: Setting a proper cursor with onmouseover/onmouseout).
While that works, it is a pity that the target URL is not visible in the status bar of a browser, unlike normal links.
So I just wonder if there is any room for optimization? Is it possible to display the URL that will be navigated to in the status bar of the browser? Or is there even a non-JavaScript way to make a tr clickable?

A: With jQuery you can do something along these lines:
$('tr').click(function () {
  $(this).toggleClass('highlight_row');
});

Then add a highlight_row to your CSS file and that row will change its class to highlight_row.  You could swap out whatever you want to do in that line (as well as change $('tr') to fit your specific row.

A: I have found this solution which works quite well:
$(document).ready(function() {
    $('#example tr').click(function() {
        var href = $(this).find("a").attr("href");

        if(href) {
            window.location = href;
        }
    });
});

Just don't forget to style the cursor as a pointer on tr:hover
#table tr:hover {cursor: pointer;}

Source: http://www.electrictoolbox.com/jquey-make-entire-table-row-clickable/

A: "
The most common (and only?) solution seems to be using JavaScript, by using onclick="javascript:document.location.href('bla.htm');" (not to forget: Setting a proper cursor with onmouseover/onmouseout).
"
The onclick-command should look like this:
onclick="window.location.href='bla.html';"

And it isn't necessary to do anything onmouseover/-out about the cursor as a cursor-property only works when the mouse is hovering the element:
style="cursor:pointer;"

A: If you don't want to use javascript, you can do what Chris Porter suggested by wrapping each td element's content in matching anchor tags. Then set the anchor tags to display: block and set the height and line-height to be the same as the td's height. You should then find that the td's touch seamlessly and the effect is that the whole row is clickable. Watch out for padding on the td, which will cause gaps in the clickable area. Instead, apply padding to the anchor tags as it will form part of the clickable area if you do that.
I also like to set the row up to have a highlight effect by applying a different background color on tr:hover.
Example
For the latest Bootstrap (version 3.0.2), here's some quick CSS to show how this can be done:
table.row-clickable tbody tr td {
    padding: 0;
}

table.row-clickable tbody tr td a {
    display: block;
    padding: 8px;
}

Here's a sample table to work with:

            Column 1
            Column 2
            Column 3

Here's an example showing this in action.

A: Another approach is to actually linkify the contents of each cell. You could change the style if necessary so they don't look like traditional links.
Note that what you are trying to do does break the intuitive user experience a little bit. It needs to be clear that clicking on a row does something. I usually prefer to put an icon at the edge of each row (a magnifying glass, etc.) which drills into a new page.

A: Fortunately or unfortunately, most modern browsers do not let you control the status bar anymore (it was possible and popular back in the day) because of fraudulent intentions.
Your better bet would be a title attribute or a javascript tooltip.

A: If your table does not have links inside, following trick should work.
Put entire table into a link and change the href attribute of the link in rows onmouseover events.
Demo code:

...

first row

second row

A: I realise this is an old thread with a perfectly legit solution in Alice's answer. There is however also a way to do this without javascript AND without duplicating your link * the number of columns AND keeping your markup/CSS valid. It took me a while to figure out, so I thought I'd post it here for others that also happen to end up on this thread like I did.
Put the link in the first column:

        Some text
        more text
        more text

This is perfectly fine markup, so your only real issue is getting that link to span the width of your table. I did it like this using pretty standard CSS:
table.search_results a {position:absolute;display:block;width:98%;}

Change the width to whatever you want and in principle you are done and dusted. So that is all relatively easy, however if you, like me, have a fluid/responsive layout, and also some standard styling on your links plus some padding on your tables, you are going to need these rules (copied necessary from above and added extra).
table.search_results td:first-child {padding:0;}
table.search_results a {position:absolute;display:block;width:98%;max-width:1272px;font-weight:normal;color:#000;padding:.5em;}
table.search_results a:hover {background:none;}
table.search_results tr:hover {border-color:#25505b;background:#b5d6dd;}

To explain:
The first rule removes all padding on my first td ONLY. By default the padding on my td is .5em.
The second rule adds the same padding back on the link, otherwise you end up with misaligned cell contents. It also corrects a few standard styles I have on my a to ensure the columns all look the same. You could do this the other way around too (add the link styles to your td).
With the last two rules I get rid of the default hover effect on my links, then put it on the tr for any tables with the right class.
This works in the browsers I care about, but you should of course test in those you care about :) Hope I help save someone some minutes with this writeup!

A: It's a hack but you can add this to your tr:
onmouseover="window.status='http://bla.com/bla.htm'"

don't forget to style your fake links:
tr.clickable {
    cursor: hand;
    cursor: pointer;
}

A: You might also try wrapping the content of your row's cells in an href and using CSS to push the href height/width to the internal bounds of each cell.  The row itself wouldn't be clickable (unless you added additional html to the row) but most of the content space of the row would act like a normal link (cursor, status bar, etc).  I can't remember off hand exactly how I did this before but I was reasonably successful getting this to work.
Edit: A comment asked for more details and they were covered by a later post from another user but I didn't realize that until I looked further into this suggestion and tested it.
If you add "display: block" CSS style tag to the anchor objects in the cells that you want to be clickable it will make the entire cell (minus any padding) act like a button.  The cursor is displayed correctly and it previews the link destination in the status bar.  This is all done with zero javascript.  Good luck.

A: I had that same problem, I solved it by using CSS only. I think it was the best solution for me, because I was using it in JSF also.
Just assign the style class to the table and you are good to go....
Here it goes:
CSS:
.myDataTable {
    background: 444;
    width: 100%;
}

.myDataTable thead tr {
    background-image: url('../img/tableHeader.jpg');
}

.myDataTable thead tr th {
    height: 28px;
    font-size: 14px;
    font-family: tahoma, helvetica, arial, sans-serif;
    padding-left: 5px;
}

.myDataTable thead tr th img {
    padding-right: 5px;
    padding-top: 1px;
}

.myDataTable thead tr td {
    height: 15px;
    font-size: 11px;
    font-weight: bold;
    font-family: tahoma, helvetica, arial, sans-serif;
    padding-left: 5px;
}

.myDataTable tbody {
    background: #f2f5f9;
}

.myDataTable tbody tr:nth-child(even) td,tbody tr.even td {
    background: #e2ebf4;
    font-size: 12px;
    padding-left: 5px;
    height: 14px;
}

.myDataTable tbody tr:nth-child(odd) td,tbody tr.odd td {
    background: #f7faff;
    font-size: 12px;
    padding-left: 5px;
    height: 14px;
}

.myDataTable tbody tr:hover td {
    background-color: #e7e7e7;
}

.myDataTable tbody tr td {
    height: 14px;
    padding-left: 5px;
    font-size: 12px;
}

.myDataTable tbody tr td a {
    color: black;
    text-decoration: none;
    font-size: 12px;
    display: block;
}

.myDataTable thead tr th a {
    color: black;
    text-decoration: none;
    font-size: 12px;
    display: inline;
}

Your table structure should be:

   Heading 1
   Heading 2

   Data    1
   Data    2

A: If your targeted browsers all support CSS Table display styles, you can use Javascript to wrap each row in an  tag styled to function as a
.
Here's some JS code using jQuery to make it happen: (jsfiddle)
$(function() {
  $('.table-linked').each(function() {
    var table, tbody;
    table = this;
    tbody = $('tbody', this);
    tbody.children().each(function() {
      var href, row;
      row = $(this);
      href = row.attr('data-href');
      $('').append(row).appendTo(table);
    });
    tbody.remove();
  });
});

This code will transform a table that looks like this:

a	1

b	2

Into this DOM structure in the browser:

a	1

b	1

Browsers don't seem to be capable of parsing this structure as HTML code (and needless to say it won't validate), it needs to be constructed using JS

A: Marko Dugonjic, in his blog maratz.com, explained how you detect a table row index with Javascript.  In his example, when you mouse over any cell in a row, the entire row is highlighted.
See example,
http://webdesign.maratz.com/lab/row_index/
and his article,
http://www.maratz.com/blog/archives/2005/05/18/detect-table-row-index-with-javascript/
With a change, you can adapt this further by placing an onclick action.

A: If you're already relying on javascript for the click, then you can also use javascript to show the url in status area, change the cursor, or do other things so it looks more like a link.  Of course, the browser may ignore the code that sets the status area.


text:
Q: How to best approach scalable test infrastructure compatible with API invocation validation? I am currently working on writing a test helper that would take an object instance and run it through a sequence of API invocations and validate the corresponding results. Please note that the API invocations results can vary based on the current state of the object instance. Currently, my initial stab at this looks like the following:
enum class API
{
    DoWork1,
    DoWork2,
};

struct DoWork1_Data
{
    bool bSlowPath;
};

struct DoWork2_Data;
{
    unsigned Seed;
};

struct APIOperation
{
    API Api;
    void* pData;
    unsigned Size;
};

/* There will be many of this per combination of APIs that we want to validate */
std::vector<APIOperation> BuildAPIOperations()
{
    std::vector<APIOperation> APIOperations;

    DoWork1_Data DoWork1Data = {};
    DoWork1Data.bSlowPath = true;
    APIOperation Op1 = {};
    Op1.Type = API::DoWork1;
    Op1.pData = &DoWork1Data;
    Op1.Size = sizeof(DoWork1Data);
    APIOperations.push_back(Op1);

    DoWork2_Data DoWork2Data = {};
    DoWork2Data.Seed = 0xDEADBEEF;
    APIOperation Op2 = {};
    Op2.Type = API::DoWork2;
    Op2.pData = &DoWork2Data;
    Op2.Size = sizeof(DoWork2Data);
    APIOperations.push_back(Op2);

    return APIOperations;
}

void ExerciseAPIOperations(IUnknown *pObject, std::vector<APIOperation> & APIOperations)
{
    for(unsigned i=0; i < APIOperations.size(); i++)
    {
        switch (APIOperations[i].Type)
        {
            case API::DoWork1:
                {
                    /* validation of pData */
                    DoWork1_Data *pData = static_cast<DoWork1_Data*>(APIOperations[i].pData);
                    pObject->DoWork1(pData->bSlowPath);
                    /* validation of API DoWork1 behavior */
                }
                break;
            case API::DoWork2:
                {
                    /* validation of pData */
                    DoWork2_Data *pData = static_cast<DoWork2_Data*>(APIOperations[i].pData);
                    pObject->DoWork2(pData->Seed);
                    /* validation of API DoWork2 behavior */
                }
                break;
        }
    }
}

I would appreciate general feedback, but more specifically, I am mainly interested to explore improvements in the following two aspects, and would love to hear thoughts on that:

*

*Instead of N number of BuildAPIOperations(), I was hoping to define a global array of all these different cases, so all the permutations will be clearer to understand and can avoid some amount of code duplication. However, this doesn't seem to fit well with the fact that each API can potentially have different set of parameters and defining that all upfront will probably result in a table that's fairly onerous to parse.

*I am not a big fan of defining a custom struct per API (i.e. DoWork1_Data) and then casting these pointers to void* and then back. However, I found them necessary to support a test helper that's compatible with any APIs that this object instance can support.
Please let me know. Thanks in advance.


text:
Q: How to add [today's date +1 day] I'm currently using this code in wordpress:
// [date]
function displaydate(){
return date('l, F jS, Y');
}
add_shortcode('date', 'displaydate');
// end date

--
What I want to do is add another shortcode that would display todays date +1day.
So I could write something like this:
'...offer runs out [todays date +1day]'
Anyone know how to do this?

A: The easiest way in PHP would be using the strtotime function.
As for your code you would add:
return date('l, F jS, Y', strtotime('+1 day'));

Based on your original code a 'shortcode' called 'tomorrow' would look like this:
// [tomorrow]
function displaydate_tomorrow(){
    return date('l, F jS, Y', strtotime('+1 day'));
}
add_shortcode('tomorrow', 'displaydate_tomorrow');
// end tomorrows date

A: The PHP documentation is really comprehensive when it comes to date manipulation, so finding a suitable solution should be quite easy. Here's one possible solution:
function displaydate($plus_days) {
  return date('l, F jS, Y', strtotime('+' . $plus_days . ' day'));
}

http://uk3.php.net/manual/en/function.strtotime.php

A: This was the only direct answer to this question that I could find and I thank you very much for supplying the answer.
I also played with the variables as I wanted to show an accurate date and by changing day to hours and entering -5 to GMT time as I'm in Toronto area, it worked beautifully!
For newbies, the full code that I am using is as follows:
 function displaydate(){
     return date('l, F jS, Y', strtotime('-5 hours'));

 }
 add_shortcode('date', 'displaydate');

Then, I enter the following on the page where I wish the date to appear on my wordpress pages as:
Last update of this page: [date]

and the result is perfect.

A: I used this snippet to count simple estimated delivery date. It's based on dianovich snippet but his(her) snippet returns error. This works fine:
function displaydate( $atts ) {
    $atts = shortcode_atts( array(
        'day'   => '0'
    ), $atts );
    $plus_days = $atts['day'];
    return date_i18n('j F Y', strtotime('+' . $plus_days . ' day'));
}
add_shortcode('delivery_date', 'displaydate');

Shortcode to show:
[delivery_date day="5"]


text:
Q: Installing Eclipse (new) on Ubuntu 16.04 (Xenial Xerus) I've been for past day trying to install any newer version of Eclipse than what the Software Center has and every attempt has failed.
I can't seem to follow any given solutions without an error somewhere.
I'm running Ubuntu 16.04 (Xenial Xerus) with mate. I have JavaSDK installed, and I just removed the Software Center version since I saw it was bit old...
All the gksudo commands just give me an error and doesn't do anything just says:
gedit eclipse.desktop
Gtk-Message: Failed to load module "topmenu-gtk-module"

I have three different Eclipse install folders extracted to my /opt folder, but I can't run any of them, it just says "open" on 2 and in one I can select "run", but it doesn't do anything.
Is there some easy way to install this software? As in note years old version of it?

A: I am assuming you extracted the Eclipse tar files in /opt. If yes, then try making the Eclipse file (the one which says 'open') executable with sudo chmod +x eclipse in the terminal.


text:
Q: Bootstrap CSS Table Not Showing When Dynamically Created I have a jquery script that on the occurrence of an event changes a div and adds a table as shown in the following code.
The page is based on Bootstrap CSS but the table is not formatted as it should.
What am i doing wrong?
$('#regionId').html('
');

for (var i = 0; i < data.length; i++) {
$('#regionId').append('
'+ data[i].field + ' 	 ' + data[i].field2+ '
');

}

$('#regionId').append('
');

A: try this demo
$('#regionId').html('

');
    for (var i = 0; i < data.length; i++) {
        $('#regionId tbody').append('
'+ data[i].field
                        + ' 	 '
                            + data[i].field2
                            + '
')
    }


text:
Q: Is there a language that employs a Computer Algebra System for additional features and optimizations? For example, imagine a function like this:
int solveSomeEquation(int y)
{
    y = (int x) * 2;
    return x;
}

Using symbolic algebra, the compiler would determine that x = y / 2. Even better, it would complain that int is not sufficient for storing the result of y / 2. Imagine this functionality extending to solving ODEs with constraints and/or boundary conditions, and integration using symbolic or numeric methods (at run time) where needed. I, for one, would love to see something like this:
int areaOfUnitSemiCircle()
{
    auto semiCircleFunc = [](double x){ return abs((1 - x^2)^0.5); };
    semiCircleFunc = (auto semiCircleIntegralFunc)'; // single quote means derivative
    return semiCircleIntegralFunc(1) - semiCircleIntegralFunc(-1);
}

simplified to:
int areaOfUnitSemiCircle()
{
    return Pi/2;
}

Furthermore, it would be able to not only simplify expressions locally inside a function, but perform whole program optimization. It could rearrange expressions to improve numerical stability (reduce the effect of floating point error) or even eliminate them entirely by using a different representation. BigInt, IEEE1394's quadruple-precision float, sets defined by a predicate, integration over piecewise functions. Probably loads more could be done.
Such a thing is possible, no? I know you can perform stuff like this using Mathematica's or MatLab's programming language functions, but they are called BY the source code. I want it to be applied TO the source code by the compiler. (Do these languages have this sort of thing? I don't know.) I love using Mathematica at work when I have an excuse, but then I end up with magical-looking functions in C++ that make no sense without referring to an external Mathematica notebook. I'd like to be able to be a mathematician and a programmer in one language, one environment. Does such a thing exist?

A: Well, Maxima [1] is certainly capable of constructing and manipulating expressions, and making functions out of them. Functions are just expressions too, so it's straightforward to take some expression, manipulate it, construct a function, and call the function, and doing all of these things with variables instead of specific values. For example, here is your circle area function:
(%i1) display2d : false $
(%i2) a(r) := ''(4 * integrate (sqrt (r^2 - x^2), x, 0, r));
Is r positive, negative or zero?
p;
(%o2) a(r):=%pi*r^2
(%i3) a(10);
(%o3) 100*%pi
(%i4) a(h);
(%o4) %pi*h^2

The general idea of a programming language being able to work on itself originated in Lisp, which is still a good language for such exercises. Maxima is implemented in Lisp. I recommend learning Lisp, you can learn a lot about programming in general from it even if you end up working with other languages.
[1] http://maxima.sourceforge.net


text:
Q: How to null coalesce for Boolean condition? I'm trying to safely check if an IList<> is not empty.
var Foo = Bar.GimmeIListT(); // Returns an IList<SomeObject>
if (Foo?.Any())
    // Do cool stuff with items in Foo

But there is an error with the condition:

Cannot implicitly convert 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

So it seems the condition evaluates to a nullable bool, so I try
if (Foo?.Any().Value())

But this is no good either:

'bool' does not contain a definition for 'Value' and no extension .... blah blah blah

So in the first instance it complains that it is a nullable bool but in the second it complains that it isn't.
As another avenue I try:
if (Foo?.Any() == true)

This works - but it shouldn't because this uses an implicit conversion which the first message said it didn't want!
What is going on? What is the correct way to do this?

A: Edit:
It seems like the cause of the bool? is the Foo?.Any() itself. If you do not want to compare it with true, I would suggest you to have temporary variable:
bool? any = Foo?.Any();
if (any.Value) ...

Alternatively, if the object is a class, you could use FirstOrDefault() != null as checking condition. It won't take time because it will only get the first object:
if (Foot?.FirstOrDefault() != null)...

I will go with the temporary variable or the Foo?.Any() == true option though.
Original:
Note: It is to my surprise too that if (a?.Any()) cannot be followed by .Value() or .Value(!).
I think what you need is Value (property) without () (method):
if (Foo?.Any()?.Value) ...

bool? has .Value (property) which is a bool.

A: Any() returns bool but Foo?.Any() will return bool?
So Foo?.Any().Value won't compile since Any() returns a bool that doesn't have a member Value.
If Foo is null, Any() won't be executed because the statement will return null without interpreting the part behind the ?. operator.
But if you put Foo?.Any() in paranthesis, you are able to work with the result of type bool? and check it via Value or GetValueOrDefault():
(Foo?.Any()).GetValueOrDefault()

A: You can  compare with the bool? if you use ==, that's indeed the best/simplest approach:
if (Foo?.Any() == true) ...

as to the why it's not allowed in an if but with ==, Jon Skeet can explain it much better:

There's no implicit conversion from Nullable<bool> to bool. There is
an implicit conversion from bool to Nullable<bool> and that's what
happens (in language terms) to each of the bool constants in the first
version. The bool operator==(Nullable<bool>, Nullable<bool>) operator
is then applied. (This isn't quite the same as other lifted operators - the result is just bool, not Nullable<bool>).
In other words, the expression fred == false is of type bool,
whereas the expression fred is of type Nullable<bool> hence you
can't use it as the "if" expression.

So the if allows only bool and you have a bool?, but the == operator converts the bool to a bool? and you can compare two bool?.

A: more syntactic sugar, the null-coalescing operator. C# 8.0 or later
if (Foo?.Any() ?? false) { }


text:
Q: How to extend existing interface IMessageFilter with TInterfacedObject? I want to implement IOleMessageFilter as described here:
How to: Fix 'Application is Busy' and 'Call was Rejected By Callee' Errors
I have found a Delphi implementation which works fine:
`EOleException: Call was rejected by callee` while iterating through `Office.Interop.Word.Documents`
(See UPDATE #1 in the answer)
The implementation looks like this:
type
  TOleMessageFilter = class(TInterfacedObject, IMessageFilter)
  public
    // IMessageFilter
    function HandleInComingCall(dwCallType: Longint; htaskCaller: HTask;
      dwTickCount: Longint; lpInterfaceInfo: PInterfaceInfo): Longint;stdcall;
    function RetryRejectedCall(htaskCallee: HTask; dwTickCount: Longint;
      dwRejectType: Longint): Longint;stdcall;
    function MessagePending(htaskCallee: HTask; dwTickCount: Longint;
      dwPendingType: Longint): Longint;stdcall;

    // TOleMessageFilter
    procedure RegisterFilter;
    procedure RevokeFilter;
  end;

implementation

function TOleMessageFilter.HandleInComingCall(dwCallType: Integer; htaskCaller: HTask; dwTickCount: Integer; lpInterfaceInfo: PInterfaceInfo): Longint;
begin
  Result := 0;
end;

function TOleMessageFilter.MessagePending(htaskCallee: HTask; dwTickCount, dwPendingType: Integer): Longint;
begin
  Result := 2 //PENDINGMSG_WAITDEFPROCESS
end;

function TOleMessageFilter.RetryRejectedCall(htaskCallee: HTask; dwTickCount, dwRejectType: Integer): Longint;
begin
  Result := -1;
  if dwRejectType = 2 then
    Result := 99;
end;

procedure TOleMessageFilter.RegisterFilter;
var
  OldFilter: IMessageFilter;
  NewFilter: IMessageFilter;
begin
  OldFilter := nil;
  NewFilter := TOleMessageFilter.Create as IMessageFilter;
  CoRegisterMessageFilter(NewFilter,OldFilter);
end;

procedure TOleMessageFilter.RevokeFilter;
var
  OldFilter: IMessageFilter;
  NewFilter: IMessageFilter;
begin
  OldFilter := nil;
  NewFilter := nil;
  CoRegisterMessageFilter(NewFilter,OldFilter);
end;

This exact Delphi code is found on many other sites on the web. So far so good. I have only changed the class name to TOleMessageFilter instead of IOleMessageFilter.
The usage is however a bit annoying.
var
  Filter: TOleMessageFilter;

Filter := TOleMessageFilter.Create;
Filter.RegisterFilter;
...
Filter.RevokeFilter;
Filter.Free;

What I want is, Filter to be declared as interface e.g.  IOleMessageFilter.
var
  Filter: IOleMessageFilter;

Filter := TOleMessageFilter.Create as IOleMessageFilter;
Filter.RegisterFilter;
...
Filter.RevokeFilter;
Filter := nil;

and have the benefit of auto freeing the TInterfacedObject.
How do I create a new IOleMessageFilter which "derives" from IMessageFilter but still has new methods RegisterFilter() and RevokeFilter(), is implemented as TOleMessageFilter = class(TInterfacedObject, IOleMessageFilter), and still be able to use it also with CoRegisterMessageFilter() which expects IMessageFilter (used in the RegisterFilter() method)?
I have tried to declare:
IOleMessageFilter = interface(IMessageFilter)
  procedure RegisterFilter;
  procedure RevokeFilter;
end;

TOleMessageFilter = class(TInterfacedObject, IOleMessageFilter)
...
end;

But then calling CoRegisterMessageFilter throws an error:

Interface not supported.

EDIT:
I have also tried to declare TOleMessageFilter as:
TOleMessageFilter = class(TInterfacedObject, IMessageFilter, IOleMessageFilter)

Which "seems" to work, but I'm not sure it's correct approach.

A: Split up both interfaces and let TOleMessageFilter keep a reference to the actual message filter, as a bonus you don't have to call RegisterFilter and RevokeFilter anymore as this will done from constructor/destructor:
program SO46913922;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  ActiveX,
  Windows,
  SysUtils;

type
  IOleMessageFilter = interface
  ['{0ECA5DA7-F6C7-4D21-8FD3-872558F88CBE}']
    procedure RegisterFilter;
    procedure RevokeFilter;
  end;

  TMessageFilter = class(TInterfacedObject, IMessageFilter)
  public
    // IMessageFilter
    function HandleInComingCall(dwCallType: Longint; htaskCaller: HTask;
      dwTickCount: Longint; lpInterfaceInfo: PInterfaceInfo): Longint;stdcall;
    function RetryRejectedCall(htaskCallee: HTask; dwTickCount: Longint;
      dwRejectType: Longint): Longint;stdcall;
    function MessagePending(htaskCallee: HTask; dwTickCount: Longint;
      dwPendingType: Longint): Longint;stdcall;
  end;

  TOleMessageFilter = class(TInterfacedObject, IOleMessageFilter)
  private
    Filter : IMessageFilter;
    procedure RegisterFilter;
    procedure RevokeFilter;
  public
    constructor Create;
    destructor Destroy; override;
  end;

function TMessageFilter.HandleInComingCall(dwCallType: Integer; htaskCaller: HTask; dwTickCount: Integer; lpInterfaceInfo: PInterfaceInfo): Longint;
begin
  Result := 0;
end;

function TMessageFilter.MessagePending(htaskCallee: HTask; dwTickCount, dwPendingType: Integer): Longint;
begin
  Result := 2 //PENDINGMSG_WAITDEFPROCESS
end;

function TMessageFilter.RetryRejectedCall(htaskCallee: HTask; dwTickCount, dwRejectType: Integer): Longint;
begin
  Result := -1;
  if dwRejectType = 2 then
    Result := 99;
end;

procedure TOleMessageFilter.RegisterFilter;
var
  OldFilter: IMessageFilter;

begin
  OldFilter := nil;
  Filter := TMessageFilter.Create;
  CoRegisterMessageFilter(Filter,OldFilter);
end;

procedure TOleMessageFilter.RevokeFilter;
var
  OldFilter: IMessageFilter;
  NewFilter: IMessageFilter;
begin
  OldFilter := nil;
  NewFilter := nil;
  CoRegisterMessageFilter(NewFilter,OldFilter);
  Filter := nil;
end;

constructor TOleMessageFilter.Create;
begin
 RegisterFilter;
end;

destructor TOleMessageFilter.Destroy;
begin
 RevokeFilter;
 inherited;
end;

var
  Filter :  IOleMessageFilter;

begin
  try
   CoInitialize(nil);
   Filter := TOleMessageFilter.Create;
   Readln; // do something
   Filter := nil;
  finally
   CoUninitialize();
  end;
  Readln;
end.


text:
Q: Ransack search for far away tables? I want to search orders by tags, but tags are associated with customers.... is it possible to do that with Ransack?
Order.rb
Class Order < ActiveRecord::Base
belongs_to :customer
 ....

Customer.rb
Class Customer < ActiveRecord::Base
has_many :orders
has_many :customers_tags
has_many :tags, through: :customers_tags
 ....

Tag.rb
Class Tag < ActiveRecord::Base
has_many :customers_tags
has_many :customers, through: :customers_tags
 ....

A: Yes, you can search through multiple associations. Just reference them as you would in the association name (plural for has_many, singular for belongs_to).
So in your example, searching for a field fieldname, you would use:
customer_tags_fieldname_cont
(Replace fieldname with whatever field you want to search.)


text:
Q: Return Promises instead of Async I want to return data which will look something like this
[
  shops: {
    id,
    products:[{Object}, {Object}]
  },
  shops: {
    id,
    products:[{Object}, {Object}]
  }
]

So I have list of shop ids on which I need to iterate and get the products for each shop and append it and then return.
This is how I have done
const shops = response.data
const respToSend = []
async.eachSeries(shops, (shop, callback) => {
  const id = shop.shop_id
  const shopObj = {
    id
  }

  // Fetch products of each Shop.
  getProductList(id)
    .then((responseData) => {
      shopObj.products = responseData.data.products
      respToSend.push(shopObj)
      callback()
    })
    .catch(() => {
    })
}, () => {
  return respToSend
})

As you can see that I am using async node module for doing the async task but the application requires from me to return response as Promises which will then be resolved otherwise it prints null. How can I achieve this using promises? I am new to promises so sorry for any typo.

A: try Promise.all(iterable)
Promise.all(shops.map(shop => getProductList(shop.shop_id)
    .then(products => ({id: shop.shop_id, products}))
    .then(/* actions for each shop */))
  .then(shops => {
    /* actions for array of shop objects */
    respToSend = shops;
  })


text:
Q: How to search a string in inner array using mongodb? How to search value in multidimensional array,
for example I want to search example keyword in the following data in mongodb
I used to fetch all data from command
>db.info.find()
{
    "_id" : ObjectId("4f74737cc3a51043d26f4b90"),
    "id" : "12345",
    "info" : [
            {
                    "sno" : 1,
                    "name" : "ABC",
                    "email" : "abc@example.com"
            },
            {
                    "sno" : 2,
                    "name" : "XYZ",
                    "email" : "xyz@example.com"
            },
            {
                    "sno" : 3,
                    "name" : "XYZ",
                    "email" : "xyz@demo.com"
            },
            {
                    "sno" : 4,
                    "name" : "ABC",
                    "email" : "abc@demo.com"
            },
            {
                    "sno" : 5,
                    "name" : "Rohan",
                    "email" : "rohan@example.com"
            }
    ]
}

Now, to find data having example I used command
>db.info.find({"info.email":"example"})
and it gives
{
    "_id" : ObjectId("4f74737cc3a51043d26f4b90"),
    "id" : "12345",
    "info" : [
            {
                    "sno" : 1,
                    "name" : "ABC",
                    "email" : "abc@example.com"
            },
            {
                    "sno" : 2,
                    "name" : "XYZ",
                    "email" : "xyz@example.com"
            },
            {
                    "sno" : 3,
                    "name" : "XYZ",
                    "email" : "xyz@demo.com"
            },
            {
                    "sno" : 4,
                    "name" : "ABC",
                    "email" : "abc@demo.com"
            },
            {
                    "sno" : 5,
                    "name" : "Rohan",
                    "email" : "rohan@example.com"
            }
    ]
}

But I want only 3 out of 5 sub rows like
{
    "_id" : ObjectId("4f74737cc3a51043d26f4b90"),
    "id" : "12345",
    "info" : [
            {
                    "sno" : 1,
                    "name" : "ABC",
                    "email" : "abc@example.com"
            },
            {
                    "sno" : 2,
                    "name" : "XYZ",
                    "email" : "xyz@example.com"
            },
            {
                    "sno" : 5,
                    "name" : "Rohan",
                    "email" : "rohan@example.com"
            }
    ]
}

A: Rohan, MongoDB always returns the whole document that you are searching on. You can't just make it return the array elements in which your keyword was found. If you want to do that, then you need to make sure all all embedded documents in the "info" field are in their own collection. And that might mean that you need to link them back to the original document in your "info" collection. Perhaps something like:
{
    "sno" : 1,
    "name" : "ABC",
    "email" : "abc@example.com"
    "info_id" : "12345",
},

Alternatively, you can of course do post-processing in PHP to obtain only the rows that you want.

A: Perhaps this is a good idea?
http://php.net/manual/en/class.mongoregex.php

A: I tried Map Reduce Function and it works on this type of problems the code is something like that:
Write a map function
  map=function ()
  {
      filter = [];
      this.info.forEach(function (s) {if (/example/.test(s.email)) {filter.push(s);}});
      emit(this._id, {info:filter});
  }

Write a reduce function
  reduce=function(key, values) { return values;}

MapReduce Function
  res=db.info.mapReduce(map,reduce,{out:{inline:1}})

And The Output look likes:
"results" : [
    {
            "_id" : ObjectId("4f9a2de0ea4a65c3ab85a9d3"),
            "value" : {
                    "info" : [
                            {
                                    "sno" : 1,
                                    "name" : "ABC",
                                    "email" : "abc@example.com"
                            },
                            {
                                    "sno" : 2,
                                    "name" : "XYZ",
                                    "email" : "xyz@example.com"
                            },
                            {
                                    "sno" : 5,
                                    "name" : "Rohan",
                                    "email" : "rohan@example.com"
                            }
                    ]
            }
    }
    ],
    "timeMillis" : 1,
    "counts" : {
            "input" : 3,
            "emit" : 3,
            "reduce" : 0,
            "output" : 3
    },
    "ok" : 1,

Now you can find your search data from
   printjson(res.results)

A: Did you try $ (projection)?
db.info.find({"info.email":"example"}, {"info.email.$":1})

document


text:
Q: Wrong Character Set for JSF's h:inputText on first submit (only) In the following form, we try to return a user's input to JSF's h:inputText or PrimeFaces' p:inputText.
We experience strange behavior when non-Latin characters (Japanese, Hebrew, etc. ) are entered:
On first request we get unrecognized character set, but on the second request - we get a correct result.
Input/Output Examples (first run only):

*

*Japanese:
 input = 日
 output = æ¥

*Hebrew:
 input = א
 output = ×
JSF:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.prime.com.tr/ui">
    <body>
        <h:form>
            <h:outputLabel value="Name:"/>
            <h:inputText value="#{newTestController.registeredCustomerFirstName}"/>
            <h:commandButton value="Continue" action="#{newTestController.RegisteredNewCustomer(actionEvent)}"/>
        </h:form>
    </body>
</html>

Backing Bean:
@ManagedBean(name = "newTestController")
@SessionScoped
public class NewTestController {

    private String registeredCustomerFirstName;

    public String getRegisteredCustomerFirstName() {
        return registeredCustomerFirstName;
    }

    public void setRegisteredCustomerFirstName(String registeredCustomerFirstName) {
        this.registeredCustomerFirstName = registeredCustomerFirstName;
    }

    public void RegisteredNewCustomer(ActionEvent actionEvent) throws Exception {
    }
}

A: As commented above - it is needed to define a default-charset for the application server.
For glassfish: add <parameter-encoding default-charset="UTF-8" /> to glassfish-web.xml.
For other application servers see BalusC's blog regarding this issue.

A: This is related to < http://java.net/jira/browse/GLASSFISH-18007 >.  That fix was made to prevent a warning message when we unconditionally set the encoding to UTF-8, which would seem to be what we want, but in this case we felt it safer to not do it.
I've created a related issue in Mojarra, < http://java.net/jira/browse/JAVASERVERFACES-2217 >.  Bottom line: setting the encoding explicitly in the app configuration is the right solution.  The implementation is already doing the right thing.

A: Specifying charset in the config file might be not enough.
Try using p:commandButton instead of h:commandButton. The p:commandButton by default uses ajax, while the h:commandButton does non-ajax submit.


text:
Q: How to remove type in XML while generating? I have 1000 records in text file. My requirement is to insert data into SQL Server. For that, if I can convert to XML or push to script component also fine.
Source Text file consists in this format...
[{"ID":1,"Name":"test1","State":"AP"},{"ID":2,"Name":"test2","State":"KN"},{"ID":3,"Name":"test3","State":null}]

String json = System.IO.File.ReadAllText(@"C:\t1.txt");
byte[] bytes = Encoding.ASCII.GetBytes();
using (var stream = new MemoryStream(bytes))
{
  var quotas = new XmlDictionaryReaderQuotas();
  var jasonreader - JsonReaderWriterFactory.CreateJasonReader(stream,quotas);
  var xml = XDocument.Load(jsonreader);
  xmlDocument xd = new XmlDocument();

  using (steamwriter fs = new streamwriter(@"C:\t.xml");
{
  fs.write(xml);
}
  console.writeLine(xml);
}

Output -
<root type="array"
  <item type="object">
     <ID type="number">1</ID>
     <Name type="string">test1</Name>
     <State type="string">AP</State>
  </item>
<item type="object">
<root type="array"
  <item type="object">
     <ID type="number">2</ID>
     <Name type="string">test2</Name>
     <State type="string">KN</State>
  </item>
<item type="object">
<root type="array"
  <item type="object">
     <ID type="number">3</ID>
     <Name type="string">test3</Name>
     <State type="string"></State>
  </item>
</root>

When am using SSIS XML Source task, am getting columns...
External Columns:
type
text
item_id

Output Columns:
type
text
item_id

Ideally, I should get ID, Name, and State columns. What is the issue? How can I get rid of type in XML?

A: How about using Linq? (using Json.Net)
var jArr = JArray.Parse(File.ReadAllText(filename));
XElement root = new XElement("root");

foreach(JObject jObj in jArr )
{
    root.Add(new XElement("item", jObj.Properties()
                                      .Select(p => new XElement(p.Name,
                                                                p.Value.ToString()))
                                      .ToArray()));
}

var xml = root.ToString();

or using more linq
var jArr = JArray.Parse(File.ReadAllText(filename));
XElement root = new XElement("root");
root.Add( jArr.Cast<JObject>()
              .Select(jObj => new XElement("item", jObj.Properties()
                                                       .Select(p => new XElement(p.Name,
                                                                                p.Value.ToString()))
                                                       .ToArray())));

var xml = root.ToString();


text:
Q: Mirror maker 2.0 backup In case of an issue where mirror maker 2.0 stops replicating messages from source to destination topic, is there a recommended approach to follow/utility(except for restarting the mirror maker instance) that can be used that will minimize the impact on the destination consumers?

A: If the producer to the destination stops, your only option is to restart it.
You need to use external process monitoring / orchestration tools such as supervisor or Kubernetes to restart the process/containers that fail.


text:
Q: RSpec tests fails without factory_girl reload I was having trouble getting one of my spec tests to pass until I forced a reload on the user object after an activation. I'm fairly new to BDD and rails, am I completely misusing factory girl in this instance? Should I have mocked something instead?
For reference I am using the sorcery gem for user activation.
describe "GET activate" do
  context "with valid attributes" do
    it "activates a new user" do
      user = FactoryGirl.create(:pending_user)
      expect {
        get :activate, id: user.activation_token
        user.reload
      }.to change{user.activation_state}.from("pending").to("active")
    end
  end
end

A: I think what's confusing here is how you are triggering activate vs. how you are trying to verify that it worked.
You're activating via the controller get :activate, but then validating via the model user.activation_state.  reload is necessary in this case, because you have to reload the attributes from the database in order to see that activation_state has been changed from pending to active.  get :activate has no affect on your user instance.
To make it more clear you could:

*

*Check for an activation result on the page that activate responds with or check a controller instance variable (there's probably an @user)

*Perform the activation from the model instead.  I assume this could be a unit test that instead calls some user.activate(activation_token) method.  Then, checking the user instance without reload will work.


text:
Q: Using try with resources in multithreaded server in java I'm reading a book "java networking 4th edition" and in the 9th chapter about server sockets while explaining multithreaded server where each client is handled with the single thread it said the following:

Example 9-3 deliberately does not use try-with-resources for the client sockets accepted by the server
  socket. This is because the client socket escapes from the try block into a separate thread.
  If you used try-with-resources, the main thread would close the socket as soon as it got
  to the end of the while loop, likely before the spawned thread had finished using it.

Here is the Example 9-3
import java.net.*;
import java.io.*;
import java.util.Date;
public class MultithreadedDaytimeServer {
public final static int PORT = 13;
public static void main(String[] args) {
    try (ServerSocket server = new ServerSocket(PORT)) {
        while (true) {
            try {
                Socket connection = server.accept();
                Thread task = new DaytimeThread(connection);
                task.start();
            } catch (IOException ex) {}
        }
    } catch (IOException ex) {
        System.err.println("Couldn't start server");
    }
}
private static class DaytimeThread extends Thread {
    private Socket connection;
    DaytimeThread(Socket connection) {
        this.connection = connection;
    }
    @Override
    public void run() {
        try {
            Writer out = new OutputStreamWriter(connection.getOutputStream());
            Date now = new Date();
            out.write(now.toString() +"\r\n");
            out.flush();
        } catch (IOException ex) {
            System.err.println(ex);
        } finally {
            try {
                connection.close();
            } catch (IOException e) {
                // ignore;
            }
        }
    }
}

}
I don't really understand why is this happening, why would main thread want to close the socket from the other thread, is it because socket object was created in the main thread and reference was supplied in thread constructor?

A: What the book is saying is that they chose to do this
try {
    Socket connection = server.accept();
    Thread task = new DaytimeThread(connection);
    task.start();
} catch (IOException ex) {}

instead of
try(Socket connection = server.accept()) {
    Thread task = new DaytimeThread(connection);
    task.start();
} catch (IOException ex) {}

because when use a try-with-resources block, it closes whatever you put in the parentheses try(...) immediately after it is done. But you do not want this to happen. The connection socket is meant to stay open because it is going to be used in the DaytimeThread that was started.

A: The main thread doesn't want to close the resource because the spawned thread executes asynchronously.
Within the try, task.start() begins execution of the thread, but it does not wait for it to finish. Therefore, it is possible (even likely) that the main method will reach the end of its try before DaytimeThread.run() finishes.
If the main method's try was a try-with-resources, the connection would be closed at this time. Then, as the DaytimeThread continues to do its work in another thread, it would attempt to use that connection after it is closed.
But to answer your actual question:

why would main thread want to close the socket from the other thread

It's not a socket from another thread. Actually, the main method is accepting the socket connection and then giving it to the DaytimeThread.
Typically, an entity responsible for obtaining a close-able resource should also be responsible for closing it. The simple way to accomplish this is with a try-with-resources. However, this principle cannot be applied with this design because a thread may need the resource after the main thread is done with it.


text:
Q: Fullcalendar add tooltip to events I'm using fullcalendar in my php site. I load events with eventSources, giving it an url redirecting to my php controller, which generates json data. Before the calendar is rendered, I wish every event has a tooltip. To this scope I wrote a javascript function that add the tooltip:
 function dailyTooltip(){
   $('.fc-day-grid-event, .fc-time-grid-event').each(function(){
      var content = $(this).data('content');
      $(this).attr('title','');
      $(this).tooltip({
       tooltipClass: 'event-tooltip',
       content: content,
      });
   });
 }

where content is html content. The function runs after calendar rendering.
After the calendar has been rendered, the tooltip is not showing.
To resolve this problem, I tried to add the function to datesRender, and eventRender. datesRender seems to work, but only when I change view (e.g. from timeGrid to dayMonthGrid). eventRender doesn't work.

A: you can use Tooltip.js with fullcalendar eventRender for showing tooltips,
<script src='https://unpkg.com/tooltip.js/dist/umd/tooltip.min.js'></script>

you can use event render function like this:
eventRender: function(info) {
        var tooltip = new Tooltip(info.el, {
          title: info.event.extendedProps.description,//you can give data for tooltip
          placement: 'top',
          trigger: 'hover',
          container: 'body'
        });
      },

Check out Event render Tooltip Fullcalendar demo

A: In fullcalendar.js V5, there is no eventRender. So what I did is everytime I click any button on the calendar header i create their tooltip
<script src='https://unpkg.com/tooltip.js/dist/umd/tooltip.min.js'></script>

const calendarControlBtns = Array.from(
  document.querySelectorAll('.fc-header-toolbar button')
);
calendarControlBtns.forEach((singleControlBtn) => {
  singleControlBtn.addEventListener('click', handleNewInterval);
});
const handleNewInterval = (e) => {
  const allEvents = Array.from(document.querySelectorAll('.fc-timegrid-event'));
  allEvents.forEach((singleEvent) => {
    singleEvent.dataset.toggle = 'tooltip';
    const title = singleEvent.querySelector('.fc-event-title').innerHTML;
    singleEvent.dataset.title = title;
  });
  $('[data-toggle="tooltip"]').tooltip();
}

A: I know this is an old post but if someone finds this post.
FullCalendar v5 has a hover example.
https://fullcalendar.io/docs/event-tooltip-demo
You can also view it in code pen(top right hand corner button)
Make sure to add the two js scripts.
https://unpkg.com/popper.js/dist/umd/popper.min.js
https://unpkg.com/tooltip.js/dist/umd/tooltip.min.js


text:
Q: Reading json file sub-levels I need some assistance in reading a json file in vs2019 vb.net. I have figured out most of it but there is a sub-level I don't know how to code to read it. I am using the Newtonsoft.json reference library.
Here is a sample of the json data:
[
    {
    "checkDate": "2020-02-07",
    "periodBeginDate": "2020-01-27",
    "periodEndDate": "2020-02-02",
    "earnings": [
      {
        "earningCode": "REG",
        "hours": 0.0000,
        "rate": 0.000000,
        "amount": 55.00,
        "chargeDate": null,
        "jobCode": "",
        "in1": null,
        "out1": null,
        "in2": null,
        "out2": null,
        "memo": "",
        "internalMemo": "",
        "costCenters": [
        {
        "level": 1,
        "levelCode": "DEPT",
        "costCenterCode": "Gradall operator"
        }
        ]
      }
    ],
    "costCenters": [
      {
        "level": 1,
        "levelCode": "DEPT",
        "costCenterCode": "Gradall operator"
      }
    ],
    "divisionKey": {
      "companyCode": "IT1",
      "divisionCode": "001"
    },
    "employeeNumber": "999"
  }
]

As you can see, there could be multiple cost centers, one at the root level and one under the earnings section. I need to get both. The root level one (and the other data) I am able to get with the code below. But I am unable to figure out how to code for the "cost centers" under "earnings". Do I need an entirely new class? And does it go under "earnings"? I am new at reading json files so any help would be appreciated.
Public Class CheckData
Public Property EmployeeNumber As String = ""
Public Property DivisionKey As divisionKeys
Public Property Earnings() As List(Of Earning)
Public Property CostCenters() As List(Of CostCenter)

<JsonProperty("periodEndDate")>
Public Property PPDEndDate As Date?

<JsonProperty("checkDate")>
Public Property CheckDate As Date?
Public Class divisionKeys
    <JsonProperty("divisionKey")>
    Public Property divisionKey() As Object
    Public Property companyCode As String = ""
    Public Property divisionCode As String = ""
End Class

Public Class CostCenter
    <JsonProperty("costCenters")>
    Public Property costCenters() As Object
    Public Property startDate As Date
    Public Property levelCode As String = ""
    Public Property costCenterCode As String = ""
End Class

Public Class Earning
    <JsonProperty("earnings")>
    Public Property earnings1() As Object
    Public Property earningCode As String = ""
    Public Property hours As Decimal
    Public Property amount As Decimal
End Class

Private Sub GetJsonData()

    SecFileName = "PayrollData.json"
    Dim jsonString = IO.File.ReadAllText(PathJson & SecFileName)
    Dim AllEmpl = JsonConvert.DeserializeObject(Of List(Of CheckData))(jsonString)

    Try
        Using cn As New SqlConnection(ConnString)
            cn.Open()

            For Each Emp In AllEmpl
                EarnCount = Emp.Earnings.Count

                For i = 0 To EarnCount - 1

                    Using cmd As New SqlCommand("Insert Into tblFTEImportBase (EmpId, FacNumPay, JobCode, PaycheckDate, PPDEndDate, EarnType, EarnHours, EarnAmt)
          Values (@EmpId, @FacNumPay, @JobCode, @CheckDate, @PPDEndDate, @EarnType, @EarnHours, @EarnAmt);", cn)
                        With cmd.Parameters
                            .Add("@EmpId", SqlDbType.VarChar, 15).Value = Emp.EmployeeNumber
                            .Add("@FacNumPay", SqlDbType.VarChar, 10).Value = Emp.DivisionKey.companyCode

                            For cc = 0 To Emp.CostCenters.Count - 1
                                Select Case Emp.CostCenters(cc).levelCode

                                    Case "DEPT"
                                        .Add("@JobCode", SqlDbType.VarChar, 15).Value = Emp.CostCenters(cc).costCenterCode

                                        'Case "JC"
                                        '    .Add("@DeptNum", SqlDbType.VarChar, 15).Value = Emp.CostCenters(cc).costCenterCode
                                End Select
                            Next

                            If IsDBNull(Emp.CheckDate) = True Or Emp.CheckDate Is Nothing Then
                                .Add("@CheckDate", SqlDbType.Date).Value = DBNull.Value
                            Else
                                .Add("@CheckDate", SqlDbType.Date).Value = Emp.CheckDate
                            End If

                            If IsDBNull(Emp.PPDEndDate) = True Or Emp.PPDEndDate Is Nothing Then
                                .Add("@PPDEndDate", SqlDbType.Date).Value = DBNull.Value
                            Else
                                .Add("@PPDEndDate", SqlDbType.Date).Value = Emp.PPDEndDate
                            End If

                            EarnTypeTest = Emp.Earnings(0).earningCode

                            .Add("@EarnType", SqlDbType.VarChar, 10).Value = Emp.Earnings(i).earningCode
                            .Add("@EarnHours", SqlDbType.Decimal).Value = Emp.Earnings(i).hours

                            .Add("@EarnAmt", SqlDbType.Decimal).Value = Emp.Earnings(i).amount
                            cmd.ExecuteNonQuery()
                        End With

                    End Using
                Next
            Next
            cn.Close()
        End Using
    Catch ex As Exception
        SuccessFlag = "N"
        Errormsg = ex.Message
    End Try
End Sub

A: I would recommend you to first generate the class using the Paste Special tool from VS2019
This will autogenerate a class that can handle that specific type of JSON (Try using a JSON that has its full range of variables, arrays, etc)
After that, just deserialize it like this:
Dim yourObjJSON = JsonConvert.DeserializeObject(Of YourJSONClass)(<JSON as String>)

If you want you can check the JObject documentantion too.


text:
Q: Does anyone know if there is a way to achieve any sorting or filtering within the JSON_ARRAYAGG()? hello guys does anyone know how to filter data or sort using like operator the data in JSON_ARRAYAGG() ,
I want to add Like operator in Following query. how I can achieve this as I am newbie in MySQL
SELECT s.state_id,s.state,
JSON_ARRAYAGG(JSON_OBJECT('city',c.city, 'city_id',c.city_id) /* i want to add like Operator here*/)
AS 'cities'
FROM `cities` AS c JOIN states AS s
WHERE s.state_id = c.state_id GROUP BY State.

i want to sort cities using like operator
These are the create table schema for citi & state table:
create table `cities` (
    `city_id` int (11),
    `city` varchar (270),
    `state_id` int (11),
    `is_active` tinyint (1),
    `created_at` datetime ,
    `updated_at` datetime
);
insert into `cities` (`city_id`, `city`, `state_id`, `is_active`, `created_at`, `updated_at`) values('1','Port Blair*','1','1','2021-03-31 07:25:28','2021-03-31 07:25:28');
insert into `cities` (`city_id`, `city`, `state_id`, `is_active`, `created_at`, `updated_at`) values('2','Adoni','2','1','2021-03-31 07:25:28','2021-03-31 07:25:28');
insert into `cities` (`city_id`, `city`, `state_id`, `is_active`, `created_at`, `updated_at`) values('3','Amalapuram','2','1','2021-03-31 07:25:28','2021-03-31 07:25:28');
insert into `cities` (`city_id`, `city`, `state_id`, `is_active`, `created_at`, `updated_at`) values('4','Anakapalle','2','1','2021-03-31 07:25:28','2021-03-31 07:25:28');
insert into `cities` (`city_id`, `city`, `state_id`, `is_active`, `created_at`, `updated_at`) values('5','Anantapur','2','1','2021-03-31 07:25:28','2021-03-31 07:25:28');
insert into `cities` (`city_id`, `city`, `state_id`, `is_active`, `created_at`, `updated_at`) values('6','Bapatla','2','1','2021-03-31 07:25:28','2021-03-31 07:25:28');
insert into `cities` (`city_id`, `city`, `state_id`, `is_active`, `created_at`, `updated_at`) values('7','Bheemunipatnam','2','1','2021-03-31 07:25:28','2021-03-31 07:25:28');

state table:
create table `states` (
    `state_id` int (11),
    `state` varchar (180),
    `is_active` tinyint (1),
    `created_at` datetime ,
    `updated_at` datetime
);
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('1','Andaman and Nicobar Islands','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('2','Andhra Pradesh','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('3','Arunachal Pradesh','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('4','Assam','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('5','Bihar','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('6','Chandigarh','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('7','Chhattisgarh','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('8','Dadra and Nagar Haveli','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('9','Delhi','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('10','Goa','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('11','Gujarat','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('12','Haryana','1','2021-03-31 06:30:04','2021-03-31 06:30:04');
insert into `states` (`state_id`, `state`, `is_active`, `created_at`, `updated_at`) values('13','Himachal Pradesh','1','2021-03-31 06:30:04','2021-03-31 06:30:04');

fiddle

A: https://dev.mysql.com/doc/refman/5.7/en/aggregate-functions.html#function_json-arrayagg says:

JSON_ARRAYAGG(col_or_expr)
Aggregates a result set as a single JSON array whose elements consist of the rows. The order of elements in this array is undefined.

https://bugs.mysql.com/bug.php?id=94696 is a feature request from 2019, asking for a way to sort elements before aggregating them with JSON_ARRAYAGG(). That ticket is in a "Verified" state, meaning it has been accepted as a feature request, but it has not been implemented.
The GROUP_CONCAT() aggregate function has an optional ORDER BY clause you can use inside the function call, but none of the other aggregate functions have such a clause.
You can take advantage of an unofficial method: because InnoDB tables read rows in index order according to the index used to access the table, you can use indexes to make it use a specific index.
Here's a table of test data:
mysql> select * from mytable;
+----+-------------+------+
| id | text        | x    |
+----+-------------+------+
|  1 | longing     | NULL |
|  2 | rusted      | NULL |
|  3 | seventeen   | NULL |
|  4 | daybreak    | NULL |
|  5 | furnace     | NULL |
|  6 | nine        | NULL |
|  7 | benign      | NULL |
|  8 | homecoming  | NULL |
|  9 | one         | NULL |
| 10 | freight car | NULL |
+----+-------------+------+

Here we see some words in my table are returned in alphabetical order:
mysql> select json_arrayagg(text) from mytable;
+-----------------------------------------------------------------------------------------------------------------+
| json_arrayagg(text)                                                                                |
+-----------------------------------------------------------------------------------------------------------------+
| ["benign", "daybreak", "freight car", "furnace", "homecoming", "longing", "nine", "one", "rusted", "seventeen"] |
+-----------------------------------------------------------------------------------------------------------------+

The reason is that the query used an index on that text column as the access order. Because I only fetched one column, it was able to do an index-scan.
mysql> explain select json_arrayagg(text) from mytable;
+----+-------------+---------+------------+-------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table   | partitions | type  | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+---------+------------+-------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | mytable | NULL       | index | NULL          | text | 83      | NULL |   10 |   100.00 | Using index |
+----+-------------+---------+------------+-------+---------------+------+---------+------+------+----------+-------------+

Whereas if I include another non-indexed column, it does a table-scan, which reads rows in primary key order:
mysql> explain select x, json_arrayagg(text) from mytable;
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-------+
| id | select_type | table   | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-------+
|  1 | SIMPLE      | mytable | NULL       | ALL  | NULL          | NULL | NULL    | NULL |   10 |   100.00 | NULL  |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-------+

And the result is that the array is aggregated in primary key order, not in alphabetical order:
mysql> select x, json_arrayagg(text) from mytable;
+------+-----------------------------------------------------------------------------------------------------------------+
| x    | json_arrayagg(text)                                                                                |
+------+-----------------------------------------------------------------------------------------------------------------+
| NULL | ["longing", "rusted", "seventeen", "daybreak", "furnace", "nine", "benign", "homecoming", "one", "freight car"] |
+------+-----------------------------------------------------------------------------------------------------------------+

Can I make another index to force it to use another order?
mysql> update mytable set x = 11 - id;
Query OK, 10 rows affected (0.03 sec)

mysql> select * from mytable order by id;
+----+-------------+------+
| id | text        | x    |
+----+-------------+------+
|  1 | longing     |   10 |
|  2 | rusted      |    9 |
|  3 | seventeen   |    8 |
|  4 | daybreak    |    7 |
|  5 | furnace     |    6 |
|  6 | nine        |    5 |
|  7 | benign      |    4 |
|  8 | homecoming  |    3 |
|  9 | one         |    2 |
| 10 | freight car |    1 |
+----+-------------+------+

mysql> alter table mytable add key (x, text);

The EXPLAIN shows that it will prefer to do an index-scan if I only reference the two columns in that index:
mysql> explain select x, json_arrayagg(text) from mytable;
+----+-------------+---------+------------+-------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table   | partitions | type  | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+---------+------------+-------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | mytable | NULL       | index | NULL          | x    | 88      | NULL |   10 |   100.00 | Using index |
+----+-------------+---------+------------+-------+---------------+------+---------+------+------+----------+-------------+

And because x is first in this index, that determines the order in which the rows are aggregated.
mysql> select x, json_arrayagg(text) from mytable;
+------+-----------------------------------------------------------------------------------------------------------------+
| x    | json_arrayagg(text)                                                                                |
+------+-----------------------------------------------------------------------------------------------------------------+
|    1 | ["freight car", "one", "homecoming", "benign", "nine", "furnace", "daybreak", "seventeen", "rusted", "longing"] |
+------+-----------------------------------------------------------------------------------------------------------------+

If you have more columns, or if the table is a joined table that is not the first in the join order, it may be quite tricky—or even impossible—to get the array order the way you want, while still accessing the table with good optimization.


text:
Q: IntelliJ IDEA Java code style: Space between Annotation and Enum How to add space between ) and Enum name?
I want to see this:
enum SampleEnum {
    @Annotation("1") ONE,
    @Annotation("2") TWO,
    @Annotation THREE
}

This is how auto-formatting works:
enum SampleEnum {
    @Annotation("1")ONE,
    @Annotation("2")TWO,
    @Annotation THREE
}

Don't want to use @formatter:off / on
UPDATE:
I added an issue https://youtrack.jetbrains.com/issue/IDEA-170457

A: The settings for auto formatting code are grabbed from the settings for "Code Style." These settings can be found at:
File - Settings - Editor - Code Style - Java
The setting your looking for is probably under the "Spaces" tab
Hopefully this fixes your problem.
Alternatively you can look through the IDEA add on repository for code style add-ons:
https://plugins.jetbrains.com/search/idea?correctionAllowed=true&search=code+style


text:
Q: How to show error page when exception happens in JSF beforephase? The JSF2 specs are pretty clear in that exceptions thrown in a beforephase method are swallowed by the container. All I see is a small message in the console log.
However, I threw an exception in the beforephase because data could not be retrieved, and of course I want to show an error page with some more information. Unfortunately I'm unable to work it out.
Throwing the Exception from anywhere else works fine, my error page and errorhandler are setup fine to catch these errors, but I can't pick them up from any beforephase method (fortunately I only have a few).
Any hints how this can be done?
Thanks!


text:
Q: iPhone app delegates does not work properly I am new to iPhone development. I am converting the date to the desired format and set it to the delegate and get its value in the another view. The session restarts when I tried to get the value from delegate. If I set the original date and not the formatted date in the set delegate, then I able to get the value in the another view. If I also give any static string value, then also I am able to the static string value back.
Only the formatted date which is string is set then the session restarts. If I print and check the value of the formatted date it prints the correct formatted date only. Here is my code for date conversion
NSString *dateval=[[stories objectAtIndex: storyIndex] objectForKey:@"date"];

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];

[inputFormatter setDateFormat:@"EEE, MMM dd, yyyy"];

NSDate *inputDate = [inputFormatter dateFromString:dateval];

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];

[outputFormatter setDateFormat:@"MMMM dd"];

NSString *outputDate = [outputFormatter stringFromDate:inputDate];

AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];

[delegate setCurrentDates:outputDate];

Edit
This is displayed in console
inside view did load
[Session started at 2010-04-21 19:12:53 +0530.]
GNU gdb 6.3.50-20050815 (Apple version gdb-967) (Tue Jul 14 02:11:58 UTC 2009)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "i386-apple-darwin".sharedlibrary apply-load-rules all
Attaching to process 4216.
(gdb)

In another view
 - (void)viewDidLoad {
NSLog(@"inside view did load");
AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
NSString *titleValue=[delegate getCurrentDates];
self.navigationItem.title =titleValue ;
}

The get does not work properly. It works fine if I give any static string or the "dateval".

A: outputDate does not seems to be retained, so the value is lost at the end of the event loop (because of the NSAutoreleasePool).
You should retain the outputDate to avoid its release with something like that in the delegate:
- (void)setCurrentDates:(NSString *)value {
    [value retain]; // <- Retain new value
    [date release]; // <- Release old value;
    date = value;
}

The best solution would be to have a declared property in the delegate with the retain attribute.


text:
Q: How to blocking Button with Check button C# Forms Application Hello i want to disable / enable button with check box.
myproject:

A: If I understood correctly you question, there is a property called Enabled on the Control.
Here is a link to that property documentation
Update: (Just to make more clear the answer based on comments)
It belogns to the Winforms API as this property is part of the  Namespace of System.Windows.Forms
As  most (if not every) control inherits from Control Class and this Class has the Enabled property which states that "Enabled
Gets or sets a value indicating whether the control can respond to user interaction."
So, every Control that inherits from this Class can use that property.

A: Hello if you want do get your button enabled or disabled try something like this.
first set the button.enable to false:
button.enabled = false;

then:
if(checkbox.checked == true)
{
 button.enabled = true;
}
else
{
 //let the user know with messagebox that he needs to accept the terms
}