text:
Q: Looping Through FileReader onload Jquery I need to loop through all my inputs that are type file, and load it as a preview. My code so far:
var _i = 0;
function setImagesToPreview(){
  $("form#form-generate-mail input[type=file]").each(function(i){
    var input = $(this);
    _i = i;

    if (input.context['files'] && input.context['files'][0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        $(document).find("div.modal-preview-mail img.image_placeholder:nth-child("+_i+")").attr('src', e.target.result);
      }

      reader.readAsDataURL(input.context['files'][0]);
    }
  });
}

The following code works, but for only 1 input. The reason for this, is that the variable 'i' that is acting as the counter, when it reaches the reader.onload, the variable is set to the final value.
ex: 5 inputs, the counter 'i' increments by 1 everytime, from 0 to 4, but once it gets to the reader.onload, it always displays 4 and never increments.
Any help will be usefull, thanks in advance.

A: I think you need to create a context like so ....
  reader.onload = (function(index){
        return function (e) {
             $(document).find("div.modal-preview-mailimg.image_placeholder:nth-child("+index+")").attr('src', e.target.result);
      };
})(_i);

A: Just wrap the inner code with an IIFE. Thus you're creating a new execution context and the current state of i is saved in it.
Brief example:
for (var i = 0; i < 5; i++) {
    (function(i) {
        setTimeout(function() { console.log(i); }, 50 * i);
    })(i);
}


text:
Q: Why is Supergirl so weak? In Superman/Batman: Apocalypse, it's shown that Supergirl's cellular structure is much more dense than Superman and that Supergirl is supposed to be much more powerful.
Why is it then that she gets hurt much easier than Superman and she's not as quick or strong?

A: Two likely possibilities haven't been mentioned yet:
It's probably proportional
Kryptonian strength is usually described in relation to human equivalents (that is, Superman isn't terribly "super" among his own people).  Even if Kara's physiology metabolizes sunlight more efficiently than Clark's, she's still substantially smaller and less muscular than he is, so she might still end up being weaker.
If I'm getting a 200% boost to a natural strength of 10, and you're getting a 300% boost to a natural strength of 3, I'm still ultimately going to be stronger than you.
Toughness isn't purely biological
I know plenty of 90-pound girls who can take a punch to the gut without flinching, and I know plenty of body-builders who cry when they get poked with a syringe.
Kara is Kryptonian, so she's "tough" in the sense that it takes a lot of force to damage her biological tissues, but mentally and behaviorally she's still a normal, teenaged girl.  By contrast, Clark grew up working on a farm, and has spent years (decades?) fighting and pummeling incredibly tough opponents in one-on-one combat.
It could be that Kara is stronger and tougher than Superman statistically, but her inexperience and lack of combat training prevent her from being as effective in a fight.

A: Although Batman says her celluar structure is a "shade" denser and that "she metabolizes sunlight more efficiently," Superman has been on Earth for many years, whereas she has only just arrived. She hasn't had as much time to absorb radition from Earth's yellow sun as Superman has.
Batman also says "bottom line, she might be more powerful than you"+
There is no guarantee that she is or will be.
+Emphasis added

A: I think that she is younger than Superman. She will be as strong as him when she reaches the same age.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I filter embedded documents within a document? I was doing an integrated assignment consisting a lot of database operations and I was going okay until I had trouble filtering embedded documents within a documents.
My document looks like
{
    flightId: "IND-101",
    AircraftName: "Delta Airlines",
    fare: 600,
    availableSeats: 5,
    status: "Running",
    bookings: [
        {
            customerId: "P1001",
            bookingId: 2001,
            noOfTickets: 3,
            bookingCost: 1800
        },
        {
            customerId: "S1001",
            bookingId: 2003,
            noOfTickets: 2,
            bookingCost: 1200
        }
    ]
},
{
    flightId: "IND-102",
    AircraftName: "JetBlue",
    fare: 750,
    availableSeats: 20,
    status: "Cancelled",
    bookings: [
        {
            customerId: "P1001",
            bookingId: 2002,
            noOfTickets: 3,
            bookingCost: 2250
        },
        {
            customerId: "G1001",
            bookingId: 2004,
            noOfTickets: 2,
            bookingCost: 1500
        }
    ]
}

I have tried the below code but obviously, it is returning all the booking documents.
return flightModel.find({ $and: [{ flightId: flightId }, { "bookings.customerId": customerId }] }, { bookings:1, _id: 0 })

The variables flightId and customerId are given using a function.
If I give flightId as IND-101 and customerID as P1001, then the desired output is
{
        customerId: "P1001",
        bookingId: 2001,
        noOfTickets: 3,
        bookingCost: 1800
    }

So how can I do this? How can I select a particular embedded document based on a filtering condition?

A: You can run an aggregate query to $filter and $project the fields you need.
Something like this should work.
let pipeline = [
  {$match: {flightId: flightId}},
  {$filter: {
    input: '$bookings'
    as: 'booking',
    cond: {$eq: {'$$booking.customerId', customerId}}
  }},
  {$project: {
    bookings: "$bookings"
  }}
]

flightModel.aggregate(pipeline);


text:
Q: Are Child Packages safe in ADA? I am very new to ADA language and, during my learning process, I have been seeing a lot of examples which uses this ADA functionality.
It seems to me that it could be useful only for unit testing in order to being able to test the private types and methods of the parent package, but I don't see any advantage for coding in such way, it seems that breaks encapsulation.
Is it a good practice to use them apart from unit testing?

A: Child packages can be seen as an extension for their parent.
It can be used, for example, to provide functionalities that are not directly linked to your base package.
The typical example is the Input-Output package.
Imagine the following package :
package Temperature is

    type Kelvin_Temp is private;
    type Celsius_Temp is private;

    function build (temp : Positive) return Kelvin_Temp;
    function build (temp : Integer) return Celsius_Temp;

    function to_celsius (temp : in Kelvin_Temp) return Celsius_Temp;

    function to_kelvin (temp : in Celsius_Temp) return Kelvin_Temp;

  private
    type Kelvin_Temp is 0.0 .. 10_000.0;
    type Celsius_Temp is -273.0 .. 10_000.0;
end Temperature;

This package provides basic operations directly linked to the types defined.
What if you want to extend it to provide I/O in text format ?
You can decide to put operations inside the Temperature package but if you want to add other types of I/O such as database I/O, you will have a lot of functions that are not directly linked to your types inside the same file.
You can define
package Temperature.Text_IO is

    procedure Put(temp : Celsius_Temp);

    procedure Put(temp : Kelvin_Temp);

end Temperature.Text_IO;

and
package Temperature.Database_IO is

   procedure insert (Temp : in Celsius_Temp);

   procedure insert (Temp : in Kelvin_Temp);

end Temperature.Database_IO;

That's exactly what is done with IO in the standard library
From an encapsulation point of view, your private types will remain private outside of the package hierarchy so you don't break encapsulation.

A: You can take a look at this presentation given at FOSDEM 2018, discussing (private) packages and enforcing safety:
https://archive.fosdem.org/2018/schedule/event/ada_safety/

A: Child packages exist to allow programming by extension, but as implemented they also provide a way to bypass the information hiding that pkgs are supposed to enforce.
While it can be convenient to design a hierarchy of pkgs sharing some hidden information, programming by extension is generally a poor idea that emphasizes ease of writing over ease of reading, and coding over software engineering. You might be interested in the article "Breaking the Ada Privacy Act", available here.


text:
Q: How can I use regular expressions to remove item from querystring data? I'd like to use a regular expression function to remove an item from a querystring based on the key.
Say I have a querystring like this:
page.asp?item1=data1&item2=data2&item3=data3

I would like to call a function like this:
newQs = removeQsItem(url, "item2")

...and have that function return this:
page.asp?item1=data1&item3=data3

... but I also need it to work if called with item 1 or 3 - regardless of their position in the querystring.
My tactic so far it to try and grab "requiredItem={anything but ampersand here}". But I'm really struggling with regex syntax and my brain is about to melt.
Any help would be greatly appreciated.

A: Does it have to be with a RegEx?  Can you just do some string functions like getting the StrPos of the given string "item2" then finding the StrPos of the next ampersand then just SubString those positions out to get "item2=data2&" (you may have to add 1 to the index of that second postion to actually get the ampersand?) the just do a myQueryString.Replace(substringToRemove, "") to replace that substring with nothing?

A: I'm not an expert at regular expressions, but I have been trying to learn. So I did some research (and trial & error), and came up with this.  Someone else can probably make this cleaner.
(\bitem2=[A-Za-z0-9]*&|&\bitem2=[A-Za-z0-9]*$|^\bitem2=[A-Za-z0-9]*$)

I'll explain it a bit.  First, there's 3 searches in one.

*

*The first one finds your item IF it's followed by a ampersand & (so we can
remove the trailing &)

*The second one finds your item IF it's the last item (so we can
remove the preceding &)

*The last one is if your item is the ONLY item.

The code:

*

*( this | that ) means OR. Match this OR that.

*\b matches a word boundery. So we know we're matching a whole word,
and not just part of one.

*[A-Za-z0-9]* matches zero or more letters or numbers. Zero in case you have an empty value.

*$ matches the end of line

*^ matches the start of line


text:
Q: SharpDX on Windows form - Race condition when minimizing screen I have a problem that I couldn't be able to fix since one week, I hope someone could have ever experienced this.
I'm using SharpDX with a windows form project, basically there is a form with a picturebox and some panel over it.
The typical Swapchain.Present(1,PresentFlags.None) works good when I zoom or translate the image. However I get this strange situation where when I minimize my screen and reopen it back, all the swapchain content is hidden like if it has been erased. However, I know it hasn't and this is probably a race condition between GDI refresh and SharpDX.
So, I tried to overrides WndProc(Message m) in every control and handle it's paint and eraseBackground event. This is not working. When I debug, windows message are always different from time to time so it is quite hard to figure out what could be wrong.
If anyone has ever experience this behavior while mixing SharpDX(or directX) on Windows form, I would really like an answer.
Here is how I handle the resize event of my SharpDX DeviceContext
Public Overrides Sub Resize(Width As Integer, Height As Integer)
      If m_SwapChain IsNot Nothing Then
         If m_BackBuffer IsNot Nothing Then
            m_BackBuffer.Dispose()
         End If
         If m_2DDeviceContext IsNot Nothing Then
            m_2DDeviceContext.Dispose()
         End If
         If m_2DTarget IsNot Nothing Then
            m_2DTarget.Dispose()
         End If

         m_SwapChain.ResizeBuffers(2, Width, Height, Format.B8G8R8A8_UNorm, SwapChainFlags.GdiCompatible)

         m_BackBuffer = m_SwapChain.GetBackBuffer(Of Surface)(0)

         m_2DDeviceContext = New SharpDX.Direct2D1.DeviceContext(m_2DDevice, SharpDX.Direct2D1.DeviceContextOptions.EnableMultithreadedOptimizations)

         m_2DTarget = New SharpDX.Direct2D1.Bitmap(m_2DDeviceContext, m_BackBuffer, m_Properties)
         m_2DDeviceContext.AntialiasMode = AntialiasMode.PerPrimitive

         m_2DDeviceContext.Target = m_2DTarget

         CType(m_Context, GPUDrawingContext).DeviceContext = m_2DDeviceContext
      End If

   End Sub

