text:
Q: Duplicating table rows with clone I am having an issue I am struggling to resolve.  I have two tables

                        Campaign Type
                        Deployment Date
                        Additional Information

                            <select class="selectType" name='typeInput[0][campType]' id="campInput">
                                <option value=""></option>
                                <option value="Main">Main</option>
                                <option value="Other">Standalone</option>
                            </select>

                            <input type="text" name='typeInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>

                            <textarea name='typeInput[0][addInfo]' id="additionalInput"  placeholder='Additional Information' class="form-control noresize"></textarea>

                Add Row
                Delete Row

              Additional Information
              Deployment Date

                <textarea name='amendsInput[0][addInfo]' id="additionalInput"  placeholder='Additional Information' class="form-control noresize"></textarea>

                <input type="text" name='amendsInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>

        Add Row
        Delete Row

One table has 3 inputs, the other has 2.  When the add button is pushed on either table, I am cloning the table row, which includes cloning a datepicker.
Things have been going fine but now I have a problem.  The second table I end everything with 4 e.g. table4, template4, add4 and delete4.  I then duplicated the Javascript from the preious table but added 4 to everything (I duplicated it because this table has different inputs).  This resulted in the following code.
$(function() {
    initJQueryPlugins();

    $('#add').on('click', function() {
        $last_row = $('#table1 > tbody  > tr').last();
        if(!hasValues($last_row)){
            alert('You need to insert at least one value in last row before adding');
        } else {
            add_row($('#table1'));
        }
    });

    $('#delete').on('click', function() { delete_row($('#table1')); });

    $('#add4').on('click', function() {
        $last_row = $('#table4 > tbody  > tr').last();
        if(!hasValues4($last_row)){
            alert('You need to insert at least one value in last row before adding');
        } else {
            add_row4($('#table4'));
        }
    });

    $('#delete4').on('click', function() { delete_row4($('#table4')); });
});

function add_row($table) {
    var tr_id = $table.find('tr').length - 1;
    var $template = $table.find('tr.template');

    var $tr = $template.clone().removeClass('template').prop('id', tr_id);

    $tr.find(':input').each(function() {
        if($(this).hasClass('hasDatepicker')) {
            $(this).removeClass('hasDatepicker').removeData('datepicker');
        }

        var input_id = $(this).prop('id');
        input_id = input_id + tr_id;
        $(this).prop('id', input_id);

        var new_name = $(this).prop('name');
        new_name = new_name.replace('[0]', '['+ tr_id +']');
        $(this).prop('name', new_name);

        $(this).prop('value', '');
    });
    $table.find('tbody').append($tr);

    $(".dateControl", $tr).datepicker({
        dateFormat: "dd-mm-yy"
    });

    $(".selectType", $tr).select2({
        tags: true
    });
}

function hasValues($row){
    $optVal = $row.find('td option:selected').text();
    $inputVal = $row.find('td input').val();
    $textVal = $row.find('td textarea').val();
    if($optVal != "" || $inputVal != "" || $textVal != ""){
            return true;
    } else {
            return false;
    }
}

function delete_row($table) {
    var curRowIdx = $table.find('tr').length - 1;
    if (curRowIdx > 2) {
        $("#" + (curRowIdx - 1)).remove();
        curRowIdx--;
    }
}

function add_row4($table4) {
    var tr_id = $table4.find('tr').length - 1;
    var $template = $table4.find('tr.template4');

    var $tr = $template.clone().removeClass('template4').prop('id', tr_id);

    $tr.find(':input').each(function() {
        if($(this).hasClass('hasDatepicker')) {
            $(this).removeClass('hasDatepicker').removeData('datepicker');
        }

        var input_id = $(this).prop('id');
        input_id = input_id + tr_id;
        $(this).prop('id', input_id);

        var new_name = $(this).prop('name');
        new_name = new_name.replace('[0]', '['+ tr_id +']');
        $(this).prop('name', new_name);

        $(this).prop('value', '');
    });
    $table4.find('tbody').append($tr);

    $(".dateControl", $tr).datepicker({
        dateFormat: "dd-mm-yy"
    });
}

function hasValues4($row4){
    $inputVal = $row4.find('td input').val();
    $textVal = $row4.find('td textarea').val();
    if($inputVal != "" || $textVal != ""){
            return true;
    } else {
            return false;
    }
}

function delete_row4($table4) {
    var curRowIdx = $table4.find('tr').length - 1;
    if (curRowIdx > 2) {
        $("#" + (curRowIdx - 1)).remove();
        curRowIdx--;
    }
}

function initJQueryPlugins() {
    add_row($('#table1'));
    add_row4($('#table4'));
}

I have set up a working FIDDLE
The problem is this.  If you start adding a few rows in the first table, this all works fine.  After this, add a few rows in the second table.  This seems to work fine.  However, now start deleting rows in the second table.  For some reason it seems to also delete rows in the first table.
So my main question is why does this happen?  Additionally, is there any way I can do this without duplicating the code?  The second table does not use select2.
Thanks

A: You are deleting this:
 $("#" + (curRowIdx - 1)).remove();

This id is also available in the first table, you have to choose a more specified selector
like:
$table4.find("#" + (curRowIdx - 1)).remove();

or better: (comment from K. Bastian above)
$table4.find('tr').last().remove()

I edited your sample here:
https://jsfiddle.net/cLssk6bv/
Here I also deleted the dublicated code, only the different insert method still exist:
https://jsfiddle.net/cLssk6bv/1/


text:
Q: Retrofit cache expires itself after 24 Hours I am trying to create an android app which will fetch data from internet using Retrofit. I have made retrofit caching system too. I works fine for 24 Hours since the app went offline but after 24 Hours all the stored cache data expire itself.
I even changed the expiration time inside code from 60 * 60 * 20 (1 day) to 60 * 60 * 24 * 185 (185 days). Is there any solution?
public class RetrofitInstance {
    private static final String BASE_URL = "DOMAIN_HERE";

    public static Retrofit getRetrofit(Context context)
    {
            File httpCacheDirectory = new File(context.getCacheDir(), "httpCache");
            Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);

            OkHttpClient httpClient = new OkHttpClient.Builder()
                    .cache(cache)
                    .addInterceptor(chain -> {
                        try {
                            return chain.proceed(chain.request());
                        } catch (Exception e) {
                            Request offlineRequest = chain.request().newBuilder()
                                    .header("Cache-Control", "public, only-if-cached," +
                                            "max-stale=" + 60 * 60 * 24 * 185)
                                    .build();
                            return chain.proceed(offlineRequest);
                        }
                    })
                    .build();

        return new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(new Gson()))
            .client(httpClient)
            .baseUrl(BASE_URL)
            .build();
    }

}

A: Hope this helps.
1) Try forcing the Cache-control
 .cacheControl(CacheControl.FORCE_CACHE)

after
 Request offlineRequest = chain.request().newBuilder()

or
 2)
 Request request = new Request.Builder()
   .cacheControl(new CacheControl.Builder()
       .maxStale(365, TimeUnit.DAYS)
         .build();

Documentation: https://square.github.io/okhttp/3.x/okhttp/okhttp3/Cache.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create a flag type / category for illegal content There was recently an answer on SO that I had flagged as Other because it contained a link to a website that illegally distributed copyrighted material (in this case, a book) and encouraged downloading the material.
I chose Other because there wasn't a flag category for illegal content. I logged in to SO the next day and noticed the answer was still there.
As it was explained in Possible illegal content linked on answer?, the Other queue is very long compared to other flag queues. Illegal content should be taken care of in an expedient manner, so I think there should be a flag category for it.

A: While I am not a lawyer my understanding is that once we start to enforce any copyright restrictions we must enforce all copyright restrictions; that is we are no longer able to use the common carrier defence. At present as long as take down notices are responded to in a timely fashion Stack Exchange is not liable for the content created by its users, on the other hand if active policing occurs then Stack Exchange could be pre-emptively sued.
This is a highly related question in which the example of YouTube is used. YouTube was previously protected from being sued for the vast amount of copyright infringing material on its site because it never tried to vet it. Once they began vetting some of it they began to be sued for the material they missed.
The point is we are not the police and attempting to enforce our own (almost certainly wrong) interpretation of the law is dangerous. The vast majority of these posts are off topic for other reasons and should be closed for those reasons.

A: The way you deal with these is by casting a moderator flag with a custom description.  Something like this:

This answer links to illegally distributed copyright material.  Please delete.

Fortunately, it doesn't happen often enough to warrant a specific, system-recognized flag.

A: You can kill a sparrow with a cannon. But no one produces cannons designed for killing sparrows. Wonder why?
If the question is useless without link, flag it as link-only answer.
If the question is complete, and link is only a reference, just edit the answer, changing the link to the name of the book. So everyone would be happy.


text:
Q: Embed php code in custom field of a plugin I am using this plugin https://wordpress.org/plugins/emailcoauthoronpost/ in my website. This plugin shoots an email to the author of the post with a link to my website. But I need to send the permalink of the post itself. So I need to embed some php code in the email body at the backend. Please see the snapshots.
Current Version

My Requirement

A: Looking at the Other Notes of the plugin, you can use one of the variables to insert the post url.

$post_url - Replaced with the URL of the post which was published

Edit:
You would just add the $post_url variable within your body field.
$title


text:
Q: How do I continue processing items if one throws an error? Had to rewrite this post with the actual code since there must be some kind of difference with binary modules.
The full cmdlet is as follows (apologies for length):
In a nutshell, this function basically uses the SMO library and pulls information about a database users from a SQL Server Instance.
namespace Namespace
{
    using Microsoft.SqlServer.Management.Smo;
    using System;
    using System.Collections.Generic;
    using System.Management.Automation;

    using static PrivateFunctions;

    [Cmdlet(VerbsCommon.Get, "DatabaseUserInformation")]
    public class GetDatabaseUserInformationCmdlet : PSCmdlet
    {
        [Parameter(Mandatory = true,
                   HelpMessage = "The user name of the account to retrieve information for.",
                   Position = 0,
                   ValueFromPipeline = true,
                   ValueFromPipelineByPropertyName = true)]
        public string LogonName { get; set; }

        private List<object> userInformation = new List<object>();

        protected override void ProcessRecord()
        {
            string samAccountName = GetSamAccountName(LogonName);
            Login login = null;
            User user = null;

            WriteVerbose($"Getting login for account: {samAccountName}...");
            try
            {
                login = GetLogin(samAccountName);
            }
            catch (InvalidOperationException invalidOperation)
            {
                ThrowTerminatingError(new ErrorRecord(
                                      invalidOperation,
                                      "LoginNotFound",
                                      ErrorCategory.InvalidOperation,
                                      login));

            }

            WriteVerbose($"Getting user for login: {login.Name}...");
            try
            {
                user = GetUser(login);
            }
            catch (InvalidOperationException invalidOperation)
            {
                ThrowTerminatingError(new ErrorRecord(
                                      invalidOperation,
                                      "UserNotFound",
                                      ErrorCategory.InvalidOperation,
                                      user));
            }

            WriteVerbose($"Gathering information for user: {user.Name}");
            var information = new
            {
                LoginName = login.Name,
                UserName = user.Name,
                FullAccess = TestFullAccessOnDatabase(user),
                Roles = user.EnumRoles()
            };

            userInformation.Add(information);

        }

        protected override void EndProcessing()
        {
            WriteVerbose("Writing information to output.");
            userInformation.ForEach(item => WriteObject(item));
        }
    }
}

The cmdlet can be used with a single argument:
Get-DatabaseUserInformation user1

Or I also want to be able to pipe an array to it when dealing with multiple users.
@('user1', 'user2','user3') | Get-DatabaseUserInformation

If I'm using a single value and that user doesn't exist, then fair enough, it terminates, and it's a case of correcting it and running it again.
But when I'm using it with multiple values, if one of them doesn't exist, it doesn't give any output as all, only the exception.
So the output I get when everything is OK is something like this (with verbose on):
VERBOSE: Getting login for account: DOMAIN\user1...
VERBOSE: Getting user for login: DOMAIN\user1...
VERBOSE: Gathering information for user: dbo
VERBOSE: Getting login for account: DOMAIN\user2...
VERBOSE: Getting user for login: DOMAIN\user2...
VERBOSE: Gathering information for user: user2
VERBOSE: Getting login for account: DOMAIN\user3...
VERBOSE: Getting user for login: DOMAIN\user3...
VERBOSE: Gathering information for user: user3
VERBOSE: Writing information to output.

LoginName           UserName                     FullAccess Roles
---------           --------                     ---------- -----
DOMAIN\user1        dbo                          True       {db_owner}
DOMAIN\user2        user2                        False      {role1}
DOMAIN\user3        user3                        False      {}

What I get when something is wrong: (in this case, user2 has been misspelt.)
Get-DatabaseUserInformation : A login for the account 'DOMAIN\usr2' does not
exist in the database.
At line:1 char:6
+ $x | Get-DatabaseUserInformation -verbose
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-DatabaseUserInformation], InvalidOperationException
    + FullyQualifiedErrorId : LoginNotFound,DatabaseUserManagement.GetDatabase
   UserInformationCmdlet