EDIT :
After trying many stuff, I realize it was happening right when I call base.Wndproc(m) where m = WM_PAINT.
I can't ignore the paint message because if I do, my control is still invalidated and it will add a new WM_PAINT to the event queue and send me into an infinite loop. I really cannot do base.Wndproc(m) because this is where my swapchain gets hide.
Is their any way to handle(ignore) this event message without having it back in the loop because SharpDX doesn't require this function since it's a paint layer over the control.

A: When you just want to resize the swapchain you don't have to recreate the DeviceContext. Maybe here is the first cause of your problem, because the swapchain was created with a different DeviceContext than the backbuffer.
For me this is working in C#:
first add eventhandlers to the resize events of the control. No need to override the WM_PAINT:
form.ResizeBegin += (o, e) => {
    formHeight = ((Form)o).Height;
    formWidth = ((Form)o).Width;
};
form.ResizeBegin += (o, e) => {
    isResizing = true;
};
form.ResizeEnd += (o, e) => {
    isResizing = false;
    HandleResize(o, e);
};
form.SizeChanged += HandleResize;

with this I can save the old size of the control for comparison. And I'm just resizing the swapchain after the resize is finished and not for every event (like when resizing a window). Also I will only resize if the control is not minimized:
private void HandleResize(object sender, System.EventArgs e) {
    Form f = (Form)sender;
    if ((f.ClientSize.Width != formWidth || f.ClientSize.Height != formHeight)
        && !isResizing
        && !(f.WindowState == FormWindowState.Minimized)) {
        formWidth = f.ClientSize.Width;
        formHeight = f.ClientSize.Height;

        DoResize(formWidth, formHeight);
    }
}

Finally DoResize is following (renderTarget is my custom class):
private void DoResize(int width, int height) {
    renderTarget.Dispose();
    swapChain.ResizeBuffers(1, width, height, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
    using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0)) {
        //recreate the rendertarget with the new backbuffer
        renderTarget.Resize(width, height, resource);
    }
}


text:
Q: ASP.NET MVC CrystalReportViewer - Exception with max number report processing We had problem with usages of CrystalReportViewer for ASP.NET MVC (webforms control from SAP). Sometimes we get this exception:

CrystalDecisions.Shared.CrystalReportsException: Report could not be loaded.
System.Runtime.InteropServices.COMException: The maximum number of report processing requests set by your system administrator has been reached.

Notes - WebForm page:
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" HasRefreshButton="True" />

In C# is only set ReportSource and then is stored to the ASP.NET MVC session.
We save in code object ReportDocument (CrystalReportViewer.ReportSource) to the ASP.NET MVC session.
After session ends we call ReportDocument.Close() and ReportDocument.Dispose().
But still are information about reports somehow in memory and user got exception with max number of reports. Only what helps is on ISS recycle application pool or set some high number in Windows registry (\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Report Application Server\Server\PrintJobLimit).
Do someone know how should be ReportDocument/ReportViewer properly cleared ?


text:
Q: Science fiction novel where Earth is invaded by aliens landing at the North Pole I'm looking for an old sci-fi book which I read about 13-15 years ago. Unfortunately there isn't much I recall, only few bits and pieces from the first book:
The story is about Earth being invaded by aliens. An empty ship approaches Earch (similar to RAMA), lands on the North pole, and later aliens start to pour out  of it  (ship seems to be serving as some kind of "Ark" for teleportation) attacking Earth.
The name of the main character - female, sergeant in the military, is "Four", or at least I recall it as being translated into my language as "Four" (Четири).
Sadly, that's about all I recall from the book. Been searching for awhile trying to  find it and/or remember more so I can re-read it but so far my search has been futile.
Does this ring any bell to anyone?


text:
Q: How to set up multiple email targets for Post-commit notification in VisualSVNServer? I am trying to set up multiple email targets for post-commit email notification.
I have tried comma separated emails including quotes and with separate quotes as below.
"%VISUALSVN_SERVER%\bin\VisualSVNServerHooks.exe" ^
    commit-notification "%1" -r %2 ^
    --from "svn.server_zenforte@zensar.com" --to "hsalunkh@abcd.com","hrushikesh.salunkhe@abcd.com" ^
    --smtp-server javamail.abcd.com

Email notification should be sent to multiple email ids on commit.

A: Resolved.
Turns out that mailing server I'm using will send emails only to mails with same domain name.


text:
Q: Javascript adding multiple arrays in a loop I am trying to add multiple arrays in javascript.
Here are my arrays I have made, and are working.
function getAmountSpent(){

    var amountSpent = ((Math.random() * 500) + 1);
    return amountSpent.toFixed(2)
}

function getGift(){
    var gift = ((Math.random()* 50) + 1);
    return gift.toFixed(2)
}

var names = ["Jeremy","Arun","Alisa","Rohan","Dana"];

var spent = [];
for (let i = 0; i < 5; i++) {
spent.push(getAmountSpent());
}

var gifts = [];
for (let i = 0; i<5; i++) {
gifts.push(getGift());
}

What I need help with is adding these arrays in a new function. I have began writing the code, and I am not sure what is wrong.
var totals =[];
for (let i=0; i<5; i++) {
totals.push(getSumTotals())
}

function getSumTotals(a){
    totals= spent+(spent * gifts);
    return totals.toFixed(2)

}

From what you can see, I am trying to add up the totals much like this:
totals[0] = spent[0] + (spent[0] * gifts[0]);
totals[1] = spent[1] + (spent[1] * gifts[1]);
totals[2] = spent[2] + (spent[2] * gifts[2]);
totals[3] = spent[3] + (spent[3] * gifts[3]);
totals[4] = spent[4] + (spent[4] * gifts[4]);

if it helps, the professor added guided instructions for function getSumTotals(a) stating:
  This function will return the sum of the elements in array a.
  You will be passing the array that holds your totals to
  the parameter a. Be sure to treat the values in a as numbers.

I am not sure if this helps but here is the output to my document.
Current Total should equal (spent) + (spent * gifts). For instance, for Jeremy in this example, current total should equal:
$36.55 + ($36.55*0.0626) = $38.83. Since there are many variables involved, I am not 100% sure what I should write for function getSumTotals(a)
The parameter "a" is a placeholder because I am not sure how many parameter values I need, and the proper format I need to use.

A: As for the code...
You're both

*

*not passing an index to getSumTotals

*not using this parameter within getSumTotals to access your spent and gifts arrays

var totals =[];
for (let i=0; i<5; i++) {
  totals.push(getSumTotals(i)) // you were missing i
}

function getSumTotals(idx) { // I took liberties to rename this
  totals = spent[idx] + (spent[idx] * gifts[idx]);
  return totals.toFixed(2);
}

Now for the Math...
All that said, this math of spent[i] + spent[i] * gifts[i] doesn't make much sense either.  Was this specified in the problem?

A: you may use like this
defined gifts
gifts=[45,43,32];

defined spends
spends=[43,32,21];

this is the getSumTotal funtion
getSumTotal=(x)=>(x.a+x.b)

this is where added
totals=gifts.map((d1,i)=>{
    return fu({a:gifts[i],b:spends[i]})
})

A: Note, that toString returns a type of "String", but not "Number".
When you try to sum a number with string, you get a concatenated string "1" + 2 = "12"
To turn a string into Number, you must use a Number("str") function, or just a bunary + before the string:

console.log( "1" + 2 );
console.log( Number("1") + 2 );
console.log( +"1" + 2 );

Also, you use the same loop 3 times, but can use just one loop instead, and call all functions inside the one loop. And use your array.length instead of fixed number 5:

let names = ["Jeremy", "Arun", "Alisa", "Rohan", "Dana"];

let spent = [];
let gifts = [];
let totals = [];

for (let i = 0; i < names.length; i++) {
  spent.push( getAmountSpent() );
  gifts.push( getGift() );
  totals.push( getSumTotals(i) );
}

console.log( totals );

function getAmountSpent() {
  return rand(1, 500, 2);
}

function getGift() {
  return rand(1, 50, 2);
}

function getSumTotals(i) {
  return +( spent[i] * ( 1 + gifts[i] ) ).toFixed(2);
}

function rand(from, to, fixed = 0){
  return +(Math.random()*( to - from ) + from).toFixed(fixed);
}

P.s. Math.random() returns a number between 0 (included) and 1 (not included). If you need a random number between (example) 20 and 100, Math.random()*(100-20) will give a number between 0 and 80. After adding +20 to the result, you get a number from 20 to 100. That's what does this formula Math.random()*( to - from ) + from
P.P.s. Another way, to get the same thing:

var names = ["Jeremy", "Arun", "Alisa", "Rohan", "Dana"].reduce( (prev, elem) => {
  let spent = rand(1, 500, 2);
  let gift = rand(1, 50, 2);
  prev[elem] = new UserData( spent, gift );
  return prev;
}, {});

console.log( "Jeremy spent: " + names.Jeremy.spent );
console.log( names );

function rand(from, to, fixed = 0){
  return +(Math.random()*( to - from ) + from).toFixed(fixed);
}

function UserData(spent, gift){
  this.spent = spent;
  this.gift = gift;
  this.total = +(spent * ( 1 + gift )).toFixed(2);
}

/* Google → Array reduce, Constructor functions */

A: I understand this is your assignment, however - if the idea is to both generate arrays, and then add them together, it is a redundant step. Just use the name array to iterate once and do all your calculations within that single loop.
Here, I had some fun and took some liberties, but hopefully you see why multiple arrays are redundant.

function getSumTotals() {
  const getAmountSpent = () => Math.random() * 500 + 1;
  const getGift = () => Math.random() * 50 + 1;
  const names = ["Jeremy", "Arun", "Alisa", "Rohan", "Dana"];

  let totals = []

  names.forEach((name, i) => {
    let spent = getAmountSpent()
    let gifts = getGift()
    let $$$ = (spent + spent * gifts).toFixed(2);
    totals[i] = $$$

    console.log(`${name} cost me $${$$$}${'!'.repeat(($$$/1000) | 1)}`)

  });

  return totals;
}
getSumTotals()

A:

    function getAmountSpent(){
        let amountSpent = ((Math.random() * 500) + 1);
        return Number(amountSpent.toFixed(2))
    }

    function getGift(){
        let gift = ((Math.random()* 50) + 1);
        return Number(gift.toFixed(2))
    }

    let names = ["Jeremy","Arun","Alisa","Rohan","Dana"];

    let spent = [];
    let gifts = [];
    let totals =[];
    for (let i = 0; i < names.length; i++) {
        spent.push(getAmountSpent());
        gifts.push(getGift());
        totals[i] = (spent[i]+(spent[i] * gifts[i])).toFixed(2);
        totals[i] = parseFloat(totals[i])
    }

Hi there
I don't think you need a function to add the totals. you just need to loop through and assign totals[i] to spent[i] + (spent[i] * gifts[i]).
then you can use the parseFloat and toFixed function to change the string to a number. remember toFixed() function turns numbers to string. so you need to use the parseFloat to change it to number again as shown in the code above. or you can come up with an easy way of changing it to number. I hope this helps!