What I want to happen is something similar to this.
VERBOSE: Getting login for account: DOMAIN\user1...
VERBOSE: Getting user for login: DOMAIN\user1...
VERBOSE: Gathering information for user: dbo
VERBOSE: Getting login for account: DOMAIN\usr2...
Get-DatabaseUserInformation : A login for the account 'DOMAIN\usr2' does not
exist in the database.
At line:1 char:6
+ $x | Get-DatabaseUserInformation -verbose
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-DatabaseUserInformation], InvalidOperationException
    + FullyQualifiedErrorId : LoginNotFound,DatabaseUserManagement.GetDatabase
   UserInformationCmdlet
VERBOSE: Getting login for account: DOMAIN\user3...
VERBOSE: Getting user for login: DOMAIN\user3...
VERBOSE: Gathering information for user: user3
VERBOSE: Writing information to output.

LoginName           UserName                     FullAccess Roles
---------           --------                     ---------- -----
DOMAIN\user1        dbo                          True       {db_owner}
DOMAIN\user3        user3                        False      {}

A: EDIT: The problem clearly is in the ThrowTerminating error. Read the msdn description here:
https://msdn.microsoft.com/en-us/library/system.management.automation.cmdlet.throwterminatingerror(v=vs.85).aspx
The remark section states that you should not use this approach if you want to continue processing the pipeline:

When a cmdlet encounters a terminating error, call this method rather
  than simply throwing an exception. Calling this method allows the
  cmdlet to attach additional error record information that describes
  the condition that caused the terminating error. When this method is
  called, the Windows PowerShell runtime catches the error record and
  then starts shutting down the pipeline. For more information about
  error reporting and error records, see Windows PowerShell Error
  Reporting. This method should not be used when errors occur where the
  cmdlet can continue processing records. To send error reports when
  nonterminating errors occur, call the WriteError method. For more
  information about cmdlets, see Windows PowerShell Cmdlets.

You have to write an advanced function like this:
Function Get-StringLength()
{
    [CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline=$true)]
        $value
    )
    Begin {}
    Process {
        Write-Output $value.Length
    }
    End {}
}

The Begin block is where you prepare something, the Process block is where you process each object from the pipeline, that means it is run for each object in pipeline. You clean up the mess in the End block.
Because it is a cmdlet then you can use ErrorAction to control what happens on error:
$values | Get-StringLength -ErrorAction SilentlyContinue

You can even put those errors in a variable using:
$values | Get-StringLength -ErrorAction SilentlyContinue -ErrorVariable MyErrors

A: Maybe throw in a try/catch statement, usually works for me. Otherwise, I would check out these two threads:
Continue execution on Exception
https://social.technet.microsoft.com/forums/scriptcenter/en-US/e9ee76cd-3446-4507-b9e7-60863550fa00/powershell-trycatch-not-continuing-after-error

A: Borrowing code from your earlier revision I make a simple function that accepts pipeline input. For every object passed we attempt to get a user from Active Directory. I was surprised when setting -ErrorAction on the internal cmdlet didn't work. So the simple solution was to set a try/catch block with not catch action.
Function Get-AdUsers()
{
    [CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline=$true)]
        $value
    )
    Process {
        try{Get-ADUser $value}catch{}
    }

}

$values = 'gooduser1','badname','gooduser2'
$values | Get-AdUsers

So the above returns 2 user objects. If I remove the try block I still get the same two objects but I also get an error. Using try suppressed it.

In your update code your are getting a terminating error because that is how you defined it. Try just leaving the catch block empty an see if that works.

A: You need to write a filtering function, rather than a regular function. To do this put the body of the function in a process block:
function Get-StringLength()
{
    [CmdletBinding()]
    Param
    (
        [Parameter(ValueFromPipeline=$true)]
        $value
    )

    process
    {
        Write-Output $value.Length
    }
}

This will cause the filter to be called once for each item in the pipeline.

A: Use either -ErrorAction SilentlyContinue or -ErrorAction Continue :
@('user1', 'user2','user3') | Get-DatabaseUserInformation -ErrorAction Continue

Also, don't use ThrowTerminatingError as I think that shuts down the pipeline. Try throwing a regular exception instead.


text:
Q: Trivial sequence: $32,21,14,\dots$ My little brother (third grade) asked me for help with this math problem on his homework, which was:

Find the next number in the sequence $32,21,14,\dots$

I was not able to see a trivial solution, so I ran a linear regression (for an equation for $a_n$) which turned up an equation with an $r^2$ of .$98$, which (considering I had three points) was not suitable, so I ran a quadratic regression and got the polynomial $$2n^2-17n+47$$ which yielded an $r^2$ of 1, and so was a perfect fit. Therefore, I said the answer was $11$.
My question is, considering that the question assumes no knowledge of algebra, or exponents, is there a simple (recursive, maybe?) formula for the next number in the sequence?

A: Note that you have not proved that the pattern is what you say.  The next term could be anything and you could find a cubic that went through the four points.  There are also many other rules that could form these numbers.  Accepting the quadratic, I think that formula is fine.  Another way to indicate it is with a difference table, where each term is the difference of the two above it: $$\begin {array}&32&&21&&14&&11\\&11&&7&&3\\&&4&&4 \end {array}$$

A: I see a pattern of subtracting the number you get by adding the digits together, doubling the resulting sum, then adding one.
e.g. $3+2 = 5 \times 2 = 10 + 1 = 11$
$32-11 = 21$ and so on
In which case, the next term would be $3$

A: A humble attempt:
To me doesn't seem trivial at all, but a possible pattern that comes to my mind is the following:
Let's say a number $a_1$ in the sequence is given, to get $a_2$ take $a_2=a_1+0.5$, to get $a_3$ take $a_3=a_2-0.75$. I believe this is a pattern that could be given to a third grade, even if they can't find a formal expression for the sequence.
Now, looks like we have something like $a_n=a_{n-1}+(-1)^{n}0.25n$ . If the first number is 1.5, follows 2.0, then 0.25, and then 1.0; notice anything curious?, those numbers can be written as $3/2,2/1,1/4,1/1,\dots$. So maybe this could be thinked as the nth term of the sequence being the fractional form of the number given by the rule above.
I don't know, maybe the way I'm thinking this is kinda dumb, but is the only thing that comes to my mind right now. But I insist, to me it doesn't look trivial at all.
Edit: I post this here because I added a couple of things for clarification and no longer fits in the comment section.

A: There are many possible answers. One possible pattern is subtraction of primes leading to a finite end, yet an infinite beginning.
...
81-19=62
62-17=45 45 <-- preceding number of sub-sequence
45-13=32 32 <-- start of given sub-sequence
32-11=21 21
21- 7=14 14 <-- end of given sub-sequence
14- 5= 9  9 <-- next number of sub-sequence
9- 3= 6
6- 2= 4 <- end of sequence


text:
Q: Mongoose promise with Bluebird error with passport js This is the error:
Warning: a promise was created in a handler at D:\Playgrounds\express-mongoose-es6-rest-api\config\passport.js:15:18 but was not returned from it
This is my passport.js:
var JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt = require('passport-jwt').ExtractJwt;

// load up the user model
var User = require('../server/user/user.model');
var config = require('./config'); // get db config file

module.exports = function(passport) {
  var opts = {};
  opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
  opts.secretOrKey = config.jwtSecret;
  passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    User.findById(jwt_payload._id)
      .then(user => {
          return done(null, user);
      })
      .catch(err => {
          return done(err);
      })
  }));
};

But, I suspect the main problem is my route controller (store.controller.js):
const Store = require('./store.model');

exports.add = async function(req, res) {

  const store = new Store({
    name: req.body.name,
    description: req.body.description,
    mobileNumber: req.body.mobileNumber,
    is_online: req.body.is_online,
    open_schedule: req.body.open_schedule,
    address: req.body.address,
    creator: req.user._id
  });

  try {
    return store.save()

   // I already have tried store.save().then(savedStore => return res.json(savedStore)), but still no help.
  }
  catch(e) {
    return res.status(403).send({success: false, msg: 'Unauthorized.'})
  }

}

If I don't use save(), and just return a message directly (like return res.json({msg: "Hi"}) ), it goes without error.
Please help me

A: It turns out I forget to call next() on my model pre-save.
I spend 'bout two days figuring this out.
So, if anyone reading this has the same problem, make sure you call next()

A: Try adding return before User in your passport code. I think the error is because you not returning an outer promise.
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    return User.findById(jwt_payload._id)    //here
      .then(user => {
          return done(null, user);
      })
      .catch(err => {
          return done(err);
      })
  }));


text:
Q: Sum values based on comparison of two different DataFrames I try to check if a value in one df is between two values of another df. If so the values of the first df shall be summed.
df1['MyNewCol'] = df2[(df2['date'] >= df1['Startdate']) and (df2['date'] <= df1['enddate'])].sum('values', axis = 1)

This is what my code looks like and it shall check if the date mentioned in df2 is between startdate and enddate. If so it shall print the sum of values.
I get "Can only compare identically-labeled Series objects" as error. Is there an easy way to solve the problem?

A: Size of series of two dataframes are not the same for comparison or the indexes aren't similar. So, the operator >= can't compare in these cases.
and is a python operator. You need logical & for your case
(df2['date'] >= df1['Startdate']) & (df2['date'] <= df1['enddate'])


text:
Q: How to create Chained JOIN query in RAILS to generate excel? I am using to_xls gem to generate excel sheets.
My query requires to Fetch data from bill model, property model, owner model and bank details model wherein all the models above form a chain.
My associations are as follows.
Bill model
   belongs_to   :property,  class_name: "::Property"

Property model
   has_many :owners,    class_name: "::Properties::Owner"
   has_many :bills,     class_name: "::Bill"

Property::Owner
   belongs_to   :property,  class_name: "::Property"
   has_one  :bank_detail, as: :account, class_name: "::Users::BankDetail"

Users::BankDetail
   belongs_to :account, polymorphic: true

My query has to contain bill.amount, bill.property.owners.(each owner)name ( property can have many owners), bill.property.owners.(each owner)email, bill.property.owners.(each owner)mobile, and bill.property.owners.(on each owner).bank_detail.ifsc.
In my Bills controller
    def create_excel
    @bills = Bill.all
    respond_to do |format|
    format.html
    format.xls do
     send_data(
              Bill.all.joins(property: {owners: :bank_detail}).select('
     bills.amount, bills.created_at, owners.name as owners_name').to_xls,
      content_type: 'application/vnd.ms-excel',
      filename: 'excel.xls')
   end
   end
   end

Here, however, it throws an error on
   ERROR:  missing FROM-clause entry for table "owners"
   LINE 1: SELECT  bills.amount, bills.created_at, owners.name as
   owner_name...

I am very unsure how to write this SQL query in rails since I am a beginner. Can someone plz help me with the exact query to display on to my excel sheet.Plz, help!


text:
Q: What's the name of this stochastic process? I heard about it sometime somewhere and want to read about it now, but I can't recall what the name is:
Start with $a_1 = \ldots =a_n=1$. Choose a number between 1 and $n$ with probability $a_i/(a_1+ \ldots + a_n)$ to choose $i$. If $i_0$ is the number chosen, increase $a_i$ by 1 and now choose another number and so on indefinitely.

A: For this process and a substantial generalization, see this.
The case $p=0$ and $\gamma = 1$ corresponds to the process you described.

A: Thanks for the pointer, Shai Covo. The name of this specific process is preferential attachment.


text:
Q: How do I get channel information in a Mirth Connect JavaScript Reader Source Connector? I'm working with Mirth Connect Server 3.8.1 and I'm using a JavaScript Reader as a channel's Source Connector. I'm trying to get the current channel id, but it seems that that's not possible. After googling I've tried the following things to see if yielded any results but it did not:
logger.info(typeof channelId != 'undefined' ? ChannelUtil.getDeployedChannelName(channelId) : 'N/A');
logger.info(typeof connector != 'undefined' ? connector : 'N/A');
logger.info(typeof channel != 'undefined' ? channel : 'N/A');

This just produces three "N/A" in the logs. Obviously I could hard-code the channel id, but I want to export this config eventually and be able to import it to other environments without needing to edit anything. Plus it feels like a Source Connector piece of JS should know who it is working for.
How do I get this information from within the script?
Update: The answer "This should work" is essentially correct, because as it turns out this does work in a brand new channel. The channel I was working with was imported and although I could find no other scripts affecting that channel, it was clearly broken. So possible the real answer is "Mirth Connect Server 3.8.1 has a bug that causes this to sometimes not work and the workaround is creating a new channel."
Update 2: The culprit turned out to be me using the channelId variable in a local scope later, something along the lines of:
for (var i=0; i<allChannelIds.size(); i++) {
    var channelId = allChannelIds.get(i);
    // Other code
}

I wrote that before realizing there was a global scope channelId variable and before needing it. Apparently this resets it to undefined. If the global channelId was set each time the script executes, this should not be a problem, but apparently that is not the case.

A: You might be overcomplicating things.
In Mirth 3.5.1 the following code worked fine for me in the Transformer on the source connector of a channel:
logger.info("Channel ID: "+channelId);

The result was something like this:
[2020-02-25 13:03:30,033]  INFO  (transformer:?): Channel ID: 1122e1c7-34af-4141-9388-533005346d0b

This ID matches the ID that appears in the Mirth dashboard and on the channel summary page.
I also verified that the code worked in a Javascript Reader.  In this case, the logged message was
[2020-02-25 14:33:20,004]  INFO  (js-connector:?): Channel ID: 1122e1c7-34af-4141-9388-533005346d0b

A: To get Channel Name you can use this code:
var channelName = Packages.com.mirth.connect.server.controllers.ChannelController.getInstance().getDeployedChannelById(channelId).getName();


text:
Q: Mysql search query two columns I'm bulding a search function for my web site and wish to search by two columns: title and author.
Query:
SELECT title, bookID, publisher, pubDate, book_image, books.authorID, authors.author FROM books, authors WHERE books.authorID = authors.authorID
            AND title LIKE '$queryString%' OR author LIKE '$queryString%'LIMIT 5

When I search by title this works fine, but when I search by author I get a list of all books with the searched for author as author. Obviously this is incorrect.
How can I fix this query to successfully search for either title or author?

A: Try below :
SELECT title, bookID, publisher, pubDate, book_image, books.authorID, authors.author
FROM books left join  authors on  books.authorID = authors.authorID
WHERE (title LIKE '$queryString%' OR author LIKE '$queryString%') LIMIT 5

I would like to suggest you to use fulltext search in mysql.That will be more faster and efficient

A: SELECT title, bookID, publisher, pubDate, book_image, books.authorID, authors.author
FROM books, authors
WHERE books.authorID = authors.authorID
        AND (title LIKE '$queryString%' OR author LIKE '$queryString%')LIMIT 5

this should do the work

A: Try it out:
SELECT bk.title, bk.bookID, bk.publisher, bk.pubDate, bk.book_image, bk.authorID, au.author
FROM books bk,  authors au
WHERE bk.authorID = au.authorID AND bk.title LIKE '$queryString%' OR au.author LIKE '$queryString%' LIMIT 5


text:
Q: Getting "Request Error" after hosting WCF on IIS Before hosting WCF Restful Services on IIS. I was getting response from server in my android application but now I have hosted my services on IIS but getting an error message of REQUEST ERROR. I don't know what's went wrong. can someone please sort out my problem. Thanks in Advance
Before Hosting on IIS

the above picture is before hosting the service on IIS. and the yellow highlighted text is param and the JSON is the response which is corresponding to that param.
After Hosting on IIS

I don't know why I'm getting this error. what went wrong and how to fix that. now im trying to retrieving data correspond to that param but getting an error message.
"SERVER LOG  after includeexceptiondetailInfaults attribute value to true"
I'ms sure that database is causing the error and you can view the picture of server log below

A: The database was causing an error. I have found the solution. what we need to do? We need to add a login to SQL Server for IIS APPPOOL\ASP.NET v4.0 and grant permissions to the database.
In SQL Server Management, under the server, expand Security, then right click the Logins and select "New Login...".
In the New Login dialog, enter the app pool as the login name and click "OK"

now right click the login, select properties and then click on the User Mapping Option. Click the appropriate DATABASE and check the properties roles. And we are done :).
hope you good luck. Thanks

A: Possible solutions would be,
(i)Just ensure all your property are public.
(ii)To So see more details about the issue, you need to includeexceptiondetailInfaults attribute to true in servicedebug tag.
<servicebehaviors>
        <behavior name="myServiceBehavior">
          <servicedebug includeexceptiondetailinfaults="true" />
        </behavior>
</servicebehaviors>

(iii)Remove the Enum types (or use their suggested work-around and use a wrapper around the enum properties) and this should go away.
(iv)Copy the connection strings from the class library app.config to the web project web.config If you are using a class library and a web project,

A: After hosting on  iis
Request  error occurred in  iis
The  server  encountered  on  request  error  see  server logs for more details
Solution
 In  your  sql  server  change  window  authentic to  sql authentic  with  username and password
and  change  on  connection  string
After  changing these step  and  refresh  the  iis  and
Your  problem  is  solved


text:
Q: scatter plot: tall arrays eating up all the memory I am working on tone mapping operators in HDR. My question is very simple. I want to scatter plot large arrays on Matlab 2015Ra with computer specs core i5 20GB RAM. Only the scatter plot eats up the whole memory (around 92% of 20GB). I need some suggestion to plot tall arrays. I know Matlab 2018 has binscatter function but I have lower version. Thank you. Sample Code:
a=randn(21026304,1);
scatter(a,a);

Only this code eats up the all memory.

A: You can create a binscatter like function yourself with histcounts2!
Histcounts bins the data into an NxN array which you can then visualize with imshow... this is pretty memory-efficient as every bin only takes up a couple of bytes, regardless of the input size.
% Some (correlated) data
x = randn(1e6,1);
y = randn(1e6,1)+x;

% Count 32x32 bins
[N,ax,ay] = histcounts2(x,y,32);

% Some gradient
cmap = [linspace(1,0,16);
    linspace(1,0.3,16);
    linspace(1,0.5,16)].';

% Show the histogram
imshow(...
    N,[],...                        % N contains the counts, [] indicated range min-max
    'XData', ax, 'YData', ay, ...   % Axis ticks
    'InitialMagnification', 800,... % Enlarge 8x
    'ColorMap', cmap...             % The colormap
);

colorbar;
axis on;
title('bin-counts');


text:
Q: Why paint class is not working with setDefaultLookAndFeelDecorated(true) package Jai;

import javax.swing.*;
import java.awt.*;

public class tuna extends JFrame{

    tuna(){
        super("Title");
        setLayout(new FlowLayout());

        getContentPane().setBackground(Color.white);
    }

    public void paint(Graphics g){
        super.paint(g);

        g.fillOval(50, 100, 100, 155);
    }

    public static void main(String[] arg){
        JFrame.setDefaultLookAndFeelDecorated(true);
        tuna obj = new tuna();
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        obj.setSize(500,500);
        obj.setVisible(true);
    }
}

I have a JFrame where I use the paint method to draw an Oval on the frame.
Whenever I try to maximize or minimize the window than the oval drawn through the paint() method disappears. I want the drawn graphics to stay even when I maximize or minimize the frame.

A: Your problem is overriding of a wrong method for a wrong object. You must override paintComponent method for the main panel. Here is the correct code:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class tuna extends JFrame {
    tuna() {
        super("Title");
        // you need to override the method paintComponent for the main panel
        setContentPane(new JPanel(new FlowLayout()) {
            @Override
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.fillOval(50, 100, 100, 155);
            }
        });
        getContentPane().setBackground(Color.white);
    }

    public static void main(String[] arg) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        tuna obj = new tuna();
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        obj.setSize(500, 500);
        obj.setVisible(true);
    }
}