text:
Q: Code broken for adding Download Link to Wordpress Default Audio Player The codes to add download links automatically to audio embeds used to work, and now, suddenly i get errors saying Uncaught TypeError: $ is not a function...
i am totally confused as to why
Sample link is https://mpmania.com/download-mp3/wizkid-ghetto-love-audio/
Ive used troubleshooting mode, deactivated all plugins, updated outdated ones, probably someone can help with rewriting these codes to work
$( document ).ready(function() {
    $('audio').each(function( index ) {

        var source = $(this).find('source').attr('src');

        if ( source != '' ) {
            $(this).after('Download (Alternative)');
        }

    });
});

I basically expect it to work as it used to

A: Expanding on my comment above, your code should look like this:
jQuery(function($) {
    $('audio').each(function(index) {
        var source = $(this).find('source').attr('src');
        if (source != '') {
            $(this).after('Download (Alternative)');
        }
    });
});


text:
Q: Link to a specific tab of an external page I need to put a link on my website which go to another website (so far nothing complicated :D)
The problem is that the page where the link goes has a content organized with tabs like that :

...

...

...

...

And the content is hidden/shown through javascript call :

What I want to do is making my link to point to this page with the last tab shown. Since I do not control the page itself (not on my website), I don't know how I can do this.
Do you guys have any idea how I can do it ?

A: Take an example of StackOverflow site
Now I will provide a link on my site, which will land on last tab of Stackoverflow

URL: https://stackoverflow.com/unanswered

Here we have a facility through the url which can land on any tab.
But in your case, you need to see the targeted site has the same privilege to do so.


text:
Q: ramaze locks uploaded files? Has anyone else encountered a file locking issue with Ramaze on Windows? All my uploaded files are being locked (I'm using the upload helper btw).
I'm using
- Ruby 1.93
- Ramaze-2012.04.14
- Rack-1.4.1
Thanks!

A: Answering my own question. Looks like the culprit's this line in ramaze/helper/upload.rb
@realfile = File.new(path) #--->this opens the uploaded/saved file, thus locking it

I patched my local copy of upload.rb with this --
class UploadedFile
    include Ramaze::Traited

    # Suggested file name
    # @return [String]
    attr_reader :filename

    # MIME-type
    # @return [String]
    attr_reader :type

    # Saved file object
    # @return [File]
    attr_reader :realfile #---> expose the variable so we can close it from the caller

And then in your caller, simply close the file after you save it, like so...
get_uploaded_files.each_pair{|k, v|
    v.save "upload/#{v.filename}"
    v.realfile.close #close the file handle
}

I will be submitting a patch soon...


text:
Q: Convert ImageView Vector Drawable to Bitmap Android I take a fingerprint from the user and add white background to it using glide. The issue is I need to get the byte array of that image and I can't get it because the Image being hold into the ImageView is a VectorDrawable. I am unable to convert this back to bitmap and thus to a byte array. I tried using it on a dummy png image like following.
Take any dummy PNG Image
firstIV = findViewById(R.id.firstIV);
secondIV = findViewById(R.id.secondIV);

Bitmap currentBmp = BitmapFactory.decodeResource(getResources(), R.drawable.test_image);
Glide.with(this).load(currentBmp).into(new SimpleTarget<Drawable>() {
    @Override
    public void onResourceReady(Drawable resource, Transition<? super Drawable> glideAnimation) {
        final ShapeDrawable background = new ShapeDrawable();
        background.getPaint().setColor(Color.WHITE);
        final Drawable[] layers = {background, resource};

        firstIV.setImageDrawable(new LayerDrawable(layers));
        setToAnotherImageView(firstIV.getDrawable().getIntrinsicWidth(), firstIV.getDrawable().getIntrinsicHeight());

    }
});

Applied Solution
private void setToAnotherImageView(int width, int height) {
    Log.e(TAG, "onCreate: " + width + ":" + height);
    Bitmap convertedBmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(convertedBmp);
    firstIV.draw(canvas);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    convertedBmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    Bitmap newBmp = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
    secondIV.setImageBitmap(newBmp);
}

Upon doing so my app crashes with an exception saying the vector drawable can not be converted to bitmap. The following is the error:
Originally what I want to achieve
Originally I want the bytearray of the the picture I have stored in my ImageView so I can convert that bytearray to WSQ bytearray and the send it to my server. I am trying to achieve such with an example defined above.

A: UPDATE:
Just find out that there is a new way to get Bitmap from ImageView:
imageView.drawToBitmap()        //draw from the ImageView size
imageView.drawable.toBitmap()   //draw from original Drawable size (I guess)

Convert ImageView to ByteArray:
private fun getImageBytes(): ByteArray {
    val bitmap = Bitmap.createBitmap(my_profile_imageView.width, my_profile_imageView.height, Bitmap.Config.ARGB_8888)

    val canvas = Canvas(bitmap)

    my_profile_imageView.draw(canvas)

    val outputStream = ByteArrayOutputStream()

    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)

    return outputStream.toByteArray()
}

However, it's not a good idea to store the image ByetArray in local, you should store the uri or url instead.

A: My question is a duplicate of How to get a Bitmap from VectorDrawable
However I solved it like this
private void setToAnotherImageView() {
    Drawable drawable = firstIV.getDrawable();
    Bitmap newBmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(newBmp);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    secondIV.setImageBitmap(newBmp);
}


text:
Q: SEVERE: error registering connector Tomcat 5.5 I've try to deploy my project with Tomcat 5.5 (sounds dull :D)
But i have a trouble when using SSL with this error like this post.

An error occurred during a connection to localhost:7080.
SSL received a record that exceeded the maximum permissible length.
(Error code: ssl_error_rx_record_too_long)

And later i go and fix it with this post with this post with adding protocol="org.apache.coyote.http11.Http11Protocol"  into my Connector tag in my tomcat server.xml. But when i restart my tomcat, there is an error like this image (dont know how to copy this error through windows terminal)

And this is my server.xml connector tag
<Connector  port="8443" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" disableUploadTimeout="true"
           acceptCount="100" scheme="https" secure="true"
           clientAuth="false" sslProtocol="TLS"
           sslEnabled="true"
           keystoreFile="${user.home}/keystores/keystore_lipsweb_jetty.jks"
           keystorePass="jetty1" />
<Connector port="7080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true"
           URIEncoding="UTF-8"/>

Well, i still have no idea how to fix this. Really appreciate with your helps. Thanks

A: i did it like this and it worked for me
 <Connector className="org.apache.coyote.tomcat4.CoyoteConnector" port="80" minProcessors="5"
                   address="10.1.0.50"
                   maxProcessors="75"
                   enableLookups="false" redirectPort="443" acceptCount="10" debug="0" connectionTimeout="20000"
                   useURIValidationHack="false" URIEncoding="UTF-8"/>

<Connector port="443" maxHttpHeaderSize="8192"
                   address="10.1.0.50"
                   maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
                   enableLookups="false" disableUploadTimeout="true"
                   acceptCount="100" scheme="https" secure="true"
                   clientAuth="false" sslProtocol="TLS" SSLEnabled="true"
                   URIEncoding="UTF-8"
                   keystoreFile="/usr/java/default/jre/lib/security/keystore.jks"
                   keystorePass="password"/>

A: I've been resolve this problem by change my Tomcat version. When i create this post, i use Tomcat 5.5.36. But when i try to use an older one (5.5.26), There is no error on deployment and my project working properly.
Well, so far i don't know what the difference between Tomcat 5.5.36 and 5.5.26. I hope in few times i can explain what happen here in detail. But anyone who knows this thing can sharing here and i really appreciate it.


text:
Q: Whatever happened to Hiroko Ai in Kim Stanley Robinson's Mars Trilogy? After her disappearance, Sax thought he saw her in a blizzard (or maybe sandstorm), and remains convinced that he really has. But she is never seen by anyone again. What really happened with her?

A: In the very end of the entire series - very end - Ann comes near to death, and then sees an older Asian woman flying a kite at the sea's edge.
This is only speculation, but there seemed to me an enormous significance of birth to the closing being a combination of:
1) New birth (Ann & Sax together with children),
2) Blue Mars realized,
3) The horticulturist 'mother' of Mars Hiroko flying a kite (was it her?).
It seemed to be poignant to the author to point out the ethnicity and age of the last stranger seen in the last pages of the last book, by a couple who fought at extremes, to be in fact a very older Asian woman from Earth who was flying kites with kids.  Life, birth, growth - that was Hiroko Ai.
Since there's no concrete answer, this is my speculation.   I see Hiroko when I read those last couple pages.  Flying a kite while Ann and Sax are at the beach.

A: I think it's safe to say Robinson intentionally left it unanswered, though he I believe he had a most likely outcome in mind and tipped it off. It is significant that Hiroko had reached mythic status, sometimes being seen in two places at once. I don't think the Asian woman referenced at the end could be Hiroko, because she would have been recognized. She might have been a nod to the other false Hirokos like the one on Earth. To be honest, I am not sure where he was going with that, because it was hard to read it and not think of Hiroko (one final tease for the reader perhaps).
My own view, sadly, is that Coyote had it exactly right. Hiroko was killed in the initial attack and "disappeared" the way secret police have done time and again. No mystery to solve, just a grim and abrupt end. Sax hallucinated her and his later enhanced memory was just an echo of the hallucination. I would add as supporting evidence the fact that she did not even attempt to reconnect over a long series of funerals for the first hundred.
I find this ending unsatisfying but realistic. It is how I would read the same account laid out as non-fiction and see no reason to apply different logic here.
I would also make the case that Coyote's statement marks a significant development in the book. In the following passage, Robinson is tipping off the reader that "Mars exceptionalism" doesn't always hold, and sometimes the explanation can be as simple and brutal as any earth-bound banana republic. He does this through a high-credibility character (Coyote) who finally comes out with the point everyone else is afraid to voice (from Part Nine, Natural History):

Coyote shook his head violently. "No. I am the exception that proves
  the rule. Anyone else, when they are reported in two places at once,
  that means they are dead. A sure sign." He made a stop thrust to
  forestall Sax's next remark, shouted "She's dead! Face it! She died in
  the attack on Sabishii! Those UNTA storm troopers caught her and Iwao
  and Gene and Rya and all the rest of them, and they took them to some
  room and sucked the air or pulled the trigger. That's what happens! Do
  you think it never happens? Do you think that secret police haven't
  killed dissidents and then disappeared the bodies so that no one ever
  finds out? It happens! Fuck yes it happens, even on your precious Mars
  it happens, yes and more than once! You know it's true! It happened.
  That's how people are. They'll do anything, they'll kill people and
  figure they're just earning their keep or feeding their children or
  making the world safe. And that's what happened. They killed Hiroko
  and all the rest of them too."

A: Given the extreme circumstances that Sax found himself in, it is likely that he was simply hallucinating. The accounts of the Zygote survivors all indicate that Hiroko and a number of her inner circle were killed by the metanational forces.
Still - there were other rumours and apparent sightings, but as Mars became more populated no evidence of a new hidden colony was ever found. The first hidden colonies could only get away with hiding in the unpopulated south pole, so it seems unlikely that they could continue hiding once the Martian population started to grow and spread.

A: I think that what happened to Hiroki is that she becomes one of the Mars myths. This is the real intention of the author.
The difficulty to assert if something is real or myth is, in a sense, what science is about. In my opinion this is an important theme for K.S. Robinson. This is especially obvious in his book Icehenge.
In other words, my interpretation is that nobody knows what happened to Hiroki (even Robinson) because, he was searching to elicit in his readers this feeling of legend mixed with real character that makes you to ask the question in first place.