text:
Q: FormData object is empty in asp.net mvc5 controller when ie11 browser is used to send request data Currently my application logic works correctly on Chrome and Firefox browser, but for some reason it doesn't work in the same way on IE11 browser. I have following function which is called from related with it html button :
    function sendStatus(url, status, comment) {
    var formData = new FormData();
    formData.append('status', status);
    formData.append('comment', comment);

    $.ajax({
        method: "POST",
        url: url,
        contentType: false,
        data: formData,
        processData: false,
        cache: false,
        error: showErrorMessage,
        success: showPreview
    });

and if request are coming to server from IE11, then HttpContext.Request.Form property doesn't include anything placed into formData. The same request called from Chrome/Firefox include everything declare in formdata object. Is there anything that I need to change in that code or provide some additional logic for ie11 browser ?


text:
Q: How to avoid suspended apps getting killed in iOS 14? I have updated my iPad operating system from iOS 11.4 to iPadOS 14.3. Unfortunately, suspended apps are now immediately killed in the background while in the older version I could keep many apps suspended in the background without need to be restarted when being used again (Even, Safari often refreshes open tabs when I want to use them after a short while during which they were not active; such a thing has also happened on the older OS, but with much less frequency).
One might expect such a bug for non-Apple apps because of non-compatibility with the new OS update, but it really surprised me that such a problem exists with Apple apps such as Safari and Pages.
It is really annoying, especially when you are writing some post on a Stack Exchange network and need to use some other app. I wonder whether this can be avoided somehow.
PS: It is worth saying that my iPad has enough free memory, more than that when running the older OS.


text:
Q: Unreadable barplot y-axis with ggplot I have a dt.csv with two columns and thousands of rows, that looks like this:
mea_mg_kg_derived;class
0.1;Actinopterygii
1.2;Actinopterygii
0.8;Elasmobranchii
2.1;Malacostraca
1.1;Elasmobranchii
0.5;Malacostraca

The values in "mea_mg_kg_derived" column go from 1.670e -6 to 61, and this column includes missing values (NA).
What I'm trying to do is to plot the group means of mea_mg_kg_derived (the mean of mea_mg_kg_derived, calculated for every single group of class, e.g. Actinopterygii, Elasmobranchii, Malacostraca...).
I've tried with this on R-Studio:
ggplot(dt, aes(x=factor(class), y=mea_mg_kg_derived)) + stat_summary(fun="mean", geom="bar")

and this is the output:

Can anyone tell me what's wrong with the y-axis?


text:
Q: How can I get the server filepath of the JSP from a servlet? This is my second shot at asking the question - I'll provide some more details this time to help get an informed answer.
What I'm trying to really do here is populate a drop-down menu with data that is dynamically generated from an executable that's supposed to run on a page load. The catch is, the executable must be in a directory local to the JSP on the server. My company has 3 or 4 clones of this website and I cannot place the executable in some absolute filepath - it must be relative (because it will be shipped with the JSP page to other processors all at once by some other team).
I know that JSP has the ability to run executables with relative paths because I could run this:
<form action="./my_executable_that_generates_a_dynamic_page">

However, I need this to run from a servlet to populate the dropbox using javascript.
<%= new File("./exec_produce_dropdown_list").getPath() %>

The above snippet gives me a different directory.
I've also tried:
<%= new File(new File(request.getServletContext().getRealPath(request.getRequestURI())).getParent().replace('\\', '/'), "exec_produce_dropdown_list"); %>

And this is pretty close except if there's a virtual path in the URI that doesn't correspond to the filesystem (which is what we have), it won't point to the right directory.
Is there a simple way for me to run the executable??
I also would like to add that there is no web.xml for me to work with.

A: Found my answer:
request.getRealPath(request.getServletPath())

Should give me the /path/in/filesystem/to/file.jsp


text:
Q: Warning issue when installing Hadoop 2.8.2 on Mac OS I am attempting to install Hadoop 2.8.2 with Java 8 on Mac OS, but i ran into this error after typing the hstart command in terminal. (I initially had Java 9 installed, but switched to Java 8 becuase i thought that Java 9 was causing the issue, but the warning still remains.

WARNING: An illegal reflective access operation has occurred WARNING:
  Illegal reflective access by
  org.apache.hadoop.security.authentication.util.KerberosUtil
  (file:/usr/local/Cellar/hadoop/2.8.2/libexec/share/hadoop/common/lib/hadoop-auth-2.8.2.jar)
  to method sun.security.krb5.Config.getInstance() WARNING: Please
  consider reporting this to the maintainers of
  org.apache.hadoop.security.authentication.util.KerberosUtil WARNING:
  Use --illegal-access=warn to enable warnings of further illegal
  reflective access operations WARNING: All illegal access operations
  will be denied in a future release 18/02/04 23:38:54 WARN
  util.NativeCodeLoader: Unable to load native-hadoop library for your
  platform... using builtin-java classes where applicable Starting
  namenodes on [localhost] localhost: namenode running as process 34039.
  Stop it first. localhost: datanode running as process 34125. Stop it
  first. Starting secondary namenodes [0.0.0.0] The authenticity of host
  '0.0.0.0 (0.0.0.0)' can't be established.

This is in my "/usr/local/Cellar/hadoop/2.8.2/libexec/etc/hadoop/hadoop-env.sh" file:
export HADOOP_OPTS="$HADOOP_OPTS -Djava.net.preferIPv4Stack=true -Djava.security.krb5.realm= -Djava.security.krb5.kdc="


text:
Q: What can be stored in a resource.resx file? In a C# project, is it possible to store more than just strings in the resources.resx file? Specifically, I was curious to know if I could take a simple data-object defined in my project, and store an instance of it in the resource file to pull out during runtime.
I figure I probably can do this if I serialize my object first, then put the serializer output in the resource file, but I was hoping to be able to have the object strongly-typed when I pull it out.
Any thoughts?

A:
So you could store your object as a binary or XML file and deserialize it back but a resource file seems uncommon place to store such things.


text:
Q: Multiple image upload I'm making the gallery website and would like to create a multiple image uploader using PHP and MYSQLI only... I'm not really good in coding so the other examples of multiple image upload on this site didn't work for me.
Here is the working code which posts the data into database according to the current user session.
html:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select a file:
<input type="file" name="image[]" id="image" multiple='multiple' />

Title:
<input type="text" name="picname" id="picname" />

Description:
<input type="text" name="picdesc" id="picdesc" />

Category:
<select name="piccat" id="piccat">
<option value="--"></option>
<option value="animation">Animation</option>
<option value="illustration">Illustration</option>
<option value="photography">Photography</option>
</select>

<input type="submit" name="submit" value="Submit" />
</form>

php & mysqli:
<?php
$path = "images/projects/";
include("check.php");

if (isset($_POST["submit"])) {
        $image = $_FILES["image"]["tmp_name"];
        $imageName = $_FILES["image"]["name"];
        $imageSize = $_FILES["image"]["size"];
        $imageType = $_FILES["image"]["type"];
        $imageTitle = $_POST["picname"];
        $imageDescription = $_POST["picdesc"];
        $imageCategory = $_POST["piccat"];
        $len = count($image);
        $path = $path . $imageName;

        $query = $db -> prepare("INSERT INTO images (user_id, image, description, type, title, size, category)
        VALUES (?, ?, ?, ?, ?, ?, ?)");
        $query -> bind_param('issssis', $_SESSION['user_id'], $imageName, $imageDescription, $imageType, $imageTitle, $imageSize, $imageCategory);
        $query -> execute();
        $query -> close();

    if ($imageName){
            move_uploaded_file($image, $path);
            }
}
?>

It works fine but only uploads one image. How to select multiple images and upload all of them at once?

A: Use this one
<?php
$path = "images/projects/";
include("check.php");
if (isset($_POST["submit"])) {
  for ($i = 0; $i < count($_FILES["image"]["name"]); $i++) {
    $image = $_FILES["image"]["tmp_name"][$i];
    $imageName = $_FILES["image"]["name"][$i];
    $imageSize = $_FILES["image"]["size"][$i];
    $imageType = $_FILES["image"]["type"][$i];
    $imageTitle = $_POST["picname"];
    $imageDescription = $_POST["picdesc"];
    $imageCategory = $_POST["piccat"];
    $path = $path . $imageName;

     $query = $db -> prepare("INSERT INTO images (user_id, image, description, type, title, size, category)
    VALUES (?, ?, ?, ?, ?, ?, ?)");
    $query -> bind_param('issssis', $_SESSION['user_id'], $imageName, $imageDescription, $imageType, $imageTitle, $imageSize, $imageCategory);
    $query -> execute();
    $query -> close();

 if ($imageName){
        move_uploaded_file($image, $path);
        }
}
}
?>

A: Use this one
<?php
$path = "images/projects/";
include("check.php");
if (isset($_POST["submit"])) {
     for ($i = 0; $i < count($imageName); $i++) {
        $image = $_FILES["image"]["tmp_name"][$i];
        $imageName = $_FILES["image"]["name"][$i];
        $imageSize = $_FILES["image"]["size"][$i];
        $imageType = $_FILES["image"]["type"][$i];
        $imageTitle = $_POST["picname"];
        $imageDescription = $_POST["picdesc"];
        $imageCategory = $_POST["piccat"];
        $path = $path . $imageName;

        $query = $db -> prepare("INSERT INTO images (user_id, image, description, type, title, size, category)
        VALUES (?, ?, ?, ?, ?, ?, ?)");
        $query -> bind_param('issssis', $_SESSION['user_id'], $imageName, $imageDescription, $imageType, $imageTitle, $imageSize, $imageCategory);
        $query -> execute();
        $query -> close();

    if ($imageName){
            move_uploaded_file($image, $path);
            }
}
}
?>

A:

<link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css">
 <form action="#" class="dropzone-area" enctype="multipart/form-data" method="POST">

Drop Files Here To Upload

 <button type="submit" class="btn btn-outline-primary" id="submit-all"> upload </button>
</form>

A:

Drop some files here

    <output id="filesInfo"></output>

    <form enctype="multipart/form-data" method="post" action="upload.php">

            Select Files to Upload

            <input type="file" name="filesToUpload[]" id="filesToUpload" multiple="multiple" />
            <output id="filesInfo"></output>

            <input type="submit" value="Upload" />

    </form>


text:
Q: How to pack nuget for winui3 and wpf at same time? I need create a nuget, it need for winui3 and wpf, because loading mainthread in winui3 is different with wpf see How to get DispatcherQueue in WinUI 3 Desktop using Windows App SDK, so i need distinguish they. But i see Windows.AppSdk just for net5-windows, don't distingush, how to distinguish they when i pack they to one nuget?

A: Bring in both the WPF and the WinUI assemblies in the shared project and check if System.Windows.Threading.Dispatcher.CurrentDispatcher is initialized in your code:
Shared.csproj:
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net5.0-windows10.0.19041.0</TargetFramework>
    <TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
    <RootNamespace>Shared</RootNamespace>
    <RuntimeIdentifiers>win10-x86;win10-x64;win10-arm64</RuntimeIdentifiers>
    <UseWinUI>true</UseWinUI>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

  <ItemGroup>
      <PackageReference Include="Microsoft.ProjectReunion" Version="0.8.4" />
      <PackageReference Include="Microsoft.ProjectReunion.Foundation" Version="0.8.4" />
      <PackageReference Include="Microsoft.ProjectReunion.WinUI" Version="0.8.4" />
  </ItemGroup>
</Project>

public static class Helper
{
    public static void Dispatch(Action action)
    {
        if (Dispatcher.CurrentDispatcher != null)
        {
            // WPF
            Dispatcher.CurrentDispatcher.Invoke(action);
        }
        else
        {
            // WinUI
            Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread()?
                .TryEnqueue(new Microsoft.UI.Dispatching.DispatcherQueueHandler(action));
        }
    }
}

WPF App:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net5.0-windows10.0.19041.0</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

  <ItemGroup>
    <ProjectReference Include="..\Shared\Shared.csproj" />
  </ItemGroup>

</Project>

WinUI App:
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net5.0-windows10.0.19041.0</TargetFramework>
    <TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
    <RootNamespace>WinUIApp</RootNamespace>
    <ApplicationManifest>app.manifest</ApplicationManifest>
    <Platforms>x86;x64;arm64</Platforms>
    <RuntimeIdentifiers>win10-x86;win10-x64;win10-arm64</RuntimeIdentifiers>
    <UseWinUI>true</UseWinUI>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.ProjectReunion" Version="0.8.4" />
    <PackageReference Include="Microsoft.ProjectReunion.Foundation" Version="0.8.4" />
    <PackageReference Include="Microsoft.ProjectReunion.WinUI" Version="0.8.4" />
    <Manifest Include="$(ApplicationManifest)" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\..\Shared\Shared.csproj" />
  </ItemGroup>
</Project>

Shared.Helper.Dispatch(() => { /* ... */ });


text:
Q: SQL JOIN with multiple rows conditionally I have 2 tables in a SQLite database that I am accessing it via PHP
This is sample data, it is enough to describe what I want to do but not why.
Lets call these tables: TableA, TableB, and TableC
------------------------
|  Unique_ID  |  Name  |
------------------------
|  1          | Sam    |
------------------------
|  2          | Bob    |
------------------------
|  3          | Jill   |
------------------------

*Assume more rows for other possible foreign keys below
--------------------------------------------
|  Unique_ID  |  Foreign_Key  | Time_Stamp |
--------------------------------------------
|  1          | 1             | 1495298339 |
--------------------------------------------
|  2          | 1             | 1495298350 |
--------------------------------------------
|  3          | 1             | 1495298365 |
--------------------------------------------

What I want in my output would be something line this
------------------------------------
|  Name  | First_Time |  Last_Time |
------------------------------------
|  Sam   | 1495298339 | 1495298365 |
------------------------------------
|  Jill  | 1495298787 | 1495298805 |
------------------------------------

Basically I want to pull the fist and last time stamp into the 1st table, but I am not sure how to do a join line this or if it is even possible, multi-layered select queries with limited results of 1?
I am hoping there is a way to avoid looping through each value in TableA and making two separate queries to get the first (lowest) and last (highest) Time_Stamp in TableB

A: You can do a join between the first table and a processed version of the second table. The second table is a group by using the Foreign_Key, and the computed values are the minimum and maximum of Time_Stamp. Something like this:
select A.Unique_Id, B.First_Time, B.Last_Time
from TableA as A
join (
    select Foreign_Key, min(Time_Stamp) as First_Time, max(Time_Stamp) as Last_Time
    from Table B
    group by Foreign_Key
) as B
on A.Unique_Id = B.Foreign_Key

A: SELECT table1.Name, MIN( table2 .Time_Stamp ) AS firstTime, MAX( table2 .Time_Stamp ) AS lastTime
FROM  `table1`
LEFT OUTER JOIN table2 ON table1.Unique_Id = table2.Unique_Id
GROUP BY table1.Unique_Id

Hope this will help you.

A: SELECT TableA.name, MIN(TableB.timeid), MAX(TableB.timeid) FROM TableA

INNER JOIN TableB ON TableA.id = TableB.TableA_id

GROUP BY TableB.TableA_id


text:
Q: Convert HTML style (dotted underline) to PDF using iTextSharp I am trying to generate PDF from below HTML i.e. a text with dotted underline. (Below is sample actual HTML is much bigger)
 Hello

as explained in How to convert HTML to PDF using iTextSharp . The output is supposed to have a dotted line which I can see in the HTML file, however the PDF generated by iTextSharp shows a normal underline and not a dotted underline. Here is my complete method
   public void UsingXMLWorker()
    {
        Byte[] bytes;

        //Create a stream that we can write to, in this case a MemoryStream
        using (var ms = new MemoryStream())
        {

            using (var doc = new Document())
            {
                //Create a writer that's bound to our PDF abstraction and our stream
                using (var writer = PdfWriter.GetInstance(doc, ms))
                {

                    //Open the document for writing
                    doc.Open();

                    //sample HTML and CSS
                    var example_html = @" Hello ";

                    using (var srHtml = new StringReader(example_html))
                    {
                        //Parse the HTML
                        iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
                    }

                    //var example_html = @" Hello ";
                    //var example_css = @".dottedBorder{border-bottom: 1px dotted #000;text-decoration: none;font-size:38px;}";
                    //using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css)))
                    //{
                    //    using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_html)))
                    //    {

                    //        //Parse the HTML
                    //        iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
                    //    }
                    //}
                    doc.Close();
                }
            }
            bytes = ms.ToArray();
        }

        var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
        System.IO.File.WriteAllBytes(testFile, bytes);
    }

I even tried other methods like below code still I see a PDF generated with a normal underline as opposed to a dotted underline. What I am missing here ?
                    var example_html = @" Hello ";
                    var example_css = @".dottedBorder{border-bottom: 1px dotted #000;text-decoration: none;font-size:38px;}";
                    using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css)))
                    {
                        using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_html)))
                        {

                            //Parse the HTML
                            iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
                        }
                    }