text:
Q: laravel router argument behaviour I notice that when you use URL:::action, and set some arguments, sometimes laravel would cast them as GET requests, sometimes not.
Is there anyone know why and how to controller it?
echo URL::action('Campaign\\CampaignController@getIndex',['para' => 1]),"
";
echo URL::action('Campaign\\CampaignController@getOtherAction',['para' => 1]),"
";
echo URL::action('Campaign\\CampaignController@getOtherAction2',['para' => 1]),"
";

Output:
/campaign?para=1
/campaign/other-action/1
/campaign/other-action2/1

Note the getIndex gets argument as GET (?para=1)

A: This happens because system cannot differentiate requests to getIndex from others if they pass it as url segment.
Means
/campaign/other-action/1 translates to other-action as a method with 1 as param
By your expectation
/campaign/other-action/1 translates to getIndex as a method with other-action/1 as param
Index methods are not suppose to have URL segments as inputs. If you need url segments as inputs then you will have to pass it as a get parameter and thats what laravel is doing for you.
According to your first route output,
if the url is /campaign/1 which means it will expect a method named get1. Another example: if the url is /campaign/param system would expect a method getParam
NOTE for fellow stackoverflow-ers:Consider asking questions before downvoting

A: I actually found the reason.
when you are using route::controllers method, laravel would assume you have multiple parameters attached to each action
Route::controllers([
        'order' => 'Order\OrderController',
        'campaign' => 'Campaign\CampaignController'
    ]);

For example:
campaign/other-action/{VALUE1?}/{VALUE2?}/{VALUE3?}...

So when you pass ['para' => 1, 'para2' => 'abc'], laravel will try to match parameters to action. in this case: campaign/other-action/1/abc
Avoiding to use Route::controllers, an help you take control on laravel router argument behaviour.
For example, in routes.php:
Route::get('campaign/other-action/{id}','Campaign\CampaignController@getOtherAction2')

when you give
echo URL::action('Campaign\\CampaignController@getOtherAction2',['id'=>366, 'para' => 1, 'para2' => 'abc']);

you will get what you want:
campaign/other-action/366?para=1&para2=abc

I hope it is helpful and I now understand why laravel remove Route::controllers from 5.3 version.


text:
Q: How to add external libraries to custom runtime image using jlink? I want to add external libraries needed by my project to the custom runtime image.
I use the following external libraries in my project: vlcj.jar, vlcj-javafx.jar
For vlcj.jar to work I also need to add external libraries: jna.jar, jna-platform.jar, vlcj-natives.jar
If I rewrite my application so that I don't need to use vlcj.jar and vlcj-javafx.jar, then the custom runtime image creation line looks like this:
jlink --no-header-files --no-man-pages --compress=2 --strip-debug --module-path 'path/to/javafx-jmods-15.0.1' --add-modules javafx.controls,javafx.web --output /path/to/RuntimeImage

Then I create the jar of my application:
cd path/to/myapp
jar cvfe path/to/myApp.jar MainClass *.*

Then I add myApp.jar to the RuntimeImage and run the app with:
cd path/to/RuntimeImage
path/to/RuntimeImage/bin/java -jar myApp.jar

The application starts up. Things are good.
The only bad thing is that it works without VLCJ.
How can I add external VLCJ libraries to the custom runtime image and run my application with it?

A: The custom runtime image does not support automatic modules (non-module jars) so you don't have any dependent jars in the jlink image which defines classpath for running with the vlc.
You can edit the META-INF\MANIFEST.MF in your own jar to specify a classpath so the extra jars could be read from the same directory you run java -jar:
Class-Path: vlcj.jar vlcj-javafx.jar jna.jar jna-platform.jar vlcj-natives.jar

Alternatively switch to standard launch for your application with explicit classpath:
path/to/RuntimeImage/bin/java -cp myApp.jar:vlcj.jar:vlcj-javafx.jar:jna.jar:jna-platform.jar:vlcj-natives.jar your.MainClass


text:
Q: Prevent original template being applied in inherited control I am having an issue in an application where I would like to derive my own custom control from a control included in a commercial library (scichart).
I am overriding OnApplyTemplate, as in the below code, but am running into an issue where when calling GetAndAssertTemplateChild (A function in the library that is pretty much the same as GetTemplateChild but throws and error if the result is equal to null) the part cannot be found in the template.
While investigating this issue I found that OnApplyTemplate is being called multiple times, it is first called with the template of the control being inherited from, and is then recalled with the template of the new control. Is there any way to avoid this and to never apply the base classes template.
public override void OnApplyTemplate()
{
    base.OnApplyTemplate();

    AnnotationRoot = GetAndAssertTemplateChild<Grid>("PART_LineAnnotationRoot");
    _line = GetAndAssertTemplateChild<Line>("PART_Line");
    _ghostLine = GetAndAssertTemplateChild<Line>("PART_GhostLine");
    _label = GetAndAssertTemplateChild<TextBlock>("PART_Label");
}

A:
Is there any way to avoid this and to never apply the base classes template

If you only want to call the derived class' OnApplyTemplate() method, you should avoid calling the base class' method in the overridden method:
public override void OnApplyTemplate()
{
    //DON't CALL THIS ONE: base.OnApplyTemplate();

    AnnotationRoot = GetAndAssertTemplateChild<Grid>("PART_LineAnnotationRoot");
    _line = GetAndAssertTemplateChild<Line>("PART_Line");
    _ghostLine = GetAndAssertTemplateChild<Line>("PART_GhostLine");
    _label = GetAndAssertTemplateChild<TextBlock>("PART_Label");
}

And if you want to provide your own default custom ControlTemplate from scratch, you should define a static constructor in your control class:
static YourControl()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(YourControl),
        new FrameworkPropertyMetadata(typeof(YourControl)));
}

...and define the default template in a ResourceDictionary called "generic.xaml" located in a folder called "Themes" at the root folder of the project in which the control class is defined.


text:
Q: How to get value from nested relations in Power Pivot? I'm using Power Pivot add-in to create a data warehouse for generate dynamic tables and graphs (strictly data source is Excel), but I have a problem whit a calculate in the relations. My data model is the following:
My Snowflake data warehouse model
So for the fact table "fSales" I need to multiply the dCostDetail[Value] per dWorkCost[Value] to generate the fSales[Expenses] amount.
I tried to use the formula but I get an error: related but it don't allow to nested between the relations, e.g. fSales[Expenses] = related(dCostDetail[Value])*related(dWorkCost[Value])
Also I tried to use the next formula:
fSales[Expenses] = related(dWorkCost[Value]) * Calculate(Calculate(Calculate(Value(dCostDetail[Value]), Userelationship(fSales[IdProduct],dProduct[Sku]),Userelationships(dProduct[IdCateg],dCategory[IdCategory]), Userelationships(dCategory[IdCategory],dCostDetail[IdCateg]))))

And I need this "type" of normalized model to have the details when I analyze the information, e.g. filter, but if you know another way to generate the calculation it would be ok.

A: RELATED doesn't work in measures, because it evaluates on a record-by-record level. So you're on the right track, but what you need to do is create a column in Powerpivot in the fSales table called "Cost Detail" or whatever, and use a RELATED formula there to pull in that value from the CostDetail table. Create another column and do the same thing to pull in the dWorkCost value into the fSales table.
Then you can do a measure for the expenses like this:
Expenses:=SUM([whatever you called CostDetailColumn])*SUM([whatever you called WorkCostColumn])
You should be able to drop that measure into a pivot and it should do what you're looking for.


text:
Q: How use title data in datatable json? I want the table title and table body use url to read data.
such as  "language": {url:'https://cdn.datatables.net/plug-ins/1.10.25/i18n/English.json'},

$(document).ready(function () {

 $('#example').DataTable({

  "language": {url:'https://cdn.datatables.net/plug-ins/1.10.25/i18n/English.json'},

  lengthMenu: [25, 50, 75, 100],

  data: {url:'/dataSet.json'},
  columns: {url:'/columns.json'}
  });

});

$(document).ready(function () {

 var dataSet = [
{"name":"name1","name2":"name2"},
{"name":"name1","name2":"name2"},
];

$('#example').DataTable({
 "language": {url:'https://cdn.datatables.net/plug-ins/1.10.25/i18n/English.json'},

  lengthMenu: [25, 50, 75, 100],

  data: dataSet,
  columns: [

{ title:"Title1",data: "name" },
{ title:"Title2",data: "name2" }

  ]

 });

});
 tfoot {

  display: table-header-group;
}
 }
 <!DOCTYPE html>

<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">

<meta charset=utf-8 />
<title>DataTables - JS Bin</title>

How can do that?
Any help would be appreciated.

A: Here is an example using a jQuery ajax approach:
Assume we have a URL which returns the following JSON:
{
  "responseData": {
    "headings": [
      {
        "title": "Name",
        "data": "name"
      },
      {
        "title": "Position",
        "data": "position"
      },
      {
        "title": "Salary",
        "data": "salary"
      },
      {
        "title": "Start Date",
        "data": "start_date"
      },
      {
        "title": "Office",
        "data": "office"
      },
      {
        "title": "Age",
        "data": "age"
      }
    ],
    "body": [
      {
        "name": "Tiger Nixon",
        "position": "System Architect",
        "salary": "$320,800",
        "start_date": "2011/04/25",
        "office": "Edinburgh",
        "age": "23"
      },
      {
        "name": "Lael Greer",
        "position": "Systems Administrator",
        "salary": "$103,500",
        "start_date": "2009/02/27",
        "office": "London",
        "age": "24"
      },
      {
        "name": "Jonas Alexander",
        "position": "Developer",
        "salary": "$86,500",
        "start_date": "2010/07/14",
        "office": "San Francisco",
        "age": "54"
      },
      {
        "name": "Shad Decker",
        "position": "Regional Director",
        "salary": "$183,000",
        "start_date": "2008/11/13",
        "office": "Edinburgh",
        "age": "43"
      }
    ]
  }
}

The overall structure can be summarized as this:
{
  "responseData": {
    "headings": [ { ... }, { ... }, ... ],
    "body": [ { ... }, { ... }, ... ]
  }
}

Now we have the data needed for all our data rows in one section of the JSON, and the titles (column headings) in another section.
The DataTable can be fed this data from a jQuery ajax call:
$(document).ready(function() {

  $.ajax({
      url: "YOUR_URL_GOES_HERE",
    method: "POST",
    success: function(json) {
      initializeDataTable(json);
    }
  });

  function initializeDataTable(json) {
    $('#example').DataTable( {
      "data": json.responseData.body,
      "columns": json.responseData.headings
    } );
  }

} );

And the HTML table is simply this:

So, now there are no specific column names anywhere in the HTML or the DataTable definition. All that data is provided by the JSON.
You can add more data to the JSON, to control other aspects of the DataTable - for example , the initial sort order, and so on.


text:
Q: How to deslect highlighted text in textbox if already highlighted? So I have this very simple JS function that selects all the text in the ASP.NET texbox (input):
function selectAllText(textbox) {
    textbox.focus();
    textbox.select();
}

..and it gets called like this on the click event:
$("#<%=Textbox1.ClientID %>").click(function () { selectAllText(jQuery(this)) });

The problem is no matter how many times a user clicks in the text box all of the text is always selected. I understand why this is occuring (based on the way my code above is), but it doesn't work well when the user tries to click in the middle of a word to get the cursor back to make a modification to the text.
How do I modify this JS to tell if the text is already highlighted and then deselect the text? This was on subsiquient click, the user can get the single cursor on a precise clicked location to make a modification.
I am trying to get the documentation on the .select() method to see if I could do if(!textbox.select()), but I am having a hard time finding it, so post any doc links as well if you have them.
EDIT: This problem and need for a workaround seems to be for IE (I am using IE9). In Chrome the behavior by default is what I need, but this is for an intranet application that runs on IE, so it appears I need an explicit workaround.
Thanks!

A: Is it necessary to do the .focus() in this function? You could instead attach a simple .select(); to the onfocus event (.bind('focus', function(){..})): http://jsfiddle.net/EGHzj/

A: Try this
$(document).ready(function(){
    $('input').bind('click',function(){
        if($(this).hasClass('selected')){
            $(this).toggleClass('selected');
        }else{
           this.focus();
           this.select();
           $(this).toggleClass('selected');
        }
    });
});

This should work in IE also,
http://jsfiddle.net/rAqgw/7/

A: function selectAllText(textbox) {
    // if there isn't selected text.
    if (textbox[0].selectionEnd) {
        textbox.focus();
        textbox.select();
    }
}

$('#txt').click(function() {
    selectAllText($(this));
});

Live DEMO


text:
Q: LaTeX Table of Summary Statistics in R with mean and sd by groups I would like to produce a LaTeX table containing the mean and standard deviation of a a variable for different values of two other variables. That is a grid of numbers with two values for each combination with the standard deviation below the mean in parentheses. Ideally, I would also report the totals (i.e. the marginals) along the bottom and right of the table respectively.
So for the mtcars data:
library(datasets)
library(data.table)
 DT<-data.table(mtcars)
 DT[, list(mean_mpg = mean(mpg), sd_mpg=sd(mpg)),by=.(gear,carb)]

This produces the necessary data:
    gear carb mean_mpg   sd_mpg
 1:    4    4 19.75000 1.552417

 2:    4    1 29.10000 5.061620

 3:    3    1 20.33333 1.934770

 4:    3    2 17.15000 2.092048

 5:    3    4 12.62000 2.089737

 6:    4    2 24.75000 3.961060

 7:    3    3 16.30000 1.053565

 8:    5    2 28.20000 3.111270

 9:    5    4 15.80000       NA

10:    5    6 19.70000       NA

11:    5    8 15.00000       NA

But, I want to obtain output of the form:
    \begin{tabular}{l*4}
\multicolumn{4}{c}{Gear} \\
Carb & 3 & 4 & 5 \\
1 & 20.3 & 29.1 & \\

  & (1.9) & (5.1) &  \\

2 & 17.2 & 24.8 & 28.2 \\

  & (2.1) & (4.0) & (3.1) \\

4 & 12.6 & 19.8 & 15.8 \\

 &  (2.1) & (1.6) & (.) \\

6 & & & 19.7 \\
& & & (.) \\

8 &  & & 15 \\
& & & (.) \\

\end{tabular}

I have experimented with Stargazr, qwraps2, and report tools and none of them seem able to do what I need. The actual numbers are easily obtained, as described here: How to get summary statistics by group but given I need to produce lots of these tables manually rearranging them. Note, that the means are the focus not additional information unlike in this question Generate Cross-table in R with mean and SD


text:
Q: Print data via GET https://api.groovehq.com/v1/tickets I'm trying to get data trough a JSON API from Groove.
https://www.groovehq.com/docs/tickets#listing-tickets
and https://www.groovehq.com/docs
This is the code I made:
<?php

    function timjson_front($atts, $content) {
        global $wpdb;

        $access_token = ""; //insert token
        $user_email = ""; // insert customers email

        $json = getJSON($access_token, $user_email);

        $html = "";

        foreach($json as $key => $waarde) {
            $html .= $key . ' = ' . $waarde;
        }

        return html_entity_decode($html);
    }

    function getJSON($access_token, $user_email) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, 'https://api.groovehq.com/v1/tickets?acces_token=' . $access_token . '&customer=' . $user_email);
        $result = curl_exec($ch);
        curl_close($ch);

        $obj = json_decode($result);
        return $obj;
    }
 ?>

The code runs on a wordpress page and is part of a self made plugin. The idea is that the tickets from a customer gets printed on a page.
Wordpress gives a error at foreach(). Does anyone know what i'm doing wrong? Or has some advice?

A: First
You're iterating on $obj but $obj = json_decode($result); will returns an object. You need to iterate through an array so use json_decode($result, true)
Second
Based on the API, the first key is tickets and has multiple tickets
So you want to start with tickets in the foreach:
foreach($json['tickets'] as $ticket){
    foreach($ticket as $key => $waarde) {
        $html .= $key . ' = ' . $waarde;
    }
}

Third
You're concatenating strings with $html .= $key . ' = ' . $waarde;
But based on the API, the values are not ALWAYS strings.
foreach($json['tickets'] as $ticket){
    foreach($ticket as $key => $waarde) {
        if(!in_array($key, ['tags','links'])){ // ignore the keys "tags" and "links" because they are array
            $html .= $key . ' = ' . $waarde;
        }
    }
}

Edit: POC https://3v4l.org/dblmj


text:
Q: Any finite group is a subgroup of an orthogonal group Prove that any finite group of order $n$ is isomorphic to a subgroup of $\mathbb{O}(n)$, the group of $n\times n$ orthogonal real matrices.
Attempt:
Let $G$ be a group of order $n$. Then $G$ is isomorphic to a subgroup of the symmetric group $S_n$.
But how to go further?

A: $S_{n}$ acts on $\mathbb{R}^n$ by the equation $$ \sigma . e_i= e_{\sigma(i)},$$
where $\lbrace e_i \vert i= 1,2,...,n\rbrace $ is the standard basis of $\mathbb{R}^n$ and $\sigma \in S_n$. Therefore we have a group morphism $$\varphi : S_n \rightarrow GL_n(\mathbb{R})$$ defined by $\varphi(\sigma)(e_i)= e_{\sigma(i)}.$
It is easy to check that $\varphi$ is one-one. Note that $\varphi(S_n) \subset \mathbb{O}(n)$, for $\langle \varphi(\sigma)(e_i), \varphi(\sigma)(e_j)\rangle~= ~\langle e_i, e_j\rangle$.

A: $S_n$ is embedded in the set of n x n matrices as permutation matrices. A permutation matrix represents a permutation by having a 1 in the ith row and the jth column if the permutation sends i to j, and zero otherwise. (One can also embed them by switching "row" and "column" in the preceding sentence.) Permutation matrices are orthogonal, and this correspondence is a bijection that maps permutation composition to matrix multiplication, i.e. is a isomorphism.


text:
Q: Sharepoint 2010 List Advanced Dialog Setting only works on first Lookup field I have a list with 3 lookup fields. I've gone into advanced list settings and turned Dialogs off.
When I click a link in first lookup field - the link works much like a standard a href. However when clicking a link in the other 2 lookup fields - the dialog window pops up.
I want all my links to respect the Dialog OFF, setting, is this possible?

A: This appears to be a bug. As far as I know there is no easy solution, only complex JS hacks.


text:
Q: HTML5 video background transitions only working on first loop I have been put in charge of a project where I need to build an application that can be displayed on huge monitors for sales people, and  it needs to look like some of those sports results on TV.
It's bascially just four divs, each with a video background and some content rotating. This works fine on the first loop, but once the four divs start again, the video background no longer works. The video "source" tag is ignored and instead the poster image shows.
I have tried several code snippets, but none of them made the video run on the second go around.
Does anybody have an idea why this is happening? Is there a code snippet I missed?
Any hint is greatly appreciated!
Project URL: http://illufoxdesign.com/tests/salescast/

A: Intuitively, I think your problem is that you're not playing the video after first loop. You have the script which loops through, but no code which actually calls the play() method on the video.
You have the code
var vid = document.getElementById("bgvid");
vid.volume = 0;
vid.play();

I suggest you make this into a function and call it on each loop, and play the video in focus.
If you're still unable to fix it, I'll edit this answer with a sample code.
EDIT: Modified the code. Working JSFiddle - https://jsfiddle.net/z3Lgc75p/5/ The below JS code is the only thing you need within <script></script> tags.
function fadeMyContent() {
    $(".wrapper:first").fadeIn(1000, function () {
        var vid = $(this).children("#bgvid");
        vid.get(0).play();
    }).delay(5000).fadeOut(1000,

    function () {
        $(this).appendTo($(this).parent());
        fadeMyContent();
    });
}
fadeMyContent();


text:
Q: Without using CV2, how do I display an image showing only the isolated green colors My goal is to read an image of a plant and then output the picture showing only the green parts without any other background colors.  Essentially, I only want to extract the leaf part from the picture and not the soil or anything else.  So far I've been able to read my images and change them to green, however my goal was to actually extract the green rather than change the whole green.  Any ideas on what I might doing wrong?
HERE IS MY CODE
import matplotlib.pyplot as plt
import numpy as np

# Read and display picture
originalImage = plt.imread("C:/Users/user/Desktop/Image for detection1.jpg")
imgplot = plt.imshow(originalImage)

# Copy 1st picture and turn into an array
edittedImage = originalImage.copy()

arr = np.asarray(originalImage) # create array for image

lowerGreen = np.array([130,137,10]) # define lower values for green
upperGreen = np.array([220,235,130]) # define higher values for green

for color in arr: # loop through pixels to find the color green
    if color >= lowerGreen and <= upperGreen:
        print (color) # print the image showing only the green sections

imgplot = plt.imshow(edittedImage)

ERROR MSG:
  File "C:/Users/user/.spyder-py3/extract green.py", line 28, in
    if color >= lowerGreen and color <= upperGreen:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

A: With OpenCv (cv2 module), I would do as follows:
import cv2 as cv
import numpy as np

img = cv.imread('MyImage.jpg')

hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)

# range of colors to filter by; you can adjust these parameters to fit your image:
lower_red = np.array([40,50,50])
upper_red = np.array([170,200,180])

# select parts of image in color range
mask = cv.inRange(hsv, lower_red, upper_red)
res = cv.bitwise_and(img,img, mask= mask)

cv.imshow('res',res)
cv.waitKey() & 0xFF


text:
Q: Decoding PKCS7 SMIME data using C# I am encrypting data using openssl using the following
openssl smime -encrypt -in data.json -aes256 certificate.pem

data.json contents:
{"array":[1,2,3],"boolean":true,"null":null,"number":123,"object":{"a":"b","c":"d","e":"f"},"string":"Hello World"}

ending up with:
MIME-Version: 1.0
Content-Disposition: attachment; filename="smime.p7m"
Content-Type: application/x-pkcs7-mime; smime-type=enveloped-data;
name="smime.p7m"
Content-Transfer-Encoding: base64