A: According to the CSS conformance list, borders are only supported on table cells.
The line you are seeing is actually the  tag's default bottom border and your text-decoration code is actually being overwritten by the default code for a  tag. If you watch the ResolveStyles method in iTextSharp\tool\xml\css\StyleAttrCSSResolver.cs, the top chunk (around 170 in 5.5.6) that sets keys and values for tagCss correctly finds and sets your property. The next block of code after that, however, special-cases certain HTML tags and forces some rules upon then.
// inherit css from parent tags, as defined in provided CssInheritanceRules or if property = inherit
IDictionary<String, String> css = t.CSS;
if (t.Name != null)
{
    if (t.Name.Equals(HTML.Tag.I) || t.Name.Equals(HTML.Tag.CITE)
        || t.Name.Equals(HTML.Tag.EM) || t.Name.Equals(HTML.Tag.VAR)
        || t.Name.Equals(HTML.Tag.DFN) || t.Name.Equals(HTML.Tag.ADDRESS)) {
            tagCss[CSS.Property.FONT_STYLE] = CSS.Value.ITALIC;
    }
    else if (t.Name.Equals(HTML.Tag.B) || t.Name.Equals(HTML.Tag.STRONG)) {
        tagCss[CSS.Property.FONT_WEIGHT] = CSS.Value.BOLD;
    }
    else if (t.Name.Equals(HTML.Tag.U) || t.Name.Equals(HTML.Tag.INS)) {
        tagCss[CSS.Property.TEXT_DECORATION] = CSS.Value.UNDERLINE;
    }
    else if (t.Name.Equals(HTML.Tag.S) || t.Name.Equals(HTML.Tag.STRIKE)
             || t.Name.Equals(HTML.Tag.DEL)) {
                 tagCss[CSS.Property.TEXT_DECORATION] = CSS.Value.LINE_THROUGH;
    }
    else if (t.Name.Equals(HTML.Tag.BIG)) {
        tagCss[CSS.Property.FONT_SIZE] = CSS.Value.LARGER;
    }
    else if (t.Name.Equals(HTML.Tag.SMALL)) {
        tagCss[CSS.Property.FONT_SIZE] = CSS.Value.SMALLER;
    }
}

Since this block happens after your CSS you'll see that you can't remove an underline on a  tag because it will always be turned back on. Similarly, you also can't un-bold a  tag, un-italic an  or explicitly set a font size on a <big> tag (I forgot that was actually a tag!) unless you have a parent container's font size set.
So unfortunately, short of modifying the source I'm not really sure that what you are looking for is possible.


text:
Q: How to change url in browserview in electron and maintain size and position I am trying to change the URL in a browserview within a main window in electron via a button click from the main window.
In other words, I have an html file loaded within the mainWindow like this:

mainWindow.webContents.loadFile('html/index.html')

I also have a browserView added properly initially and added the ability to set its position and resize like this:

mainWindow.setBrowserView(view)

view.webContents.on("did-finish-load", () => view.setBounds({x: 100, y:100,width: widthVal, height: heightVal   }))

view.webContents.on("did-finish-load", () => view.setAutoResize({
width: true,
height: true,
horizontal: true,
vertical: false   }))

When the app first opens, everything works, and adjusting the size of the app properly updates the browserviews via auto resize.
Within this html file, I have a button, which I can properly loop back to my main.js and execute the method:

browserview.webContents.loadURL("www.newwebpage.com").

This does indeed change the browserview's url and displays it within the browserview.
However, if after opening the app, the size of the app changes, e.g. maximized, the size and location of the browserview changes within the application.  This works properly before i click my button to change the URL.  however, after I click the button and load the new URL, the browswerview size reverts back to the original size when the app was first opened.
I cannot get the browswerView to maintain its size and position after the app is maximized (or just not its default size when opened).  I tried forcing it via the same mechanism I used to call the browserview in the first place e.g. did-finish-load and view.setBounds().  This didn't work.
Thanks

A: I figured it out:
You need to query for the current size of the browserView and force it to that size after loading the new webpage:
const bounds = view.getBounds()
view.webContents.loadURL('https://www.newpage.com')

view.webContents.on("did-finish-load", () => view.setBounds({
    x: bounds.x,
    y: bounds.y,
    width: bounds.width,
    height: bounds.height
}))

view.setAutoResize({
    width: true,
    height: true,
    horizontal: true,
    vertical: false
})


text:
Q: How to get and change a variable in my view controller from SKScene Ok so here is the code
class GameViewController:  UIViewController,  SceneTransitionDelegate,
GKGameCenterControllerDelegate, ADBannerViewDelegate {

var coolbool:Bool = false

...abunch of unimportant stuff functions and stuff

 }

And here is what I am trying to do from my SKScene
func thing1()
{
        let controller = GameViewController()
        controller.coolbool = true
        println(controller.coolbool) // Will say that it is true
        sceneDelegate.transitionToScene(Menu.self) //Menu.self is the skscene that
       we used to be in and will be in
}

func thing2()
{
        println(controller.coolbool) // Will say that it is false
        if (controller.coolbool == true)
        {
           //Put rainbows over every sprite and change generator settings
        }
}

So basically what happens is that "coolbool" is initialized as being false.  Until thing1() is called causing the variable "coolbool " to change.  And i confirm its change immediately after, before the transition.  However after the transition (to the same scene (I'm trying to make it look different if the bool is true)) if you ask what the value is, it says its false.... even though i just set it to true.
Anyway I assume I am doing something wrong, is their a better way to do this???  Incase you want it here is the transition function
func transitionToScene(sceneClass:Scene.Type) {
    playing = false
    var sizeRect = UIScreen.mainScreen().applicationFrame
    var width = sizeRect.size.width * UIScreen.mainScreen().scale
    var height = sizeRect.size.height * UIScreen.mainScreen().scale
    let skView = self.view as! SKView
    let scene = sceneClass(size: skView.bounds.size)
    scene.size = CGSizeMake(width, height)
    rwidth = width
    rheight = height
    swidth = width
    sheight = height
    skView.ignoresSiblingOrder = true

    scene.scaleMode = .AspectFill
    scene.sceneDelegate = self

    skView.presentScene(scene)
}

A: You need to get the current instance of the GameViewController, so this statement:
let controller = GameViewController()

isn't going to work because it declares a new instance of a controller, which is not related to the SKView you are currently using. Instead, we need to obtain the current, presenting view controller.
Obtaining Instance of the View Controller:
The closest method that can help us here is in the UIResponder class, and it is nextResponder:. Its general function is to find and return the current next responder, which seems vague and not of much use to us, until Apple mentions that:

Subclasses must override this method to set the next responder. UIView implements this method by returning the UIViewController object that manages it (if it has one) or its superview (if it doesn't)

This means that if we are in a scene, we can find the view controller by using the scene's self.view which is the presenting SKView object (inherits from UIView). All we have to do is find the View Controller in our responder chain.
Swift:
var currentViewController: GameViewController?
var upstreamResponder: UIResponder? = self.view
var found = false

while (found != true){
    upstreamResponder = upstreamResponder!.nextResponder()
    if let viewController = upstreamResponder as? GameViewController {
        currentViewController = viewController
        found = true
    }
    if upstreamResponder == nil {
        //could not find VC, PANIC!
        break
    }
}

Objective-C: (will probably have to #include "GameViewController.h")
GameViewController *currentViewController;
UIResponder *upstreamResponder = self.view;
BOOL found = false;

while (found != true) {
    upstreamResponder = [upstreamResponder nextResponder];
    if ([upstreamResponder isKindOfClass:[GameViewController class]]) {
        currentViewController = (GameViewController *)upstreamResponder;
    }
    if (upstreamResponder == nil) {
        //omg where did VC go?!
        break;
    }
}

Setting properties on your View Controller
Now that you have your current view controller, it is very simple to set any desired property. So if you wanted to change coolbool, all you have to do is state:
currentViewController.coolbool = true

Hope this helps! -Max


text:
Q: Date dimension has stopped processing in OLAP cube Little bit of background, we have an OLAP system that has been happily processing it's cube for a customer for a long time. Then recently it started to fail. This has coincided with the main developer accidentally getting married and making himself unavailable. So obviously I can't go pestering him.
We have a date dimension that works at Year, Month, Day level. We have thow hierarchies  for calendar and fiscal years.
It's currently throwing a message that I find pretty indecipherable (not being an OLAP dev) and the examples I've read online refer to it being caused by weeks splitting across months, which is not a problem I have.
The message is:
Rigid relationships between attributes cannot be changed during incremental processing of a dimension.

When I reprocess the cube I now get problems related to dates.  When I reprocess the Date dimension I get the following:
Internal error: The operation terminated unsuccessfully.
Errors in the OLAP storage engine: Rigid relationships between attributes cannot be changed during incremental processing of a dimension.
Errors in the OLAP storage engine: An error occurred while the 'Date ID' attribute of the 'Date' dimension from the 'TMC_CUBE_TESCO' database was being processed.
Errors in the OLAP storage engine: The process operation ended because the number of errors encountered during processing reached the defined limit of allowable errors for the operation.
Server: The operation has been cancelled.

When I view the entire detail for the Date Dimension I see that it has processed a heap of SELECT statements but falls down here:
SELECT DISTINCT [dbo_dw_DIMdate].[DateTime] AS [dbo_dw_DIMdateDateTime0_0],[dbo_dw_DIMdate].[DayOfMonth] AS [dbo_dw_DIMdateDayOfMonth0_1],[dbo_dw_DIMdate].[MonthNumberCalendar] AS [dbo_dw_DIMdateMonthNumberCalendar0_2],[dbo_dw_DIMdate].[YearCalendar] AS [dbo_dw_DIMdateYearCalendar0_3]
FROM [dbo].[dw_DIMdate] AS [dbo_dw_DIMdate]
Processing Dimension Attribute 'Date ID' failed. 1 rows have been read.
Start time: 10/21/2011 10:30:35 PM; End time: 10/21/2011 10:30:35 PM; Duration: 0:00:00
SQL queries 1

SELECT DISTINCT [dbo_dw_DIMdate].[DateID] AS [dbo_dw_DIMdateDateID0_0],[dbo_dw_DIMdate].[DayOfCalendarYear] AS [dbo_dw_DIMdateDayOfCalendarYear0_1],[dbo_dw_DIMdate].[DayOfFiscalYear] AS [dbo_dw_DIMdateDayOfFiscalYear0_2],[dbo_dw_DIMdate].[DayOfWeek] AS [dbo_dw_DIMdateDayOfWeek0_3],[dbo_dw_DIMdate].[IsCalendarYearToDate] AS [dbo_dw_DIMdateIsCalendarYearToDate0_4],[dbo_dw_DIMdate].[IsFiscalYearToDate] AS [dbo_dw_DIMdateIsFiscalYearToDate0_5],[dbo_dw_DIMdate].[IsLastCalendarMonth] AS [dbo_dw_DIMdateIsLastCalendarMonth0_6],[dbo_dw_DIMdate].[IsLastWeek] AS [dbo_dw_DIMdateIsLastWeek0_7],[dbo_dw_DIMdate].[IsWeekDay] AS [dbo_dw_DIMdateIsWeekDay0_8],[dbo_dw_DIMdate].[IsYesterday] AS [dbo_dw_DIMdateIsYesterday0_9],[dbo_dw_DIMdate].[DateTime] AS [dbo_dw_DIMdateDateTime0_10],[dbo_dw_DIMdate].[DayOfWeekName_engb] AS [dbo_dw_DIMdateDayOfWeekName_engb0_11],[dbo_dw_DIMdate].[ShortDayOfWeekName_engb] AS [dbo_dw_DIMdateShortDayOfWeekName_engb0_12],[dbo_dw_DIMdate].[WeekNumberCalendar] AS [dbo_dw_DIMdateWeekNumberCalendar0_13],[dbo_dw_DIMdate].[WeekNumberFiscal] AS [dbo_dw_DIMdateWeekNumberFiscal0_14],[dbo_dw_DIMdate].[WeekCommencing] AS [dbo_dw_DIMdateWeekCommencing0_15],[dbo_dw_DIMdate].[YearFiscal] AS [dbo_dw_DIMdateYearFiscal0_16],[dbo_dw_DIMdate].[YearCalendar] AS [dbo_dw_DIMdateYearCalendar0_17],[dbo_dw_DIMdate].[IsLastCalendarWeek] AS [dbo_dw_DIMdateIsLastCalendarWeek0_18]
FROM [dbo].[dw_DIMdate] AS [dbo_dw_DIMdate]
Error Messages 1

I'm not after "sent me teh codez", but any help understanding the error message and problem would be very much appreciated.

A: You should process your DB in full mode, not incremental (if size of DB is not very big). But it's only one approach. Also, you could have problems with your dictionary (source table for your dimension). Use the query from process window - try to obtain the same distinct count for attribute Id and attribute Name fields.


text:
Q: Unable to perform arithmetic and sort operations in pandas dataframe I am unable to perform arithmetic operations but mentioning .values at the end of the object, I was able to perform it. However, I am unable to sort the dataset by column. Screenshot arithmetic operations sorting error attached.
Here is the data structure and info.
Data Structure and info
grade   n_obs   n_good
A   74867   71970
B   136929  126170
C   125293  110909
D   76888   65040
E   35757   28793
F   13229   10037
G   3322    2398

As you can see all variables are either float or int but still, I have to use .values in order to perform any arithmetic operations.
Any help is appreciable.


text:
Q: Retrieving an identifier from timed-out std::future? I have an async executor that sends requests to a server with an id. The server performs the request and the executor will be able to identify the work item promise from this same id value in the response. Requests may time out. In such case, I want the executor to drop the ID of this request completely. However, I don't know how identify this promise when the future timed out and there is no ID from the server.
I'm posting a simplified example for brevity.
struct Executor {
    std::map<work_id_t, std::promise<Result>> work_items;
};

// run requests asynchronously
std::future<Result> Executor::post_work(Request r, work_id_t id) {
    work_items[id] = std::promise<Result>();
    do_request(w);
    return work_items[id].get_future();
}

// called when a requests finishes (the server supplies the id)
void Executor::work_finished(work_id_t id, Result r) {
    work_items[id].set_value(r);
    work_items.erase(id);
}

// ...

Executor e;
auto ft = e.post_work(Request("foo"));
auto wait_result = ft.wait_for(timeout_value);
if (wait_result == std::future_status::timeout) {
    e.remove_item(???); // what can I pass here?
}

How can I implement the remove_item function when a timeout happens? Alternatively, how can I change my design to allow a similar mechanism?

A: From the interface you supplied it seems the work_id_t is available in the call to Executor::post_work.
As such, since the caller needs the id in the event of a timeout, just return both the future and the id from post_work:
Perhaps wrap it in a struct such as:
struct Work {
    std::future<Result> ft;
    work_id_t id;
};

If you return a Work instance from Executor::post_work, you can then wait on the future, and in the event of a timeout, use the id to remove the item
Work w = ...
auto wait_result = w.ft.wait_for(timeout_value);
if (wait_result == std::future_status::timeout) {
    e.remove_item(w.id);
}

In the context of your example:
struct Executor {
    std::map<work_id_t, std::promise<Result>> work_items;
};

struct Work {
    std::future<Result> ft;
    work_id_t id;
};

// run requests asynchronously
Work Executor::post_work(Request r, work_id_t id) {
    work_items[id] = std::promise<Result>();
    do_request(w);
    return { work_items[id].get_future(), id };
}

// called when a requests finishes (the server supplies the id)
void Executor::work_finished(work_id_t id, Result r) {
    work_items[id].set_value(r);
    work_items.erase(id);
}

// ...

Executor e;
Work w = e.post_work(Request("foo"));
auto wait_result = w.ft.wait_for(timeout_value);
if (wait_result == std::future_status::timeout) {
    e.remove_item(w.id);
}


text:
Q: Jsonlint validator gives this error Parse error on line 1: varbio={ "name": ^ Expecting '{', '[' varbio={
    "name": "Valeriu Turcanu",
    "role": "Front end web Developer",
    "image": "path to image",
    "skills": [
        "Html",
        "Css",
        "Javascript",
        "Python",
        "Jquery"
    ]
}

A: That is not JSON.
That is an assignment of a js object to a variable named varbio
the json would be
{
    "name": "Valeriu Turcanu",
    "role": "Front end web Developer",
    "image": "path to image",
    "skills": [
        "Html",
        "Css",
        "Javascript",
        "Python",
        "Jquery"
    ]
}

If you were, instead, just trying to declare a variable then you might have missed a space after the var
var bio={
    "name": "Valeriu Turcanu",
    "role": "Front end web Developer",
    "image": "path to image",
    "skills": [
        "Html",
        "Css",
        "Javascript",
        "Python",
        "Jquery"
    ]
}

But this has nothing to do with JSON.


text:
Q: border spacing property doesn't work as expected I am trying to make the following table:

I have an outer border and one border at the bottom.
I got it all right, my only problem is that I can't get the space between the outer border and table (space of 20 px)
when I use border-spacing it doesn't work.
I would appreciate your help.
here is a sample of the code:
http://jsbin.com/AcanusA/1/edit
css code:
.outlined
{
  font:13px Tahoma;
  width: 70%;
  border-collapse: collapse;
  border: 10px solid #d0d0ff;
  margin: 20px;
  border-spacing:20px;
}

.center{
  text-align: center;
}

.side{
  text-align: left;
}

.lastLine{
   border-bottom: 2px solid black;
}

html code:
<!DOCTYPE html>

  <title>web programming project 2</title>
  <link rel="stylesheet" type="text/css" href="exe2CSS2.css">

        Item
        Manufacturer
        Size
        Unit Price
        Quantity
        Total Price

        Corn Flakes
        Kellogg's
        18 0z
        2.5
        1
        2.5

        Solid White Tuna
        Starkist
        5 oz
        2.79
        2
        5.58

        Cream of Mushroom Soup
        Campbell's
        10.75 oz
        1.00
        2
        2.00

        2% Lowfat Milk
        Safeway
        0.5 gal
        1.99
        1
        1.99

        Extra-Wide Egg Noodles
        Golden Grain
        12 oz
        0.87
        3
        2.61

        Total

        9
        14.68

A: Why doesn't border-spacing work?
border-spacing doesn't work because, from https://developer.mozilla.org/en-US/docs/Web/CSS/border-spacing,

The border-spacing CSS property specifies the distance between the
  borders of adjacent cells (only for the separated borders
  model).

Moreover border-spacing is the space between all cells, not only between border cells and the table, so it isn't what you want.
Solution 1: wrapper

#wrapper {
  border: 10px solid #d0d0ff;
  width: 70%;
  overflow: auto;
}
.outlined {
  font: 13px Tahoma;
  border-collapse: collapse;
  margin: 20px;
}
.center {
  text-align: center;
}
.side {
  text-align: left;
}
.lastLine {
  border-bottom: 2px solid black;
}

      Item
      Manufacturer
      Size
      Unit Price
      Quantity
      Total Price

      Corn Flakes
      Kellogg's
      18 0z
      2.5
      1
      2.5

      Solid White Tuna
      Starkist
      5 oz
      2.79
      2
      5.58

      Cream of Mushroom Soup
      Campbell's
      10.75 oz
      1.00
      2
      2.00

      2% Lowfat Milk
      Safeway
      0.5 gal
      1.99
      1
      1.99

      Extra-Wide Egg Noodles
      Golden Grain
      12 oz
      0.87
      3
      2.61

      Total

      9
      14.68

It's the old way of doing it: set a a margin to the table and place it inside a wrapper element with a border.
Modifying the layout for styling purposes can be syntactically incorrect, but works on old browsers.
Solution 2: outline

.outlined {
  font: 13px Tahoma;
  width: 70%;
  border-collapse: collapse;
  border: 20px solid transparent;
  margin: 20px;
  outline: 10px solid #d0d0ff;
}
.center {
  text-align: center;
}
.side {
  text-align: left;
}
.lastLine {
  border-bottom: 2px solid black;
}

    Item
    Manufacturer
    Size
    Unit Price
    Quantity
    Total Price

    Corn Flakes
    Kellogg's
    18 0z
    2.5
    1
    2.5

    Solid White Tuna
    Starkist
    5 oz
    2.79
    2
    5.58

    Cream of Mushroom Soup
    Campbell's
    10.75 oz
    1.00
    2
    2.00

    2% Lowfat Milk
    Safeway
    0.5 gal
    1.99
    1
    1.99

    Extra-Wide Egg Noodles
    Golden Grain
    12 oz
    0.87
    3
    2.61

    Total

    9
    14.68

Add a transparent border and an outline to the table:
border: 20px solid transparent;
outline: 10px solid #d0d0ff;
margin: /* >= 10px */;

Note the outline doesn't increase table's width, so it will overlap surrounding elements. Then, it can be a good idea to use, at least, a margin of 10px.
Browser support
Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit)
1.0    | 1.5 (1.8)       | 8.0               | 7.0   | 1.2 (125)

Note: Outlines may be non-rectangular. They are rectangular in Gecko/Firefox. But e.g. Opera draws a non-rectangular shape
Solution 3: box-shadow

.outlined {
  font: 13px Tahoma;
  width: 70%;
  border-collapse: collapse;
  border: 20px solid transparent;
  margin: 20px;
  box-shadow: 0 0 0 10px #d0d0ff;
}
.center {
  text-align: center;
}
.side {
  text-align: left;
}
.lastLine {
  border-bottom: 2px solid black;
}

    Item
    Manufacturer
    Size
    Unit Price
    Quantity
    Total Price

    Corn Flakes
    Kellogg's
    18 0z
    2.5
    1
    2.5

    Solid White Tuna
    Starkist
    5 oz
    2.79
    2
    5.58

    Cream of Mushroom Soup
    Campbell's
    10.75 oz
    1.00
    2
    2.00

    2% Lowfat Milk
    Safeway
    0.5 gal
    1.99
    1
    1.99

    Extra-Wide Egg Noodles
    Golden Grain
    12 oz
    0.87
    3
    2.61

    Total

    9
    14.68

You can also use a transparent border with a box-shadow:
border: 20px solid transparent;
box-shadow: 0 0 0 10px #d0d0ff;
margin: /* >= 10px */;

Note the shadow doesn't increase table's width, so it will overlap surrounding elements. Then, it can be a good idea to use, at least, a margin of 10px.
Browser support
Use vendor prefixes (-webkit-box-shadow and -moz-box-shadow) for more support:
Chrome     | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit)
-----------------------------------------------------------------------------------
10.0       | 4.0 (2.0)       | 9.0               | 10.5  | 5.1 (Webkit 534)
4.0 -webkit| 3.5 (1.9.1) -moz|                   |       | 5.0 (Webkit 533) -webkit

Notes (thanks @davidbuttar):

*

*In order to get box-shadow in IE9 or later, you need to set border-collapse to separate. Then, you lose the bar in your table.

*On Chrome, transparent borders don't stop the the bar in your table, and it reaches the box-shadow. I think it's a bug, and can be fixed using a white borders instead of transparent.

Appendix: How does box-shadow solution work?
See https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow

Formal syntax: none | [inset? && [ <offset-x> <offset-y>
  <blur-radius>? <spread-radius>? <color>? ] ]#

*

*inset: omitted, don't want it.

*<offset-x> <offset-y>: 0 0, because we don't want to move the shadow.

*<blur-radius>: 0, because we don't want a blurred shadow.

*<spread-radius>: 10px,  because we want the shadow to expand to be 10px wide.

*<color>: #d0d0ff

How could it be that you made the border transparent and the shadow
  colored, and you got the opposite result?

That's because border-spacing defines a shadow outside borders (unless you use inset)
From the spec:

An outer box-shadow casts a shadow as if the border-box of the element
  were opaque. The shadow is drawn outside the border edge only.

A: I would just use a container div and put the border on that with some padding:
http://jsbin.com/AcanusA/8/edit
Html becomes:

<th class="si .......

Additional CSS:
.outlined-container-1
{
width:70%;
}

.outlined-container-2
{
border: 10px solid #d0d0ff;
padding:20px;
}

.outlined
{
  width:100%;
  font:13px Tahoma;
  border-collapse: collapse;
}

Obviously change the outlined name to something more relevant.


text:
Q: Does the self-homeomorphism group of a finite CW complex have CW homotopy type? Let $X$ be a finite CW complex and form the group $\mathcal{H}(X)$ of self-homeomorphisms $X\xrightarrow{\cong}X$, furnishing it with the compact-open topology. Under the assumptions on our space $\mathcal{H}(X)$ is a topological group. My very simple question is the following:

If $X$ is a finite CW complex, then does $\mathcal{H}(X)$ have CW homotopy type?

I couldn't find this question addressed in the literature. To my knowledge it is an open question as to whether $\mathcal{H}(X)$ is an ANR, even when $X$ is a (smooth) compact manifold (although it is in case that $\dim X=1,2$). Note however that I am asking for something much weaker.


text:
Q: Error al leer string Estoy empezando a aprender c++ y he desarrollado el siguiente programa que me da un error al leer la variable nombre, la he puesto de tamaño 1 ya que solo quiero leer la inicial del nombre y no consigo entender porque da error, gracias de antemano.
string nombre[1];
string apellido1;
string apellido2;
string nombreyapellidos;

cout<<"Nombre: ";
cin>>nombre;
cout<<"ap1: ";
cin>>apellido1;
cout<<"ap2: ";
cin>>apellido2;

nombreyapellidos=apellido1+" "+apellido2+" "+nombre;
cout<<nombreyapellidos;

A:
Lo he puesto de tamaño 1 ya que solo quiero leer la inicial del nombre.

Ahí está tu malentendido. En C++ puedes tener formaciones1 de cualquier cosa2 y lo que tendrás será esa cosa repetida tantas veces como el tamaño que especifiques.
Has entendido bien que nombre[1] es una formación de un solo elemento, lo que no has entendido es de qué es la formación. Has creado una formación de un objeto std::string.
El objeto std::string se usa para guardar cadenas de caracteres, si lo que quieres es guardar una sola letra necesitas un tipo de dato que guarde una sola letra, por ejemplo char.
O bien lee el nombre al completo pero escribe sólo la primera letra:
string nombre, apellido1, apellido2;
//     ^^^^^^ <-- Cadena de caracteres, no formación

cout << "Nombre: ";
cin >> nombre;

cout << "ap1: ";
cin >> apellido1;

cout << "ap2: ";
cin >> apellido2;

string nombreyapellidos;
nombreyapellidos = apellido1 + " " + apellido2 + " " + nombre[0];
//                   Primera letra de la cadena 'nombre' --> ^^^

cout << nombreyapellidos;

1También conocidas como arreglos o en inglés arrays.
2Bueno, cualquier cosa no, cualquier cosa excepto referencias.


text:
Q: How to make sure map is loaded with google-map-react I am using google-map-react and need to have access to the map.
I access the ref through doing something like:
<GoogleMap ref={ref => this.map = ref} />

When I call the ref on componentDidMount() like so this.map.map_ it returns null because the map has not loaded yet. I need a way to access this when the component mounts.

A: I think you can use onGoogleApiLoaded:
handleGoogleApiLoaded = ({map, maps}) => {
  map...
}

<GoogleMap
  onGoogleApiLoaded={this.handleGoogleApiLoaded}
  yesIWantToUseGoogleMapApiInternals
/>


text:
Q: how to change column type counter to bigint in cassandra? CREATE TABLE temp (
    id bigint PRIMARY KEY,
    date timestamp,
    count counter
)

I have a cassandra table^ . I want to change field type counter to bigint.
ALTER TABLE temp ALTER count TYPE counter ;

ConfigurationException:  ErrorMessage code=2300 [Query invalid because
  of configuration issue] message="Cannot change count from type bigint
  to type counter: types are incompatible."

A: Counters are treated as special types in Cassandra, which is why only counter types are allowed as non-key fields in counter tables.  NOTE: Your table definition cannot be correct, as the date column needs to be a part of the key for the above definition to be valid.
Your best option here, is to COPY your table to a file from CQLSH:
aploetz@cqlsh:stackoverflow> COPY countertest TO 'countertest_20151028.csv'
                             WITH DELIMITER='|' AND HEADER=true;

3 rows exported in 0.008 seconds.

Then DROP and re CREATE your table with count as a BIGINT.  And finally run COPY (FROM) to re-import the data to your new table.


text:
Q: Cannot Deserialize Nested JSON in C# I am new to programming and to C#.  I'm using Visual Studio (latest) to write my app.
This is a console app that is attempting to read a log (text) file where each line is a separate JSON entry.
This is what a single item JSON entry looks like:
{
    "timestamp": "2022-02-09T07:05:59Z",
    "event": "Color",
    "Hex": "#FFFF00",
    "Name": "Yellow"
}

I establish the full path to the text file and store it in a string 'fileFullPath' and I'm 'using System.Text.Json'.
Each entry in the text file always has two fields - 'timestamp' and 'event'.  I created a base class called 'LogHeader':
namespace LogModels
{
    public class LogHeader
    {
        public string TimeStamp { get; set; }
        public string Event { get; set; }

    }
}

Then, I created a class for each event and inherited from LogHeader:
public class Color : LogHeader
{
  public string Hex { get; set;}
  public string Name { get; set;}
}

Next, I read the file and start going through each line and writing to the console using a switch statement based on the 'event' field:
foreach (string line in File.ReadAllLines(fileFullPath))
{
  var logHeader = JsonSerializer.Deserialize<LogHeader>(line,options);

  switch (logHeader.Event)
  {
     case "Color":
       var eventColor = JsonSerializer.Deserialize<LogModels.Event.Color>(line, options);
       Console.WriteLine($"The color is {eventColor.Name}.");
       Console.WriteLine($"The Hex value is {eventColor.Hex}.");
     break;
  }

The console output is:

The color is Yellow.
The Hex value is #FFFF00.

The problem comes in with the nested JSON objects, which look like this:
{
    "timestamp": "2022-02-09T07:07:52Z",
    "event": "Carpet",
    "Shag": [
        {
            "Color": "Green",
            "Count": 3
        },
        {
            "Color": "Black",
            "Count": 104
        }
    ],
    "Pile": [
        {
            "Color": "Blue",
            "Count": 5
        },
        {
            "Color": "Beige",
            "Count": 13
        }
    ],
    "Outdoor": [
        {
            "Color": "Pebble",
            "Count": 300
        },
        {
            "Color": "Astroturf",
            "Count": 12
        }
    ]
}

At this point, I'm lost.  I've tried creating a class called "Carpet" with child classes called "Shag", "Pile", etc.  I've tried creating separate classes for each of the subtypes.
The desired outcome is for this to appear on the console:

Shag Carpet -
Green: 3
Black: 104
Pile Carpet -
Blue: 5
Beige: 13
Outdoor Carpet -
Pebble: 300
Astroturf: 12

I can't imagine this is as hard to do as I'm making it out to be, but I can't seem to find any examples to help me through it.
Also, I've only posted to this site a couple of times, and I'm not sure of the proper structure of replying to suggestions, etc.
Thank you for your help with this.

A: Since you are new to programming and to C#, I highly recommend you to use Newtonsoft.Json serializer.
You can try this code
Data data = JsonConvert.DeserializeObject<Data>(json);

classes
public class Data
{
    [JsonProperty("timestamp")]
    public DateTime TimeStamp { get; set; }
    [JsonProperty("event")]
    public string Event { get; set; }
    public string Hex { get; set; }
    public string Name { get; set; }
    public List<ColourCount> Shag { get; set; }
    public List<ColourCount> Pile { get; set; }
    public List<ColourCount> Outdoor { get; set; }
}

public class ColourCount
{
    public string Color { get; set; }
    public int Count { get; set; }
}

you can test using reflection
    var props = data.GetType().GetProperties();

    foreach (var prop in props)
    {
        if (!prop.PropertyType.IsCollectible)
        {
            if(prop.GetValue(data)!=null)
            Console.WriteLine($" {prop.Name} : { prop.GetValue(data).ToString()} ");
        }
        else
        {
            Console.WriteLine($" { prop.Name} - ");

            var items = prop.GetValue(data) as IList<ColourCount>;

            foreach (var item in items)
            {
                Console.WriteLine($" {item.Color} : {item.Count}");
            }
        }
    }

result
 TimeStamp : 2022-02-09 7:07:52 AM
 Event : Carpet
 Shag -
 Green : 3
 Black : 104
 Pile -
 Blue : 5
 Beige : 13
 Outdoor -
 Pebble : 300
 Astroturf : 12

if you still want to use Text.Json change property name attribute
Data data = System.Text.Json.JsonSerializer.Deserialize<Data>(json);

public class Data
{
    [JsonPropertyName("timestamp")]
    public DateTime TimeStamp { get; set; }
    [JsonPropertyName("event")]
    public string Event { get; set; }
    .....
}

A: Here's how I did it, thanks to Serge's examples:
public class Carpet
{
    public List<ColourCount> Shag { get; set; }
    public List<ColourCount> Pile { get; set; }
    public List<ColourCount> Outdoor { get; set; }
}

public class ColourCount
{
    public string Color { get; set; }
    public int Count { get; set; }
}

In the switch statement:
  case "Carpet":
     var eventCarpet = JsonSerializer.Deserialize<LogModels.Event.Carpet>(line, options);

     foreach (var shag in eventMaterials.Shag)
     {
        Console.WriteLine($" {shag.Color}: {shag.Count}.");
     }

     foreach (var pile in eventMaterials.Pile)
     {
        Console.WriteLine($" {pile.Color}: {pile.Count}.");
     }

     foreach (var outdoor in eventMaterials.Outdoor)
     {
        Console.WriteLine($" {outdoor.Color}: {outdoor.Count}.");
     }

  break;

This gives me the desired output to console (minus the 'fluff'):

Green : 3
Black : 104
Blue : 5
Beige : 13
Pebble : 300
Astroturf : 12

I know this is probably the Fisher-Price version of what you did, but thanks again for your help!


text:
Q: How to automatically pull data from client's webservice I am trying to find the best solution to build the application at work.
1) My client has a web service, I need to have a automatically process to pull data from client web service, store in a database. The data will be displayed in a aspnet MVC web application. Once new data coming in, I want to notify the current user (something like a badge)
Question 1: I have two ideas for the process to pull data from client's web service,
           A)I create a WCF service, and host it as a Windows Service
           B)Create a console application and get the schedule task to run the console application