MIIF6AYJKoZIhvcNAQcDoIIF2TCCBdUCAQAxggUeMIIFGgIBADCBpzCBmTELMAkG
A1UEBhMCSUwxEDAOBgNVBAgTB0NlbnRyYWwxEDAOBgNVBAcTB1JhYW5hbmExDzAN
BgNVBAoTBmFtZG9jczEMMAoGA1UECxMDV01UMSUwIwYDVQQDExxtYWNyZXBvcnRp
bmcuY29ycC5hbWRvY3MuY29tMSAwHgYJKoZIhvcNAQkBFhF3bXRhbGxAYW1kb2Nz
LmNvbQIJAPKpzLFUszFYMA0GCSqGSIb3DQEBAQUABIIEWk/ImeSYH1yGgK9wscxS
RZlqt9UurQY3wH9ZSlQEv0WyGJndmveYfEtKfOoem99TCyqopYDFfWcqGwnv57eS
fP4XHTVw4AD14zznq4gfPJjLhtXBTcjFtkgqQLsN/fOUTV2ic+nAjnAa7Okw7kd0
lXwwBtpdcD9EvMvteN1DYsLLvon6qQ3Ba1r2PYGgvmezz8WG6AAmz8h3yGtXeAqH
+e0z2aT/Ob9lpGJuvGqJUXjkcvJrVuuWPplubR5I1FJfpD+sECgw/w+swt30VLcf
Spaysm2DiiYXdyu8k/fWVhiNjNCD8D1yTJR5wvBVOFNiQs++DtagFxb8Z+Njp/hv
lBWCN+F9twPzlH16bg/6PWXLbSNMk61ixWdjWMqtaeI3hRIqRla5uQL131yIGXzy
PN4XIyMQnwMSSvsQR2IMKEN6WAdGn4+v5U2IQAjbBRPiruMf+q0BVKu97rxXGffg
2MaB3PjwofBknY+SO9m9Nfyf1M+90h10lIyv7l3QrQjwaC8+gjSNvA9HqgjjrI6/
KZP7xePww8e+2ozhxFtU5Yex0vjbPGwEFPtur1hcsJIFWcCIgvGty+Aaf3n1E4F1
2+4y4v3fZO9Aku3j4+mL+n8dkNUVQw8IYXtd03lhbWlQlXOKqUqZ3HEwTaHuN8NR
7RlBhbKP85eN3GVzdVNqkv8OWYtVFG0pkTlU7QNirOEE+LmCX9PpbUVL0WM75kXK
xw2AeUOkm1Wrl3ew514ObPw2pgYvgyIayQMFkg8sO9lfCwjRu6NdkszjytvszDBJ
RpcVDAf38pMTGwDXRE7CxrEp5aqAm9wHSTFZIdqBnJ+/1uGxoVT1jk4LiCz0c0Vg
24/MMaFWGfpD5HFJjZuG6wTs2Nis0aDNnnK90eM4z893e8ojx/XDRayjWk9HEEAH
m7wephJ0M8sOhkaW6yqfjF9J9kKzXUeJKoAu+bnvb4EKm7pcCAWCbmxbYvMnRmnk
pC3+mCPhPbVc0ByJ3DMGyrBQQbGQfIp2odXr0uQ5udkggJfjv5Qwm+wWxPSL0HMA
maB52x4Lzeb5BwL9zHtaLuZJwnM+mHKX7wfOCzUY+3fqdwpZ2sIA8ND2vFyzHQvh
rlzrGhIDqwt7kmn+Weh8/NnPrFEEZFZTGtDmn2TB4FrIRq8aP3HkwW8/3Lt52v/d
72ty8sypuxyzxezi9Ny8dftn5WouaPO2Dm/Yc0rp7QHSGQGHqUDAwPiIIFCYUKlF
ZLQ1zpM8W2KFZyc6fIPXZNT9VffBYUV8TV6qzn98yZtsA/ILpqAJXa331iBIqf9M
Fb9wbcxW0zzLFlVOW7tVgCniJPD90X0bOgQKsPZMlV4dfETpqfkcpEAn3p644M3F
fuyKhymL5s2KgVUfV9lxqWQfCX2E9P3vUS4ivsxPH7HEgAX80pLxpYJH54PikV+Q
ELufvjNh6P1qVG2c6bYOqqiQegxeMGM4H/E2WWWUwWqKbXZmZmb2IV8G5yIwga0G
CSqGSIb3DQEHATAdBglghkgBZQMEASoEEMOMNOkZhYGNzlaXPYtkwuuAgYAZywPG
zMizOuIhL875mrW6gjzf5nKR1EsnFoRKQ6X/9/k348YHld714JpzA2vpW7UNtvir
MYnoiSPSzQ8CbYJXrAoMMB6sfMG1fJe+wUVjef2cqSZ2oiuYvTtpmXsuQGOtvWlj
XJ/pHqF8PjqjiocUKHMJJgPcds077lUmPMNmZg==

I'm looking for a way to decrypt using the private key (PEM file) in C#
however, everything i've found is half baked / no proper documentation or examples
Any ideas? recommendations?
Thanks!

A: Part of your problem is that S/MIME needs to encrypt a MIME entity, not content data. In other words, you first need to add MIME headers such as a Content-Type header and potentially others if you decide to base64 encode the json data (e.g. Content-Transfer-Encoding).
For example:
Content-Type: text/json

{"array":[1,2,3],"boolean":true,"null":null,"number":123,"object":{"a":"b","c":"d","e":"f"},"string":"Hello World"}

Once you've done that, using MimeKit, you could do this to decrypt it:
var pkcs7 = (ApplicationPkcs7Mime) MimeEntity.Load (stream);
MimePart mime;

using (ctx = new WindowsSecureMimeContext ()) {
    mime = (MimePart) pkcs7.Decrypt (ctx);
}

using (var content = new MemoryStream ()) {
    mime.Content.DecodeTo (content);

    // now your raw json data is contained in the `content` stream.
}


text:
Q: Mysql query comma separated filter result My table looks like this

id pname     pfilter
1  onename   24, 36, 120
2  another   22, 124, 1
3  yet       120, 12, 124

I´m trying to run this query:
$filterrun = "24";

SELECT * FROM table WHERE pfilter LIKE '$filterrun'

In this example i would like only id #1 to show up. And not id #2 and #3 since these contains pfilter 124.
How can this be done?

A: try this with FIND_IN_SET
  SELECT * FROM table WHERE  FIND_IN_SET('$filterrun', pfilter)

if you have speces then you can use this
  SELECT * FROM table WHERE  FIND_IN_SET('$filterrun',replace(replace(pfilter, ', ', ','),' ,',','))

EDIT: it would be hard if you have spaces between values , you can also go around them like that.
    SELECT * FROM table WHERE
    pfilter LIKE ' $filterrun,%'
    or pfilter like '$filterrun,%'
    or pfilter like '%,$filterrun,%'
    or pfilter like '%, $filterrun,%'
    or pfilter like '%,$filterrun ,%'
    or pfilter like '%,$filterrun %'
    or pfilter like '%, $filterrun'

Or use this
   SELECT * FROM table1 WHERE  FIND_IN_SET('$filterrun',pfilter)
                            or FIND_IN_SET(' $filterrun',pfilter)
                            or FIND_IN_SET('$filterrun ',pfilter)

Note here: that there is spaces before and after $filterrun.
DEMO TO PLAY WITH

A: Your data contains a comma-space delimited list.  This gives you two direct methods:
SELECT *
FROM table
WHERE concat(', ', $filterrun, ', ') like concat('%, ', pfilter, ', %');

Or a slight variation on echo_me's solution:
SELECT *
FROM table
WHERE find_in_set($filterrun, replace(pfilter, ', ', ','));

Otherwise, you have to start dealing with the spaces.
Ultimately, though, you should be using a separate association/junction table.  This would have one row per id and filter value.


text:
Q: Disable webpage like js alert do? I am using custom dialog-box for confirmation message it will appear correctly but the back view of page is clickable/enable so user can click anywhere i want to disable that back view.
Just like native js alert, confirm box do.
Following is image of js alert box in which all back view is not accessible how do i achieve this thing when i am using my custom boxes.

A: Try this....
HTML:

CSS:
#alert-overlay {
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
z-index: 1000;
}

Add the html div in the html of the custom alert box as well add the css.
This work as the overlay for the body.
The one thing you have take care is that the "z-index" of the custom alert box must be greater than 1000 as overlay z-index is 1000.

A: You may try jQuery Alert or a similar plugin.
Logic: Create a div with lightbox like effect. The lightbox will cover the entire page.

A: The best example of your situation is bootstrap modals Bootstrap modal
Just see how twitter developers do it.

A: You can try :-
Twitter boot strap modol box : Modol Box
jQuery Fancybox : Fancybox
jquery Colorbox : Colorbox


text:
Q: React Navbar isn't rendering in React js I am trying to make single page website. I have used react bootstrap for the nav bar and I am trying to figure out why it isn't rendering. I am not getting any errors just the page being blank.
Here is my code for App.js
import React from 'react';
import Navbar from "../components/Navbar/navbar"
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import "./App.css";
import Shop from './shop';
import Learn from './learn';
import Aboutus from './aboutus';
import Contactus from './contactus';

function App(){

  return (
  <>
  <Router>

      <Navbar />

hi

      <Routes>
      <Route path="/shop" element={<Shop/>} />
      <Route path="/aboutus" element={<Aboutus/>} />
      <Route path="/contactus" element={<Contactus/>} />
      <Route path="/learn" element={<Learn/>} />
    </Routes>

  </Router>
  </>
  );
}
export default App;

Here is my navbar.js code:
import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import 'bootstrap/dist/css/bootstrap.min.css';
import Navbar from 'react-bootstrap/Navbar';
import "../Navbar/navbar.css";
import instalogo from "../assets/instalogo.png";
import discordlogo from "../assets/discordlogo.png";
import youtubelogo from "../assets/youtubelogo.png";
import '../fonts/ETAluminiumB.ttf' ;
import '../fonts/ETAluminiumA.ttf' ;

function CollapsibleExample() {
  return (

<Navbar bg="black" className="justify-content-center">
        <Container>

          <Navbar.Brand href="#home" >

WeTech

          </Navbar.Brand>

Shop

Learn

  About

Contact us

        </Container>
      </Navbar>

  );

}

export default CollapsibleExample;

and my shop.js, learn.js, aboutus.js, and my contacts.js look like this(with each one named to their file name):
import React from 'react'

function learn() {
  return (

learn

  )
}

export default learn

I also suspect that one of the issues is because of my routes.
EDIT: I think it could be an issue with the Navbar.js since I am able to change the color of the body, but still the Navbar is not rendering.

A: In your App.js From this:
import Navbar from "../components/Navbar/navbar"

To This:
import CollapsibleExample as Navbar from "../components/Navbar/navbar"

I wish it help...

A: Try to simplify your code like this.
App.js
function App() {
  return (
    <>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home/>}>
        <Route path="projects" element={<Projects/>}/>
      </Routes>
    </>
  );
}

index.js
ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);


text:
Q: Unable to make style changes to the DOM after form submit in Safari I'm having problems making style alterations to the DOM after I submit a form in Safari. Does anyone have any idea if its even possible? Is this expected browser behavior from Safari?
I have set up a very simple example so you can see the issue in action:
http://jamesmichaelking.com/stackoverflow/safari/index.html
The example consists of a html form posting to itself, with a jquery form submit event which looks for the input button and changes the background to red.
The example works fine in Firefox and Chrome
I've included the html, js and css from the example:
HTML
<form action="index.html" method="post">
    <input type="submit" value="Submit me!">