Question 2: I am thinking to use SignalR to indicate users of the new data, but in the backend how do get SignalR to check the data changes?
Thanks very much guys
Regards

A:
Question 1: I have two ideas for the process to pull data from
  client's web service, A)I create a WCF service, and host it as a
  Windows Service B)Create a console application and get the schedule
  task to run the console application

Did you mean WCF client? To pull data from client's web service you need a WCF client not a service? The rest looks ok to me here.

Question 2: I am thinking to use SignalR to indicate users of the new
  data, but in the backend how do get SignalR to check the data changes?

SignalR is just a mean to send notifications to clients. The way you check for updates depends on the nature of the notification. So you would better elaborate on this part to get a better advice. A common way to do it is to have a notifications log table/queue which you can check for updates, process them and send to the clients. Don't forget to remove or mark processed notification in the table.
Alternatively, you can host SignalR in a windows service with a WCF client and a timer to pull data from web services. You can notify your web users directly from the windows service. Please see this article Tutorial: SignalR Self-Host
Hope it help!


text:
Q: Auto increment the id when date is changed Is there a way in mysql to auto increment an ID when the date is changed?
I have a table like this and the id must be auto increment when the day is changed.

ID
Name
Date Time

1
Adi
2022-06-29 17:00:00

1
Adi
2022-06-29 17:00:00

1
Adi
2022-06-29 17:00:00

2
Adi
2022-06-30 17:00:00

2
Adi
2022-06-30 17:00:00

3
Adi
2022-07-01 17:00:00

3
Adi
2022-07-01 17:00:00

4
Adi
2022-07-02 17:00:00

4
Adi
2022-07-02 17:00:00


text:
Q: Migrating Wordpress to IIS convert .htacces to web.config An outside company is making a website, they are working on LAMP, there is an IIS server at our place so I have to prepare this server for the implementation. Preliminarily it has been prepared (I mean it works normally) however there is a problem with the plugin that substitutes jpg files for webp (webp-express plugin). The entire wordpress folder has an awful lot of .htaccess files ~25, most of them are almost empty so converting to web.config would not be a problem. The problem gets when, some htaccess files don't pass through URL Rewriter(that function in the panel with import roles).
RewriteRule (?i)(.*)(\.jpe?g|\.png)$ /wp-content/webp-express/webp-images/uploads/%2%3\.webp [T=image/webp,E=EXISTING:1,E=ADDVARY:1,L]

RewriteRule (?i).*$ /wp-content/plugins/webp-express/wod/webp-on-demand.php [E=WE_WP_CONTENT_REL_TO_WE_PLUGIN_DIR:../../,E=WE_SOURCE_REL_HTACCESS:$0,E=WE_HTACCESS_ID:uploads,NC,L]

Both of these rules return an error
<!-- The rule cannot be converted into an equivalent IIS format unsupported flags:E-->

What will you advise to do in this situation? As a last resort, if nothing goes I will urge to change to Linux.