</form>

CSS
body {
    font-family: sans-serif;
    color: #fff;
    text-align: center;
}

input {
    border: none;
    padding: 20px;
    font-size: 20px;
    background: #036;
    color: #fff;
}

JQUERY
$(function() {

            $('form').on('submit', function() {
                $(this).find('input').css('background', '#c00');
            });

        });

Strangely, I have created a JSFiddle of the same code and it works fine:
http://jsfiddle.net/jamesking/q8WcV/
I'm testing using Safari 7 on a mac
Any help much appreciated

A: Looks like A. Wolff's solution doesn't work for me on Safari 8.0.6
I also tried other things like restoring the default submit event handler (How to unbind a listener that is calling event.preventDefault() (using jQuery)?), but it didn't work.
After a lot of testing, I came up with a solution. It might not be the cleanest one, but it's working.
var form = $("form");
form.on("submit", function (e) {

    // Do your thing

    e.preventDefault();

    setTimeout(function(){
        form.off("submit");
        form.find("input[type=submit], button[type=submit]").eq(0).click();
    }, 500);
});

A: I have found that the solution is to not use the form submit event but instead the click event of the submit button. If you, as I do, also want to disable the submit button to prevent double submits, you have to submit the form programmatically otherwise the disabling of the submit button will prevent the form from being submitted. You also need to introduce a short delay before submitting. I have found that 500 msecs works, and this is barely noticeably to the user.
This is the code I use
jQuery.fn.preventDoubleSubmission = function() {
  $form = $(this);
  var submit_btn = $form.find(":submit");
  wait_msg = "One moment please"
  submit_btn.on("click", function(e) {
    var $subm = $(this);
    var the_form = $subm.closest('form');
    $subm.attr("disabled", true);
    $subm.val(wait_msg+" ...");
    setTimeout(function() {
      the_form.submit();
    }, (100));
  });
  // Keep chainability
  return this;
};

To apply this behavior to a form you need to do
$("#myform").preventDoubleSubmission;


text:
Q: Django: Combine two count annotations from two filter queries I am computing some statistics based on two different filters, but I'm not sure how I can combine both results into a single QuerySet.
My code looks like this:
qs1 = User.objects.filter(c1).annotate(count1=Count("id"))
qs2 = User.objects.filter(c2).annotate(count2=Count("id"))

I would like to create a third queryset, qs3 which has both count1 and count2.  Basically I want to left join on User.id but I can't find a straightforward way of doing that.
I also tried
count1 = Count('id', filter=c1)
count2 = Count('id', filter=c2)
qs3 = User.objects.annotate(count1=count1).annotate(count2=count2)

But it gave me different results.

A: I ended up solving with SubQuerys, as described in the first answer here.
qs1 = User.objects.filter(c1).annotate(count=Count('id')).filter(pk=OuterRef('pk'))
qs2 = User.objects.filter(c2).annotate(count=Count('id')).filter(pk=OuterRef('pk'))
users = User.objects.annotate(
    count1=Subquery(qs1.values('count'), output_field=IntegerField()),
    count2=Subquery(qs2.values('count'), output_field=IntegerField())
)

I still don't fully understand the solution since this is the first time I've seen a SubQuery, but it seems to work.  If anyone want to provide a more detailed answer I would be happy to accept it.


text:
Q: How to set applicationID using Android.mk I have a custom rom based on AOSP and I have intend to make App on a system app that is based on Launcher3.
I would like to change App's packageName(or applicationID) from specified in a manifest.
I can change appliationID when build by gradle.
But I don't know how to set applicationID using Android.mk.
How to set applicationID using Android.mk?
Update:
I want to set applicationID using Android.MK like I set to applicationID using build.gradle.

A: I don't think there is a way ( at least that I know of ) to specify applicationId on the makefile.
You can always try to replicate what gradle does, which is changing the package field in AndroidManifest as the last step of the build ( after R class generation is already done with original package name field )
Read more on: https://developer.android.com/studio/build/application-id

One more thing to know: Although you may have a different name for the
  manifest package and the Gradle applicationId, the build tools copy
  the application ID into your APK's final manifest file at the end of
  the build. So if you inspect your AndroidManifest.xml file after a
  build, don't be surprised that the package attribute has changed. The
  package attribute is where Google Play Store and the Android platform
  actually look to identify your app; so once the build has made use of
  the original value (to namespace the R class and resolve manifest
  class names), it discards that value and replaces it with the
  application ID.

A: Application package name can be change in AndroidManifest.xml and your application classes.
Android.mk doesn't contain any package name or ApplicationID. it contains your module name to include in source code and add it to build configs.
ApplicationID should set in gradle filer


text:
Q: Does this show that equality (set theoretically) does not necessarily imply isomorphic (categorically)? I was thinking about a rather simple question, namely: If two things are equal, are they necessarily isomorphic? At first, I thought this was a silly question as it seems that the identity map should provide the isomorphism we are after. However, after thinking about it a little bit more, I started to think of what does equality and isomorphism mean. Thus, I decided to work in a case where I know what equality and isomorphism mean. Here when I say equality, I mean equality of sets (i.e. both sets are subsets of each other), and when I say isomorphism, I mean that in the category that we are working given two objects $A$ and $B$ they are isomorphic if there is $f:A\rightarrow B$ and $g:B\rightarrow A$ such that $f\circ g=1_B$ and $g\circ f=1_A$. Thus, I thought that if we can cook up a category where $A=B$, but there are no morphisms between $A$ and $B$, then we must have that $A=B$, but $A\not\cong B$.
Thus, I consider the following category where the objects in the category are sets and the morphisms are functions of sets. In this category, I will take two distinct objects $A$ and $B$ where $A$ is the empty-set and $B$ is also the empty set, and the only morphisms will be the identity morphisms $1_A$ and $1_B$. Thus, if we think of the associated graph, it will just consist of two nodes with self loops. Now clearly, we must have that $A=B$ and $\emptyset\subset\emptyset$, but $A\not\cong B$ since there are no arrows between $A$ and $B$. Thus, would this constitute an example where equality does not imply isomorphism?
Furthermore, one might say that this is a silly example since there is a larger category that has this as a subcategory where $A\cong B$ (just "add the identity map between the objects"). Thus, is it always the case that if I have a category where there are objects which are equal but not isomorphic to just "add the identity morphism" between them to arrive at a larger category where equal objects are now isomorphic and contains the original category as a subcategory?

A: When you define a category, you need a set (or class) of objects $\text{Ob}$. If your objects are themselves sets, $A,B\in\text{Ob}$ and $A = B$ as sets, then they are indistinguishable as objects.

A: As has already been said, the most common way to define a category is as having a class of objects, and classes cannot have duplicates of the same element. It's also possible to imagine an approach in which the collection of objects in a category does not come equipped with an equality predicate at all--that is, it's meaningless to ask whether two objects of a category are equal. This is, in fact, a more categorically natural approach, though it doesn't sit very well with the standard "everything is a set" foundation. In this case, the question "does isomorphism imply equality" is meaningless, rather than having a positive answer. In principle you could imagine defining a "category" with a multiset of objects, exhibiting the behavior in your post, but then you would simply have proven that you aren't really talking about categories as usually understood at all.

A: No, you can't do this. The reason is that the fundamental characteristic of equality---whatever equality is taken to actually mean---is that equal things may be substituted for one another in a way that the rest of the theory must respect.
So, for instance, it is completely fine to consider a theory where there are multiple, distinct empty sets. This is not how set theory is usually defined, because the axiom of extensionality declares all empty sets to be equal, but you could remove extensionality. However, once you do say that two sets $A$ and $B$ are equal, you can't go on to say that $A \cong A$, but not $A \cong B$, because if $A = B$, I must be allowed to substitute $B$ for $A$ on the right of $A \cong A$. And the only way we could have $A \ncong B$ is if $A \ncong A$ also, for the same reason.
So, there is plenty of room to negotiate about which things are considered equal. Maybe sets are equal when they were defined by the same formula. Maybe they're equal when they have the same elements. Maybe they're equal when they have the same number of elements. But, the thing that is not negotiable is that however equality is characterized, the rest of the theory must somehow be invariant with respect to interchanging equal things. Otherwise you are not really talking about what people mean by, "equality."


text:
Q: Distorted sound with bluetooth speaker in Ubuntu 16.04 I just upgrade to Ubuntu 16.04 this morning.
When I got to work I connected my Blackweb Tsunami bluetooth speakers, and they connected fine, but the sound is so distorted, and almost sounds monotone.
It sounds horrible, these speakers worked perfectly in Ubuntu 15.10.
EDIT:
When I try to set the device sound mode from HSP/HFP to A2DP as suggested in LiveWireBTs answer the sound stops working completely.
Any help would be appreciated.

A: Go to Sound Settings, select your Bluetooth audio device and check that the device is set to A2DP not HSP/HFP (which is mono and has very low quality).

Edit: If Bluetooth audio stops working after you do that in 16.04 you need to apply the following workaround: https://askubuntu.com/a/817926/40581


text:
Q: How to check if there are block in getChildHtml in Magento 2? In my code, there are many blocks that will be rendered but is there a product page that isn't rendering because there are no custom options.

How can I check if it'll return some blocks in my phtml?

<?php echo $block->getChildHtml('', true);?>

Today I'm using like that:
$_getChildHtml = $block->getChildHtml('', true);
$_hasOptionsPersonalize = strpos($_getChildHtml, 'class="field"') ? true : false;

A: If I understand you correctly, you should build your child blocks that only render any html if they have to.
In this case, you can just check if the getChildHtml does not return a null string
<?php if ($childHtml = $block->getChildHtml('', true)): ?>

<?= $childHtml ?>

<?php endif; >

In your child block you could have an if condition for example if field != null


text:
Q: Some unicode characters are represented as "?" mark when inserting to Oracle from Delphi I have written an application in Delphi 2010 that imports data from one database to another. I've done this before many times: From Access to Acces, Access to SQL Server. But now I have to import data from SQL Server 2005 to Oracle 10G. I do this by selecting all the rows from a table in SQL Server database and inserting them one by one to a table with the same structure in Oracle database. The import performs normally except for that I get question marks for some unicode characters. When I insert those characters in the database manually it shows them properly. It's something between Delphi and Oracle. I use UniDac component set for this purpose. Does anybody know the reason for those question marks?

A: Basically two possibilities: either the character encoding is wrong, or the software used to display the text is using a font (or set of fonts) that does not contain all the characters. To check this, copy some of the displayed text containing the problem characters into another program, like MS Word, and see if it displays them. Set Word to use Arial Unicode MS if needed.


text:
Q: Angular - Rendering a collection of child controls without a FormArray? TL,DR;
When a collection of child controls is not a FormArray, how can it be rendered?
// 'foo', 'bar' and 'baz' are actually names chosen by the user.
// and are *not* known ahead-of-time.

let form = this.fb.group({
    fields: this.fb.group({
      foo: this.fb.control(''),
      bar: this.fb.control(''),
      baz: this.fb.control('')
    })
});

I'm using a FormGroup for fields because the JSON representation resulting from the value property must be an object and not an array.
How can fields be rendered without *ngFor - since fields is not iterable, it will not work.

Detail;
I want to render a collection of child controls belonging to an Angular Form, but not in a FormArray.
// Use FromBuilder to create the form.
constructor(private readonly fb: FormBuilder) { }

The form must represent a structure consisting of fields which contain key/value pairs:
// Create the form with no/empty fields to start.
let form = this.fb.group({
    fields: this.fb.group({})
});

I don't know how many child controls will exist in fields - they will be added from a user action.
At this point, it's common for fields to be a FormArray, but I must use a FormGroup because the representation resulting from the Form value must be a JSON object and not a JSON array.
At some point after the app has loaded, child controls are added to fields using addControl. Control names are actually chosen by the user.
For simplicity I have hard-coded them here as foo, bar and baz:
const fields = form.get('fields');

const foo = new FormControl('');
fields.addControl('foo', foo);

const bar = new FormControl('');
fields.addControl('bar', bar);

...

const baz = new FormControl('');
fields.addControl('baz', baz);

Ideally I would used *ngFor, but since controls is not iterable, this will not work:
<ng-container [formGroup]="form">

  <ng-container formGroupName="fields">

       <mat-form-field *ngFor="let f of form.get('fields').controls">

         <input matInput ...>

       </mat-form-field>

  </ng-container>

</ng-container>

Additionally, I don't know the name of any child controls within fields - since as mentioned earlier, the name's of newly added controls are actually chosen by the user.

A: When you want to use ngFor with the keys of an object, you can simply extract those keys from the object using Object.keys and then loop over that array.
As it's going to be something pretty generic (you might want to reuse that), and it's going to be deal with (ideally) from the template, creating a pipe for that is a good idea:
@Pipe({
  name: 'keys'
})
export class KeysPipe implements PipeTransform {
  transform(value: any): any[] {
    return Object.keys(value)
  }
}

Now you can do something like

Another interesting part is to prevent adding a key that already exists into the form. Here's a complete example with a custom validator:
TS:
export function forbiddenFieldNameValidator(form: FormGroup): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const fieldToAdd: string = control.value;
    const forbidden = !!form.controls[fieldToAdd];

    return forbidden ?
      {'forbiddenFieldName': { value: control.value }} :
      null;
  };
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  resultForm: FormGroup = new FormGroup({});

  addFieldGroup: FormGroup = this.fb.group({
    addField: ['', [Validators.required, forbiddenFieldNameValidator(this.resultForm)]]
  });

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void { }

  addField(fieldName: string) {
    this.resultForm.addControl(
      fieldName,
      new FormControl('')
    );

    this.addFieldGroup.reset();
  }
}

HTML:
<form [formGroup]="addFieldGroup" (ngSubmit)="addField(addFieldGroup.controls['addField'].value)">
  <input type="text" formControlName="addField">

  <button type="submit" [disabled]="addFieldGroup.invalid">Add field to form</button>

This field is required

The key "{{ addFieldGroup.controls['addField'].value }}" is already into the dynamic form

</form>

Dynamic form

<form [formGroup]="resultForm">

    {{ controlName }} <input type="text" [formControlName]="controlName" [placeholder]="controlName">

</form>

Form value

{{ resultForm.value | json }}

Here's a working stackblitz where you can try to add dynamic values into the final form and see that the input to add those values is blocked if one already exists:
https://stackblitz.com/edit/angular-w2ibtb
Side note:
For the pipe, note that we have to set it as impure because we're not directly handling the controls properties of the form and under the hood angular is not creating a new reference for the controls array every time we add a property into it. Thus, the reference passed to the pipe is the same but still, we want to update the view. That's why we have to set pure to false.

A: Another option is make an array of Controls
controls:FormControl[]=[] //declare a variable
form:FormGroup //Your form

constructor(private fb: FormBuilder) { }
//When you defined the form, you create the array
this.form=this.fb.group({
    fields: this.fb.group({
      foo: this.fb.control(''),
      bar: this.fb.control(''),
      baz: this.fb.control('')
    })
    //usign map from Object.keys
    Object.keys((this.form.get('fields') as FormGroup).controls).map(control=>{
      this.controls.push((this.form.get('fields') as FormGroup).get(control) as FormControl);
    });

//Your .html is like

    <input [formControl]="control">

  {{form.value |json}}


text:
Q: Derivatives for a piecewise defined function $f$ is a function on real line and $f(x)=\begin{cases} x^2& x<0\\ 2x+x^2&x\ge 0\end{cases}$. Could any one tell me which of the following is/are true?
1.$f'(0)$ doesn't exist
2.$f'(x)$ exist other than at $0$
3.$f''(x)=2$
4.$f''(0)$ does not exist
I have myself checked that $1$ is true as $\lim x\uparrow 0 f'(x)=0\neq \lim x\downarrow f'(x)=2$ I mean to say lefthand derivative is $0$ but right hand derivative is $2$, but I am not getting how to find $f''$ please help

A: Hints:
At each side of $\,x=0\,$ the function is polynomial and thus infinitely differentiable, which already answers (2) and almost-almost (really almost!) (3).
Now, just as $\,f'(x_0)\,$ cannot exist if $\,f\,$ isn't defined at $\,x_0\,$ , we get that (4) is true after we take a peek at what we did in (1) ...


text:
Q: XML and Latin1 issue Is there any simple way to just save a xml file so that it would show the latin characters?
For some strange reason I have my original file from some years back which works fine but if I copy new information into it I get:

"The document "abc.xml" cannot be saved using the Latin1 encoding. Would you like to save it using UTF-8 instead?"

If I save it using UTF-8 the latin characters are simply overrun.
My xml file starts with <?xml version="1.0" encoding="iso-8859-1"?>


text:
Q: Heat-Work equivalence in thermodynamics of ideal gases If $n$ moles of an ideal gas (one atomic) are heated at a constant volume $V$ from initial temperature $T_1$ to final temperature $T_2$, the amount of energy heat needed can be calculated as
$$ Q = nC_V \Delta T $$
Solving with work-energy theorem
By the work-energy theorem, the change in total kinetic energy is equal to the work done by net sum of the external forces ($\Delta K = W_f$). In this case, the work done on the gas is due to adding the heat $Q$ to the system. The total kinetic energy in a one atomic gas is given by $K = \frac{3}{2}pV = \frac{3}{2}nRT$. Therefore
$$ Q = \Delta K = K_2 - K_1 = \frac{3}{2}nR(T_2 - T_1) = \frac{3}{2}nR \Delta T$$
And since $C_V = \frac{3}{2}R$ for one atomic ideal gases, the two equations are identical.
Is my reasoning valid?

A: TL; DR:  there is (mechanical) work and (thermodynamic) work.
Work-energy theorem

The work done by all forces acting on a particle (the work of the resultant force) equals the change in the kinetic energy of the particle.

is a theorem in classical mechanics, referring to the energy and work (done upon) of a point-like object.
In statistical mechanics we consider a very large collection of such objects (atoms or molecules) - of the order around Avogadro number of them. The work done on each atom/molecule obeys the work-energy theorem, but when we speak about the collection as a whole, we usually split this work into two components: (thermodynamic) work - corresponding to the macroscopic changes, and the work done on the microscopic level - which we call heat. The sum of the two correspond to the change of the total energy of the collection, and, in case of non-interacting particles (ideal gas) can be viewed as a manifestation of the work-energy theorem (for a non-ideal gas or a substance in another aggregate state, the total energy also includes the energy of interaction between the molecules, not covered by the work-energy theorem as formulate for one object.)

A: From the first law:  ΔU = Q – W
Where:
ΔU is the change in internal energy,
Q is heat added to the gas, and
W is work done by the gas which, for a closed system, is the integral of pdV
For a constant volume process (dV = 0), no work is done so W = 0.  Moreover, for an ideal gas undergoing any process we have:
ΔU = n Cv ΔT
So Q in your example is simply heat added to the gas that results only in an increase in internal energy.

A: Let us try to understand the basics of First  Law of Thermodynamics-
Heat (Q) and work (W) are the two ways to add or remove energy from a physical system.

n moles of an ideal gas (one atomic) is heated at constant volume V from temperature T1 to temperature T2, the amount of energy heat needed can be calculated as

Q = n C(v)ΔT
The processes are very different.
Heat is driven by temperature differences, while work involves a force exerted through a distance.
The heat and work can produce identical results.
For example, both can cause a temperature increase.
Heat transfers energy into a system, such as when the sun warms the air in a bicycle tire and increases the air's temperature.
Similarly, work can be done on the system, as when someone pumps air into the tire. Heat and work are both energy in transit—neither is stored as such in a system. However, both can change the internal energy, U, of a system.
Internal energy is the sum of the kinetic and potential energies of a system's atoms and molecules.
It can be divided into many subcategories, such as thermal and chemical energy, and depends only on the state of a system (that is, P, V, and T), not on how the energy enters or leaves the system.
In order to understand the relationship between heat, work, and internal energy, we use the first law of thermodynamics. The first law of thermodynamics applies the conservation of energy principle to systems where heat and work are the methods of transferring energy into and out of the systems.
It can also be used to describe how energy transferred by heat is converted and transferred again by work.
so  use
ΔU = Q – W
and the process given by you says that no p.dv   work is being done ,therefore the  alternate calculation does  not  stand correct ,though it may be relating to change in temperature  in the initial and final  state of the system and trying to relate K.E. with work done, which  is not happening..
Reference- https://www.texasgateway.org/resource/122-first-law-thermodynamics-thermal-energy-and-work

A: You are confusing the mechanical work with non-mechanical heat. Now, Joule did show that the two are 'interconvertible', albeit with some loss (the second law of thermodynamics), the two are not the same.
The first law states $dU = \partial W + \partial q$, where the signs may differ for different authors.
Correct statement: $\Delta U =\int \partial q$
Incorrect statement: $\int \partial W = \Delta K =\int \partial q$
$\Delta U = \int \partial W + \int \partial q$. For the isochoric case $dV = 0 \implies \int \partial W = 0$, we get $\Delta U =\int \partial q$. Nice though, that for a 'one atomic' (ideal) gas, the internal energy $U$ is equal to the sum of the kinetic energies of the gas particles ($K$), which, from Maxwell-Boltzmann distribution, for one mole, turns out to be $K = \dfrac{3}{2}RT$. So, numerically, for the isochoric case, your approach works, though it cannot be generalized for the not-isochoric cases.
You are actually obtaining the molar isochoric heat capacity $C_v$ using this approach. The molar isobaric heat capacity of ideal gases is $C_p = \dfrac{5}{2}RT$, giving the famous equation
$$
C_p-C_v = R
$$


text:
Q: Auto close youtube video on colorbox pop up close I am using colorbox pop up having youtube video, but it does not close when youtube video ends.
Colorbox should automatically close at video ends.

A: For auto close you have to trap the YouTube video state. This state can interact with color box close event.
YouTube video state can be checked using YouTube API. Just visit the API at -
YouTube API
Available video states are -
unstarted=-1, ended=0, playing=1, paused=2, buffering=3, video cued=5
Getting video state one can hybridised the color box close event - parent.$.fn.colorbox.close()
Visit the full implementation of Colorbox close event and YouTube video API at INFOTOKRI with a sample demo.