ajax file upload

Question: hii i am using ajax file upload in this code

Please enable JavaScript to use file uploader.

but this code is giving me error this._element is undefined
[Break on this error] if (this._element.nodeType != 1){
please tell me what is the problem
using this one ...http://valums.com/ajax-upload/
Comment: I make the assumption here that your: fileuploader.js does Not use jQuery.
Answer: There is no id="file-uploader" element in your question, did you mean to do this instead?
element: $('#file-uploader_photo')[0],
//or without jQuery at all:
element: document.getElementById('file-uploader_photo'),

You can give it a try here.
Comment: @Rahul - It's working here with only that change: http://jsfiddle.net/nick_craver/mwDb8/ you sure you don't have the file cached or anything?
Comment: or perhaps element: $("div[id^='file-uploader_']")[0],
Comment: @Mark - Since you're using a `[0]` indexer it should be an exact/single match here ;) I would actually argue to leave jQuery out of it altogether, just `document.getElementById("file-uploader_photo")`
Comment: @Nick Craver - yes, I looked at that as well, but was making no assumptions regarding the rest of the code after viewing his code.  Probably a good idea here for your snippit as well since the [0] does return that singleton.  Seems like a wierd error and I wonder if there is some other issue in the full context of the code.
Comment: @Rahul - Is the demo I posted working for you?  If so there's something in addition to your question affecting this, is the code *exactly* as you posted? Try replacing `$('#file-uploader_photo')[0]` with `document.getElementById("file-uploader_photo")` just to take jQuery completely out of the picture.
Comment: @Mark - good point, I updated the snippet and demo here as well.
Comment: @Nick Craver - I get a "ContentWindow is undefined" error in your fiddle if I click the button.
Comment: @Mark - Sounds like a plugin error, which browser and are you running extensions/addons/plugins?
Comment: I am using IE8 in compatibility mode.  Only have the f12 developer add-in for that nothing else.  His markup template:xxx bothers me a bit, seems to be jQuery UI, but that is not in the sample.  I also pause when it is not wrapped given the jQuery selector.  I examined the plugin link and no "template:" is in those examples.(enough of my random thoughts already :)

ajax file upload


Can you call WCF web service methods from a web browser for testing purposes?

Question: I was thinking about moving from ASMX to WCF to implement web services. One thing that was sometimes very practical with ASMX web services is the fact that you can simply enter the URL of the asmx-file in a web browser and you get a simple user interface that allows you to call the web methods directly from the browser, e.g. for testing/debugging (at least as long as the methods do not take any complex parameters).
Is this also possible for WCF-based web services (hosted in IIS or in a windows service)?
Answer: did you try the WCFTestClient ? it is not a web browser but it does the job
Answer: The standard WCF messages are SOAP messages, and a browser doesn't normally do SOAP, so no - you cannot simply call WCF messages from a web browser. WCF also does not provide a "testing" ASPX page like ASMX did.
But WCF does provide - as Yassir already pointed out - a quite powerful and useful little SOAP tester called WcfTestClient which should be on your machine already.
If you're doing WCF REST however (webHttpBinding), then of course, you're simply exchanging XML documents via HTTP, so you can use a web browser in that case to hit your URLs and get the data payload back as XML.
Marc


How to get the number of physical and logical cores in a batch file on a dual socket machine?

Question: WMIC CPU Get NumberOfCores,NumberOfLogicalProcessors gets me most of what I want, but how do I store the combined output into a variable?
for /f "delims=" %%a in ('"WMIC CPU Get NumberOfCores,NumberOfLogicalProcessors /value"') do set /a "_%%a"
set _

Works for single socket machines only. The WMIC command returns cpu info on separate lines, i.e.
>WMIC CPU Get NumberOfCores,NumberOfLogicalProcessors /value

NumberOfCores=24
NumberOfLogicalProcessors=48

NumberOfCores=24
NumberOfLogicalProcessors=48

Comment: How is this different from https://stackoverflow.com/questions/71861185/how-to-get-the-number-of-physical-and-logical-cores-in-a-batch-file that you already asked today?
Comment: There was stern feedback to close and ask again with minor changes about the dual socket part
Comment: I've edited my answer to your previous question, but have no multiprocessor system to check. Please revisit and let me know if it works.
Answer: @echo off
setlocal

set /A "_NumberOfCores=_NumberOfLogicalProcessors=0"
for /F "tokens=1,2 delims==" %%a in ('WMIC CPU Get NumberOfCores^,NumberOfLogicalProcessors /value') do if "%%b" neq "" set /A "_%%a+=%%b"

set _

Note that wmic command output lines terminated in CR+CR+LF ASCII characters, even the empty lines, so it is necessary to check if the %%b part exists to avoid to process empty lines.
Answer: This will do it:
for /f "tokens=2,3 delims=," %%a in ('WMIC CPU Get NumberOfCores^,NumberOfLogicalProcessors /value /format:csv') do set "both=Cores=%%a Processors=%%b"

/format:csv changes up the format some, making it easier for us to manipulate, which I did in the above command.
Comment: This seems to execute `set "cores=24"   & set "processors=48` twice where I would like to get the total sum, i.e. cores=48 and processors=96
Comment: @roro You should learn how to manipulate basic variables. I edited my answer to do what you said.


bucket policy vs iam policy which one takes the precedence

Question: I have a task to create an S3 bucket named "xyz" and give Read-Write access to particular users. I have created the bucket and wrote an IAM policy like the following and attached it to specific users.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:GetObjectVersion",
                "s3:GetBucket"
            ],
            "Resource": [
                "arn:aws:s3:::xyz",
                "arn:aws:s3:::xyz/*"
            ]
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": "s3:ListAllMyBuckets",
            "Resource": "*"
        }
    ]
}

Now I have to apply another condition, that is restricting access to this bucket to a particular VPC. For that I have to write a bucket policy.
While trying to generate the bucket policy using policy generator it's again asking for actions on the S3 bucket.
If I select all the actions i.e, s3:* will it be giving all the access to the users?
I want to know which policy takes the precedence.
Answer: None of them takes precedence. This is the way permissions work in AWS:

Does any of the applicable policies explicitly allow access?
⇨ If not access is denied by default.
⇨ If yes go to the next step.
Does any of the applicable policies explicitly deny access?
⇨ If yes access is denied (even if another policy allows access).
⇨ If there is no deny access is now granted.

That means that if there is no applicable policy then access is by default denied and if any policy denies access then access is denied too.
Only if one or more policies explicitly allow access and none denies access only then access is granted.
In your case the bucket policy should deny access to everyone not in your VPC (using policy conditions). The IAM Policy will then grant access to your users while the bucket policy will deny access from outside of your VPC.
Also note that individual objects in S3 can have their own permissions too.
Best to refer to Overview of Managing S3 Access for all the details.
Hope that helps :)
Comment: @Nishanth almost the same task... but there's a distinction.  The IAM policy controls permissions for **your** user to access **any** bucket, while the bucket policy controls permissions for **any** user to access **your** bucket.  Both policies are required in order to grant access **unless** the same account owns both the user and the bucket, and that is the overlap you are seeing.  When both the user and the bucket are owned by the same account then either policy can grant a permission as long as the other policy does not deny it.
Comment: Thank you for the explanation. So almost both the policies are doing the same task. :)


Generate all possible combinations of choices from mutually exclusive options

Question: I have an optimisation problem that requires me to test all potential combinations of choices of potential portfolios, that I also need to be able to quickly adapt to exclude certain choices.
This must be done in Excel.
The rules for my sanitised example below:

I can chose to buy fruit from any of 3 grocers
The grocers may have different amount of aisles, and different combinations of fruit to select from
I can only pick one selection of fruit (or no selection at all) from all the grocers

Combinations

My first combintaon is no fruit from any grocer
In the next I pick apples from Aisle 3 from Grocer3
then apples from Aisle 2 from Grocer3
then apples from Aisle 1 from Grocer3
then I pick apples from Aisle 2 from Grocer2 and nothing from Grocer 3 (ie same  choice from Grocer 3 as combination 1 etc)
thenI pick apples from Aisle 2 from Grocer2, and  apples from Aisle 3 from Grocer3 (ie same  choice from Grocer 3 as combination 2)
And so on

All up this will give me 7*4*4 = 112 possible combinations consisting of

7 choices for Grocer 1 (6 selection choices + 1 do nothing)
4 choices for Grocer 2 (3 selection choices + 1 do nothing)
4 choices for Grocer 3 (3 selection choices + 1 do nothing)

1. Unconstrained Problem

My actual problem is far more complicated but the basic structure holds true.
What I would like to do is have an excel-formula or vba approach to populate all the available choices for:

The unconstrained problem.
A constrained problem (for example where I turn off Aisle 2 giving me 45 valid combinations)

2. Constrained Problem

What I have tried
I did solve an intial problem where the number of grocer options was the same with a MOD\INT approach. This was simple with a single formula as the patterns were repeatable.
If there is a smart formula solution then that would be preferred, but I'm open to code (and this is the route I am now trying)
Comment: + 1 For a nice + Clear + precise question :)
Comment: So correct me if I am wrong... You want to populate Cells `G3:G5` based on `D3:D5` + Row 12?
Comment: I want to populate C15 to Nx where (x-15) is the number of valid combinations
Comment: Oh ok.. `If there is a smart formula solution then that would be preferred, but I'm open to code (and this is the route I am now trying)` I can think of a VBA solution for this :p Can you upload a demo file with which I can play with?
Comment: @SiddharthRout uploaded to [here](https://skydrive.live.com/#cid=5D1B99F93ACE3CA1&id=5D1B99F93ACE3CA1%21122)
Comment: Thanks having a look at it now
Answer: In this Experts-Exchange PAQ http://rdsrc.us/qdl6tl I worked on a very similar problem to enumerate every combination of five different categories of things. The number of things in each category varied. The enumeration had to consider the possibility of no selection in a category as well as any one selection drawn from that category.
I approached the problem as writing a five digit number, where the number of possible digits at each position in the number was a variable.
Sub CombinatrixPlus()
'Forms all the combinations of at least two subattributes taken from a selection. _
    No more than one subattribute may be taken from any row.
'Uses variable base counting method

Dim i As Long, ii As Long, j As Long, k As Long, lenSep As Long, _
    m As Long, mCol As Long, mSheet As Long, mRow As Long, _
    N As Long, nBlock As Long, nMax As Long, nWide As Long
Dim v As Variant, vInputs As Variant, vResults As Variant
Dim rg As Range, rgDest As Range
Dim ws As Worksheet
Dim s As String, sep As String

Application.ScreenUpdating = False
sep = ", "      'Separator substring between each subattribute in results
Set ws = Worksheets("Sheet2")   'Put first batch of results in this worksheet
Set rgDest = ws.[A2]      'Put results starting in this cell
mSheet = rgDest.Worksheet.Index
mCol = rgDest.Column
lenSep = Len(sep)
Set rg = Selection      'Cells containing the subattributes
nBlock = 16384          'Maximum number of values in results array

'Clear the previous results
Application.DisplayAlerts = False
For i = Worksheets.Count To ws.Index Step -1
    Worksheets(i).Cells.Clear                   'Clear the cells
    If i > ws.Index Then Worksheets(i).Delete   'Delete the sheet
Next
Application.DisplayAlerts = True

N = rg.Rows.Count
nWide = N       'If results lists subattributes in separate cells
'nWide = 1      'If results lists subattributes as a single string with separators
ReDim v(N, 1 To 2)
vInputs = rg.Value
v(0, 2) = 1
For i = 1 To N
    v(i, 1) = Application.CountA(rg.Rows(i))
    v(i, 2) = (v(i, 1) + 1) * v(i - 1, 2)
Next
nMax = v(N, 2) - 1

ReDim vResults(1 To nBlock, 1 To nWide)
For i = 1 To nMax
    s = ""
    m = 0
    ii = ii + 1
    For j = 1 To N
        k = (i Mod v(j, 2)) \ v(j - 1, 2)
        If k <> 0 Then
            m = m + 1
            If nWide > 1 Then vResults(ii, j) = vInputs(j, k)
            s = s & sep & vInputs(j, k)
        End If
    Next
    s = Mid$(s, lenSep + 1)
    If nWide = 1 Then vResults(ii, 1) = s  'Results in a concatentated string
    If m < 2 Then ii = ii - 1

    If ii = nBlock Then
        Application.StatusBar = "Now posting combination " & i & " of " & nMax
        mRow = rgDest.Worksheet.Cells(Rows.Count, mCol).End(xlUp).Row
        If rgDest.Worksheet.Cells(mRow, mCol) <> "" Then mRow = mRow + 1
        If mRow < rgDest.Row Then mRow = rgDest.Row
        If (Rows.Count - mRow) >= nBlock Then
            rgDest.Worksheet.Cells(mRow, mCol).Resize(nBlock, nWide).Value = vResults
        Else
            mSheet = mSheet + 1
            If Worksheets.Count < mSheet Then Worksheets.Add After:=Worksheets(mSheet - 1)
            With ActiveSheet
                Set rgDest = .Range(rgDest.Address)
                For j = 1 To N
                    .Columns(j).ColumnWidth = ws.Columns(j).ColumnWidth
                Next
                mRow = rgDest.Row
                .Cells(mRow, mCol).Resize(nBlock, nWide).Value = vResults
            End With
        End If
        ii = 0
        ReDim vResults(1 To nBlock, 1 To nWide)
    End If
Next

If ii > 0 Then
        Application.StatusBar = "Now posting combination " & i & " of " & nMax
        mRow = rgDest.Worksheet.Cells(Rows.Count, mCol).End(xlUp).Row
        If rgDest.Worksheet.Cells(mRow, mCol) <> "" Then mRow = mRow + 1
        If mRow < rgDest.Row Then mRow = rgDest.Row
        If (Rows.Count - mRow) >= nBlock Then
            rgDest.Worksheet.Cells(mRow, mCol).Resize(nBlock, nWide).Value = vResults
        Else
            mSheet = mSheet + 1
            If Worksheets.Count < mSheet Then Worksheets.Add After:=Worksheets(mSheet - 1)
            With ActiveSheet
                Set rgDest = .Range(rgDest.Address)
                For j = 1 To N
                    .Columns(i).ColumnWidth = ws.Columns(j).ColumnWidth
                Next
                mRow = rgDest.Row
                .Cells(mRow, mCol).Resize(nBlock, nWide).Value = vResults
            End With
        End If
    i = rgDest.Worksheet.UsedRange.Rows.Count   'Reset the scrollbar
End If
Application.StatusBar = False   'Clear the status bar
Application.ScreenUpdating = True
End Sub

Comment: Test for all combinations listed =IF($A12>=(COUNTA($B$3:$B$8)+1)*(COUNTA($C$3:$C$8)+1)*(COUNTA($D$3:$D$8)+1),"",previously posted formulas)
Comment: Thank you for the quick response Brad, I will look to run through this tomorrow - much appreciated.
Comment: +1 This is 99.9% there. It gives me 99 of the 112 combinatons of my trial, missing only a) no selections (1) b) single selections (11).
Comment: For a formula only solution, the worksheet layout is inconvenient. So too is the desire to exclude certain possible values.
Comment: =IF(D11="",INDEX(D$3:D$8,1),IF(MATCH(D11,D$3:D$8,0)=COUNTA(D$3:D$8),"",INDEX(D$3:D$8,MATCH(D11,D$3:D$8,0)+1)))    formula for right-most position
Comment: =IF(COUNTIF(D12:$D12,"?*")>0,C11,IF(C11="",INDEX(C$3:C$8,1),IF(MATCH(C11,C$3:C$8,0)=COUNTA(C$3:C$8),"",INDEX(C$3:C$8,MATCH(C11,C$3:C$8,0)+1))))     formula for other positions
Comment: The above formulas are using three columns of possible values in cells B3:D8. This range includes some blank cells at the bottom of each column. The number of blank cells may vary with column. The formulas restart the list once all combinations are satisfied.


Block direct access to subfolders with .htaccess or other methods

Question: Sorry for my bad english :)
I've a question.
How can i block with an error page, or redirect an user that is trying to access subfolders, in my website? I don't need password protected folders but just a displayed error for all subfolders.
Example:
www.mysite.com/folder - this folder content should not be visible to users
Answer: This is a simple solution without editing the .htaccess file.
Create a new index.html or index.php file in your folder and write these line on the body.
In PHP:
    <?php
      header("Location:../index.php");
    ?>

In HTML:
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <meta http-equiv="refresh" content="1;url=http://www.yourDomainName.com">

    <title>Page Redirection</title>

    If you are not redirected automatically, follow the link to Your domain name home page

From this way you can block

www.yourDomain.com/img

folder

www.yourDomain.com/css

folder and other folders you wish to deny access easily. I don't know still can hackers bypass this files but this is the simple solution. Try this and see the answers for yourself.


Show default phone wallpaper in ImageView

Question: How to display users phone wallpaper to ImageView using Java in Android Studio?
Comment: Welcome to Stack Overflow At this site you are expected to try to write the code yourself. After doing more research, if you have a problem you can post **what you've tried with a clear explanation of what isn't working** and providing a Minimal, Complete, and Verifiable example. I suggest reading [How to Ask](https://stackoverflow.com/help/how-to-ask) a good question and the [perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/). Also, be sure to take the [tour](https://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/6676466).
Comment: https://stackoverflow.com/a/9939358/5192105
Answer: <code>Drawable wallpaper = WallpaperManager
            .getInstance(this)
            .getFastDrawable();
</code>
You can get it like this.


hook_nodeapi is not working in D8

Question: As per the api the hook_nodeapi should be called before saving the node .But its not calling the function at all when i try to save the node . How could i solve this ?
/**
 * hook_nodeapi, this function used to intercept the node before doing any
 * action on it
 *
 */
function module_name_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
    echo 'in hook_nodeapi';exit;
    call_fn_on_save($node, $op);
}

Answer: hook_nodeapi was in Drupal 6 (which is not supported now) and has been removed starting from Drupal 7. In Drupal 8, if you want to do something when Node/Entity has been created/updated you can check respective hook_entity_[HOOK] or hook_ENTITY_TYPE_[HOOK] provided by Entity API. A complete list of all hooks provided by Entity API in Drupal 8 Core can be accessed here.
Comment: Did you tried re-building cache after implementing this hook?
Comment: `hook_entity_presave` is what you are looking for.
Comment: Its not callling to **function module_name_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
    die($entity->id());
}** also , I tried it
Comment: And **function module_name_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
    die($entity->id());
}** not working too
Comment: thanks , its now okay i guess :) I cleared the cache , But only entity_presave worked , entity_update not worked
Comment: `hook_entity_presave` is called before entity is created or updated, whereas `hook_entity_update` is only called when entity is updated.
Comment: Which should i rely on based on my condition ? I need to execute it before saving a node (New & Existing)

hook_nodeapi is not working in D8


Numerous questions about advanced guitar tablature notation

Question:
8 slide 0...why is 0 in parentheses?

7 slide 9...what does curve under mean?

5 7 5..7 5 0..are they hammers or pull offs..how you distinguish those

how to play this?

what does this long line mean?

15 slide 17 with curve and 17 slide 19 with no curve...what is difference?
Comment: This is pretty standard notation, not just for Guitar Pro.
Answer: I'll answer each of your questions in order:
The notes in parentheses are ghost notes. You should play them quietly - certainly don't emphasize them. They do have rhythmic value, however (i.e. they aren't grace notes).
The 7 to 9 slide is a legato slide. Pick the 7, then slide to 9, but don't pick again for the 9.
The 5-7-5, 7-5-0 are indeed hammer-ons and pull-offs. The same legato notation works for both: if a note is followed by a higher note, it will be a hammer-on; if it is followed by a lower note, it will be a pull-off. So in your example, 5-7-5 is a hammer-on (5-7) followed by a pull-off (7-5). The 7-5-0 would be two pull-offs (7-5, 5-0).
I'm not entirely sure about the next one (in this case it might help to see the staff notation). Certainly you would play the chord and then play the hammer-ons and pull-offs on the top line (B string). Possibly you should keep the rest of the chord fretted so it will ring, or at least the 6 on the G string for a gentle pull-off to (0) at the end. But I'm not certain.
The 14-12-14-12 etc with the long line over-top is a long series of pull-offs and hammer-ons.
The 15 to 17 slide with the legato marking has the same meaning as the 7 to 9 slide in your first question: pick 15, slide to 17, don't pick again. The 17 to 10 slide means pick the 17, slide to 19, and pick again.
Comment: thx, detailed answer


Filtering firebase using multiple queries

Question: I have a list of users in an array: let userArray = ["userId1", "userId2"]. I'm trying to pull the list of all comments for a given postId and filter the results to only pull those where the userId is in userArray. Below is my code so far but it doesn't seem to be working. Is there a better way to approach the problem?
//pulls all comments given a postId of "postId1"
  let commentsRef = databaseRef.child("comments").queryOrdered(byChild: "postId").queryEqual(toValue: "postId1")

      commentsRef.observe(.value, with: { (comments) in

        var resultArray = [Comment]()
        for comment in comments.children {

           let value = child.value as? NSDictionary

           let userId = value?["userId"] as? String ?? ""

               for contactinfo in userArray {
                   if(contactinfo = userId) {
                     let comment = Comment(snapshot: comment as! DataSnapshot)
                                resultArray.append(comment)
                            }
                        }
                        completion(resultArray)

                    }
                })
    })

Firebase:
Comments
-CommentId1
 -postId: "postId1"
 -userId: "UserId1" //RETRIEVE
-CommentId2
 -postId: "postId2"
 -userId: "UserId50" //DO NOT RETRIEVE

Comment: "I have a list of users in an array"  Firebase also has a list of products.
Comment: Firebase Database queries can only order/filter on a single property. In many cases it is possible to combine the values you want to filter on into a single (synthetic) property. For an example of this and other approaches, see my answer here: http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase
Comment: I'm going with @FrankvanPuffelen on this. As an alternative, depending the quantity of data, you could add a .childAdded event to the Comments node - that will iterate over each child node (CommentId1, CommentId2 etc). Compare the userId child value with what's in your array and ignore the ones that don't match and process the ones that do. OR if there are just a couple hundred comments, read them in via observerSingleEvent(.value... and iterate over the child nodes in code; ignore the ones that don't match and process the ones that do. It all depends on how many child nodes and qty of data.
Comment: As a side note, your code isn't working because the database node is Comments (capital 'C') and your code is trying to read 'comments' (lower case 'c'). Other than that, it's pretty close to one of my suggestions, although I would suggest creating a class var array to store the comment (self.commentArray) and populating that and upon completing the for loop do something with the array. Also, you are adding an observer query so anytime anything changes that matches your query, the code in the closure will be called - not sure if that was intentional or not.
Comment: Thanks Jay. Sorry, I'm relatively new to Firebase so excuse my basic questions. Can you provide an example of what you mean by this "As an alternative, depending the quantity of data, you could add a .childAdded event to the Comments node - that will iterate over each child node (CommentId1, CommentId2 etc). Compare the userId child value with what's in your array and ignore the ones that don't match and process the ones that do."  What would a sample code look like
Answer: In this condition, you are doing a 'and' query, according to the doc, you should put multiple query together like this.
// Create a reference to the cities collection
let commentsRef = db.collection("comments")

// Create a query against the collection.
commentsRef.whereField("postID", isEqualTo: "post1")
commentsRef.whereField("userID", isEqualTo: ['user1', 'user2'])

Checkout the doc for more detail. https://firebase.google.com/docs/firestore/query-data/queries.
---EDIT---
Emmmmm, I will remain above answer if you change your database selection.
I read this link Query based on multiple where clauses in Firebase
.
So I think you should be able to add a custom index on you comments model like this
Comments
  -CommentId1
    -postId: "postId1"
    -userId: "UserId1" //RETRIEVE
    -idx: "postID1+UserID1"

Now you could do the query on this index. And if you want to retrieve multiple users records, you could simply loop the users array.
Comment: I should have mentioned that I'm using the realtime database so it doesn't have that function. https://firebase.google.com/docs/database/ios/read-and-write
Comment: The API you call is for Cloud Firestore. OP is using the Firebase Realtime Database.
Comment: Emmmm, in this condition, I think you should write a cloud function to extend what your need.
Comment: Can you please update your answer to make it an answer? As is, it's not really helpful. Perhaps showing what you mean and an example of a *Cloud Function* and a trigger that would provide the result the OP wanted?
Comment: But keep in mind: Cloud Functions is just a (admittedly very convenient) place to run code that triggers on and interacts with Firebase. It can't magically do something that the API doesn't allow. Since the Firebase Realtime Database doesn't allow filtering on multiple properties, that also isn't possible in Cloud Functions.
Answer: Here are two examples of how to retrieve the posts from a specific user - either option could be expanded to exclude posts from unwanted users by adding additional if statements.
Here's the Firebase structure
comments
-CommentId1
 -postId: "postId1"
 -userId: "UserId1" //RETRIEVE
-CommentId2
 -postId: "postId2"
 -userId: "UserId50" //DO NOT RETRIEVE

and the code tied to two different buttons in the UI
var postsArray = [String]()
let userIdWeWant = "userId1"

func button0() {
    self.postsArray = []
    let commentsRef = self.ref.child("comments")
    commentsRef.observe(.childAdded, with: { snapshot in
        let dict = snapshot.value as! [String: Any]
        let userId = dict["userId"] as! String
        if userId == self.userIdWeWant {
            let post = dict["postId"] as! String
            self.postsArray.append(post)
            print(post)
        }
    })
}

func button1() {
    self.postsArray = []
    let commentsRef = self.ref.child("comments")
    commentsRef.observeSingleEvent(of: .value, with: { snapshot in
        for child in snapshot.children {
            let childSnap = child as! DataSnapshot
            let dict = childSnap.value as! [String: Any]
            let userId = dict["userId"] as! String
            if userId == self.userIdWeWant {
                let post = dict["postId"] as! String
                self.postsArray.append(post)
            }
        }
        print(self.postsArray)
    })
}

As it is, we are just capturing posts from userId1 and adding them to an array, but say we wanted to capture posts from any user that loves pizza and has a shoe size of 13. So the structure would be
comments
    -CommentId1
     -postId: "postId1"
     -userId: "UserId1" //RETRIEVE
     -food: "Pizza"
     -shoe: "13"

and a code snippet would be
let shoe = dict["shoe"] as! String
let food = dict["food"] as! String
if shoe == self.shoeWeWant && food == self.foodWeWant {

EDIT
Per a question in a comment, 'get any uid stored in the uid array', it's super simple in Swift 4. Here's an example to see if an object exists in an array
var uidArray = ["uid0", "uid1", "uid2", "uid3"]
if uidArray.contains("uid1") {
    print("it exists! Do something with it!")
} //otherwise ignore it

that technique could be used to see if the read in array with
let userId = dict["userId"] as! String

exists in the array of users you are interested in.
Comment: This is great. But what if the userIdWeWant is any userId stored in the array userIdArray. How would we modify the code?
Comment: @JohnWong Great question with a super simple answer. I edited my question with an additional answer to address your question.


How to sign Mac OS X application?

Question: I created a Mac OS X application but I don't know which steps I have to do for signing my Mac OS X application correctly.
Thank you.
Answer: I found the Apple documentation far too verbose. I have written up some detailed notes on how I signed my own software for Mac. There is too much to put it all here. See:
http://successfulsoftware.net/2012/08/30/how-to-sign-your-mac-os-x-app-for-gatekeeper/
Comment: I seem to have mistakenly downvoted your answer - and now I can't undo it unless the answer is edited...
Answer: At first you need an fully functional (and thus paid) Apple developer account.
Then you can follow this information: https://developer.apple.com/library/archive/documentation/Security/Conceptual/CodeSigningGuide/Introduction/Introduction.html
The above link is the global procedure, but there is a specific topic with clean illustrated how to at the following URL: https://developer.apple.com/library/archive/documentation/Security/Conceptual/CodeSigningGuide/Procedures/Procedures.html#//apple_ref/doc/uid/TP40005929-CH4-SW2
Answer: With Qt
macdeployqt APP_NAME.app -codesign="Developer ID Application: YOUR NAME (ID_NUMBERS)"

Otherwise
codesign --force --verify --verbose --sign "Developer ID Application: YOUR NAME (ID_NUMBERS)" APP_NAME.app

You also need to sign every framework and dylib file into the package with something like this
codesign --force --verify --verbose --sign "Developer ID Application: YOUR NAME (ID_NUMBERS)" APP_NAME.app/Contents/Frameworks/QtCore.framework/Versions/5/QtCore
codesign --force --verify --verbose --sign "Developer ID Application: YOUR NAME (ID_NUMBERS)" APP_NAME.app/Contents/Plugins/bearer/libqcorewlanbearer.dylib

Comment: Can you give me an example of those variables? Wdym ID_NUMBERS, are the parenthesis meant to be their?
Answer: There is good Apple documentation on this. Go to the developer provisioning section and there is a good primer there that can get you running quickly.
Comment: If you at least put a link in to help, I would have voted you up.
Comment: I couldn't put a link in as answering from work where the apple developer site is blocked.
Answer: When you sign an app, all executables inside that app need to be signed, otherwise, the notarization will fail.
I wrote this node code that will recursively find all executables within an app and sign them.
#!/usr/bin/env node
// 5.14

const APP = "./yourAppName.app";
const IDENTITY = "your_signature_";

/****************************************************************************/
const items = [];
console.log("### finding things to sign");

const fs = require('fs');
const child_process = require('child_process');
const recursive = require("recursive-readdir");
const listdirs = require('listdirs');

const folder = `./nwjs.app`;

const main = async()=>{

    const allFiles = await recursive(folder);
    const exeFiles = allFiles.filter((x)=>{
        try {
            fs.accessSync(x, fs.constants.X_OK)
            return true;
        } catch (error) {
            return false
        }

    })
    console.log("all files", exeFiles);
    items.push(...exeFiles)

    const myListDir = (folder)=>{
        return new Promise((resolve, reject) => {
            listdirs(folder, function callback(err, list){
                if(err){
                  return reject(err)
                }
                else {
                  return resolve(list)
                }
            });
        });
    }

    const allFolders = await myListDir(folder);
    const appFolders = allFolders.filter((x)=>{
        return x.endsWith(".app")
    })

   console.log("all Folders", appFolders);
   items.push(...appFolders)

    /****************************************************************************/

    console.log("");
    console.log("### signing");

    function exec(cmd) {
        console.log(cmd);
        const result = child_process.spawnSync(cmd, {shell: true, stdio: 'inherit'});
        if (result.status !== 0) {
            console.log(`Command failed with status ${result.status}`);
            if (result.error) console.log(result.error);
            //process.exit(1);
        }
    }

    items.push(`${APP}/Contents/MacOS/nwjs`)

    for (const item of items) {
        try {
            exec(`codesign --verbose --force --deep --strict --options runtime --timestamp --sign "${IDENTITY}" --entitlements neededToRun.entitlements "${item}"`);
        } catch (error) {
            console.log(error);
        }

    }

    exec(`codesign --verbose --force --deep --strict --options runtime --timestamp --sign "${IDENTITY}" --entitlements neededToRun.entitlements "${APP}"`);

    /****************************************************************************/

    console.log("");
    console.log("### verifying signature");

    exec(`codesign --verify -vvvv "${APP}"`);
}

main();

How to sign Mac OS X application?


Laravel 5.5 global variable in template from service provider

Question: How can I get info about logged user in service provider? When I use this in my template {{ $test }} always return 0 but i'm 100% sure that im logged in. Or mybe you have better solution?
use Illuminate\Support\ServiceProvider;
use Auth;
use View;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $user = Auth::user();
        if ($user !== null) {
            $walletsCount = $user->wallets()->count();
        } else {
            $walletsCount = 0;
        }
        View::share('test', $walletsCount);
    }
}

Comment: but you already have the user when you make Auth::user()
Comment: you don't have Sessions until the session middleware has ran ... service provider @ boot is called super early in the lifecycle, well before the request gets to that middleware
Comment: `Auth::user()` is already global therefore I don't quite understand your intentions...
Comment: when im using this in controller I don't have any problem. I want to have count of wallets in templates.
Comment: I still don't understand the intention here... It's almost like you're wanting a ComposerServiceProvider. Please clarify
Comment: @lagbox so how can I save my count? I have many controllers so i need to do this in one place
Answer: You do not have access to sessions this early in the request lifecycle, by default. The web group of middleware has a StartSession middleware which is responsible for actually starting and loading the session. The Auth system by default, web guard, uses sessions to store the user. So you don't have access to the session yet, so the user will return as null. The request hasn't even made it to that stack of middleware yet.
You could add a middleware to do this. Add the middleware to the end of your web stack. When this middleware gets ran the previous middleware in the stack have already loaded the session so you will have access to your authenticated user there.
If this is like a layout you need this variable for you could use a view composer instead. There are some options depending on exactly your need.
Answer: It's happening because auth functionality is not initialized yet when Laravel is loading service providers. One way to deal with it is to move the logic to the view:
{{ auth()->check() ? auth()->user()->wallets()->count() : 0 }}

Another way to go is using a view composer with closure:
public function boot()
{
    view()->composer('*', function($view) {
        $view->with('walletsCount', auth()->check() ? auth()->user()->wallets()->count() : 0);
    });
}


Existe diferença ao juntar dois arrays com array_merge ou com "+"?

Question: Eu costumava unir dois arrays, em PHP, usando a função array_merge:
$arr3 = array_merge($arr1, $arr2);

No entanto, mais recentemente passei a ver uniões de arrays com + (sinal de soma):
$arr3 = $arr1 + $arr2;

Existe alguma diferença entre esses os dois métodos?
Comment: @WallaceMaxters valeu pelo toque, quando eu havia escrito o título esse post não apareceu. No entanto, a resposta é boa, então vou validá-la assim mesmo. :)
Comment: Rodrigo, sem problemas. É melhor porque as perguntas fazem referência uma a outra. No caso, você usou o operador "+" no título, e eu coloquei "soma".
Answer: Existem duas diferenças entre + e o array_merge():
Operador +:
Quando usamos este operador no caso de termos elementos com as mesmas chaves (sejam elas numéricas ou não) os valores do array da esquerda prevalecem  sobre os do array da direita. Considere o exemplo:
$a = array("a" => "apple", "b" => "banana", 'lol');
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry", 'lil');

$merged = $a + $b;

Resultado:
(
    [a] => apple
    [b] => banana
    [0] => lol
    [c] => cherry
)

Como se pode ver, em elementos com a mesma chave em ambos os arrays ($a e $b), só os de $a foram considerados, ignorando os elementos em $b.
Com array_merge():
Aqui é o oposto, no caso de termos chaves iguais (não numéricas) as do array da direita  prevalecem sobre as do da esquerda. No caso de termos chaves numéricas, e serem as mesmas chaves em ambos os arrays elas são redefinidas de maneira a que ambos os elementos sejam incluidos na fusão:
$a = array("a" => "apple", "b" => "banana", 'lol');
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry", 'lil');

$merged = array_merge($a, $b);

Resultado:
(
    [a] => pear
    [b] => strawberry
    [0] => lol
    [c] => cherry
    [1] => lil
)


For $X_i \sim \mathcal{N}(\mu_0, \sigma^2)$, show that $\hat{\sigma}^2_0 = n^{-1} \sum_{i=1}^n (X_i - \mu_0)^2$ is a UMVU estimate of $\sigma^2$

Question: Somewhere along the way I make an error and I can't seem to find where.
I mostly use central moments in the derivation so I will state them here for the sake of  completeness: for $X \sim \mathcal{N}(\mu, \sigma^2)$,
$$
\mathbb{E}(X - \mu)^2 = \sigma^2, \quad \mathbb{E}(X - \mu)^4 = 3\sigma^4, \quad \mathbb{V}(X - \mu)^2 = \mathbb{E}(X - \mu)^4 - (\mathbb{E}(X - \mu)^2)^2 = 3\sigma^4 - \sigma^4 = 2\sigma^4.
$$
Firstly, it's easy to show that the estimator $\hat{\sigma}^2_0(\mathbf{X})$ is unbiased. Therefore, the information inequality (or equality for uniform minimum variance unbiasedness) takes the form
$$
\mathbb{V}(\hat{\sigma}^2_0(\mathbf{X})) \geq \frac{1}{n I_1(\theta)}.
$$
where $I_1(\theta)$ is the Fisher information number. Lets derive $I_1(\theta)$ first
\begin{align}
I_1(\theta) = \mathbb{E}(\frac{\partial}{\partial \theta} \log p(x, \theta))^2 & = \mathbb{E}(\frac{\partial}{\partial \theta}(-\frac{1}{2\sigma^2}(x - \mu)^2 - \log(\sqrt{2\pi}\sigma ))^2, \\
& = \mathbb{E}(\frac{1}{\sigma^3}(x-\mu)^2 - \frac{1}{\sigma})^2, \\
& = \mathbb{E}(\frac{(x-\mu)^2 - \sigma^2}{\sigma^3})^2, \\
& = \frac{\mathbb{E}(x-\mu)^4 - 2 \sigma^2 \mathbb{E}(x-\mu)^2 + \sigma^4}{\sigma^6}, \\
& = \frac{3\sigma^4 - 2\sigma^4 + \sigma^4}{\sigma^6}, \\
& = \frac{2}{\sigma^2}.
\end{align}
Now for the variance of the estimator,
\begin{align}
\mathbb{V}(\hat{\sigma}^2_0(\mathbf{X})) & = \mathbb{V}(n^{-1} \sum_{i=1}^n (X_i - \mu_0)^2) \\
& = n^{-2} \sum_{i=1}^n \mathbb{V}(X_i - \mu_0)^2 \\
& = n^{-2} n 2 \sigma^4 \\
& = n^{-1} 2\sigma^4.
\end{align}
Now the inequality takes the form
$$
\frac{2\sigma^4}{n} \geq \frac{\sigma^2}{2n}
$$
So what is missing is a square value of $\sigma$ and a factor of 2.
Answer: You are trying to estiamte $\sigma^2$, so in the definition of Fisher information, you should take derivative with resepct to $\sigma^2$ and not $\sigma$ which you currently seem to be doing.


Partition of interval is countable

Question: Consider the arbitrary partition of the real non-empty interval $[a,b)$, into the disjoint sets $[\alpha(i),\beta(i))$ where $i\in I$ and $I$ is some index set. Why is it necessary that $I$ be countable? Isn't it true that $[a,b)$ contains an uncountable set that could serve as a source of candidates for the endpoints of the partition intervals?
Comment: There is a surjection from some subset of $\mathbb{Q}$ to the set of intervals.
Answer: Hint: Each interval contains a rational.
Added: The following is probably more explicit tha necessary. Let $r_1,r_2, r_3,\dots$ be an enumeration of the rationals. For each $i\in I$, let $n_i$ be the least index such that $r_{n_i}$ is in $[\alpha(i),\beta(i))$. Then the set $\{n_i\}$, as $i$ ranges over $I$, is a subset $M$  of the natural numbers, and the mapping $i\to n_i$ gives a bijection between $I$ and $M$. Thus $I$ must be finite or countably infinite.
Comment: If you had an uncountable indexing set $I$, each set in $I$ would contain a rational. Hence there would be uncountably many rational numbers in the interval $[a,b)$, but the set of rationals is....
Comment: I know that I have to construct a one-to-one mapping from $I$ to the rationals, but I don't see how to use the hint.

Partition of interval is countable


Convergence of a series with M-test

Question:
$\sum\limits_{k=1}^{\infty} \frac{\exp({x^k})}{5k^2}$

I have a request on the convergence of this function series over the interval $(0,1)$, (look above). My idea is to do the $M$-test or comparison criterion. So because of that you can say that $e^{x^k}$ is $< e^x$ and then do the Quiotient criterion. Is that one good approach?
Comment: $e^{x^{k}}<e^{1}$.
Comment: Okay, and then we have e/(5k^2) and then with we have e/5 * 1/k^2 and that is convergent
Comment: It is better to use some latex to write math formula and use dollar signs to include the code. Ref: https://latexeditor.lagrida.com/
Answer: $e^y$ is monotonically increasing, so $e^y<e^1$ for every $y\in (0, 1) $. In particular if $x\in(0, 1) \implies x^k\in (0, 1) $ for every $k\in\mathbb{N}$. So we have that $$\frac{e^{x^k}}{k^2}<\frac{e^1}{k^2}\sim \frac{1}{k^2}, $$ and by the M-test $$\sum \frac{e^{x^k}}{k^2}, $$ converges uniformly in $(0, 1) $.
Comment: Okay, thank you very much. It is possible to show that the series is continuous?
Comment: The partial sums are continuos functions, so the uniform limit of a continuos Sequence is continuous
Comment: So if the question is: the boundary function is continuous than I must build the limits
Comment: What do you mean by boundary function?
Comment: if you want to check if the limit function is continuous because we should also show that the limit function is continuous
Comment: You dont have to. The sums $f_n(x)=\sum_{k=1}^N \frac{e^{x^k}}{k^2}$ are continuous, if $f$ is the uniform limit of the $f_n$ we Know that is continuous, is a theorem

Convergence of a series with M-test


como pegar url de requisições do console em javascript

Question: galera eu preciso pegar a url de um get do console eu quero saber isso pq eu tenho um iframe que eu preciso pegar a url de um get dele so que na url existe uma variavel randomica que fica mudando sempre que dou reload existe alguma maneira de eu pegar a url direto do console
Comment: Elvis, bem-vindo ao [pt.so]! A meu ver não está muito claro o que você está querendo obter. O console registra as requisições para que você possa inspecionar, mas não é algo que faz parte do escopo de uma página. Você quer monitorar as requisições feita pela página do `iframe`? Quer executar algo com isso ou apenas inspecionar no console? Como está fazendo isto agora? Por favor, tente esclarecer esses pontos para podermos ajudar você melhor.
Comment: tipo isso por exemplo, eu tenho um iframe na minha pagina, esse iframe faz um get, eu preciso pegar a url deste get mais nesta url tem uma variavel que muda a cada vez que a pagina é visitada e essa variavel funciona como uma chave entende, a variavel é mudada atraves do javascript do iframe e como eu n posso mudar o codigo do iframe n tenho como pegar esta variavel mudada, a unica maneira de conseguir seria pegando o get do console com todas as variaveis já certinhas
Comment: A não ser que você esteja implementando uma extensão para o Chrome, não creio que você possa acessar informações do console a partir da sua página principal. Além disso, se a sua página está em um domínio diferente daquela do `iframe`, então por questões de segurança vai ser impossível você interagir com ela em JavaScript.
Comment: A que tipo de variável você se refere? Seria um parâmetro de URL ou uma variável global da página? Caso você tenha acesso ao `iframe`, supondo que não haja restrições de segurança, você poderia listar todas as variáveis e identificar o nome dessa variável que você procura. Ou ainda se essa requisição usar JQuery, você pode adicionar um *hook* global para escutar às requisições AJAX. Mas teria que saber mais detalhes para dizer exatamente o que é possível e o que não é.
Comment: psé mais o iframe n deixa eu fazer modificações vou dar algum jeito de fazer diferente.
Answer: você pode obter os parametros da URL atravez do objeto, window, segue um exemplo abaixo.

Segue também outra função para conseguir os parâmetros no formato de objeto.
<code> function getQueryParams() {
   var queryParameters = window.location.search.split('+').join(' ');

   var params = {},
       tokens,
       re = /[?&]?([^=]+)=([^&]*)/g;

   while (tokens = re.exec(queryParameters)) {
     params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
   }

   return params;
 }
</code>
Comment: tipo não sao as variaveis da minha url o get é feito atraves de uma pagina externa queria pegar as variaveis dessa url externa lembrando que esse get é feito por um iframe por isso n consigo pegar direto pelo meu javascript


Como acessar um dado de dentro do objeto, estando no mesmo objeto

Question: let carryData = {
    prova: Number(34),
    semanal:Number(345),
    aExtra:Number(543),
    total:??? //quero o valor da prova, nesse mesmo objeto
}

Answer: Se você quer declarar a propriedade total com o mesmo valor, terá que duplicar o valor atribuído a prova.
Agora se total é apenas uma propriedade para acessar o valor, você pode declarar ela como um getter.

let carryData = {
    prova: 34,
    semanal: 345,
    aExtra: 543,
    get total() {
        return this.prova;
    }
};

console.log(carryData.total);


How do you set up redundant servers?

Question: To the sysadmins out there, I'm trying to get an idea about how you go about maintaining redundant servers for small projects. The modest number of servers in my mind is two, and three main essential services come to mind: HTTP, mail and DNS. How do you automate this duplicity? Is rsync the tool of choice (again, for small projects)?
In addition to common tools for these tasks, references to books and articles would be greatly appreciated. The more hands-on the approach, the better.
Answer: It sounds like your real question is actually how to make a service highly available (ignore if that is not the real question). Since you are talking about servers, services and data (zone files, apache docroot, ...) -- if my guess is right you might want to adjust the title and tags of your question :)
Redundancy (as in multiple copies of the data)
can be achieved with:

drbd (synchronous -- gives you certain guarantees that on both servers there'll always be the same data)
rsync (asynchronous -- no guarantees about data consistency between 2 hosts)

scp or any other tool that can copy data between hosts (or even cp if you NFS mount)

I believe that is not what you're actually asking for...
High Availability
rsync is not the tool of choice for high availability (HA).
It is the tool of choice if you want to synchronize 2 directories.
You should walk thru the Clusters from Scratch Guide from Clusterlabs to get an idea. This covers the following topics:

HA of Services
Migration of Services between Hosts (so that any one can go down and you are still providing service)
Sample Services

Apache (without any synchronization for the data)
drbd (syncrhonous block device synchronization)
GFS (Cluster File System that allows the same block device to be mounted by different hosts)

Active/Passive and Active/Active Clusters

It's more or less a step-by-step howto that will give you the right pointers. But be aware that HA is not a topic to get right in one afternoon if you just started with it. Also since you tagged it with sysadmin-basics: expect having a hard time (but it will pay off after understanding the concept)
Comment: Thanks a lot! I guess having redundant servers may be considered HA, but I wanted pointers about the technical aspects of server redundancy, which you provided very thoroughly. I by no means plan to get this in one afternoon... I just didn't know where to go to get started. Thanks again.
Comment: Fantastic! Thank you for the well written response and resources!
Answer: Redundancy isn't usually something you just slap onto existing systems with rsync. For HTTP it's common to use a load balancer that supports failover such as HAProxy or MS's NLB, or possibly an IP sharing solution like CARP; the backend server would serve from a common shared storage, or two file system synchronized with something like rsync, or a database system (again, could be more or less complicated). For e-mail, it has it's own systems in conjunction with DNS to provide round robin and preference order for SMTP; multiple POP or IMAP servers to front a redundant DBMS; or Exchange has DAGs. DNS also has its own mechanisms, mainly multiple name servers in master/slave configurations (or multimaster in some cases).
How you achieve redundancy in a particular situation, with particular software, is highly dependent on your requirements; certainly not a one-size-fits-all that I can point you to a quick how-to document.
Answer: This is a pretty broad question; since you mention rsync, I assume you are talking about a *nix system.
It really depends on the type of setup you have. If your HTTP service is fully static (no database, or what-have-you) then two twin apache servers with an rsync'ed root directories.
Mail is more tricky, because if you are hosting mailboxes, they're probably in a database, and rsyncing a database at the file-system level will cause corruption.
Depending on how your DNS works (if it uses flat-files for storage) you could also configure the DNS software to run the same on both machines and rsync the flat-files, if it uses a database or custom binary file, rsync will not help.
There ARE enterprise level systems available for this, but since you asked specifically about small-projects I presume that they are out of your scope.

How do you set up redundant servers?


Good upper bound for $\sum\limits_{i=1}^{k}{n \choose i}$?

Question: I want an upper bound on $$\sum_{i=1}^k \binom{n}{i}.$$
$O(n^k)$ seems to be an overkill -- could you suggest a tighter bound ?
Comment: Do you mean $\sum_{i=1}^k {n \choose i}$?
Comment: Assuming $n$ grows while $k$ is a fixed constant, the given sum is $\frac{n^k}{k!}+ O(n^{k-1})$. This is tight up to the constant in the $O$ notation.
Comment: @Srivatsan, if $k$ is a fixed number, then the constant factor $\frac{1}{k!}$ is irrelevant for the growth rate.
Comment: @Hen Thanks. Fixed now :-).
Comment: @Robert - yes, of course, sorry. Fixed.
Comment: @Srivatsan - so, $O(n^k)$ it is, I guess ?
Comment: On the other hand, if $k \ge c n$ where $c > 1/2$, then the sum is $(1 + o(1)) 2^n$.
Comment: For certain values of $k$ we can get a good estimate from the Central Limit Theorem by considering an iid sequence of Bernoulli $\\{0,1\\}$ random variables.
Answer: We are interested in the sum $$V(n,k) := \sum\limits_{i=0}^k \binom{n}{i}.$$ (Notice that I have added $i=0$ for convenience. This affects the sum only by an additive $1$.) Indeed, this quantity has a combinatorial significance: it is the volume of a "Hamming ball" of radius $k$ in the Hamming space (the $n$-dimensional hypercube). It is quite difficult to say anything precise without information about the relative sizes of $k$ and $n$. I will therefore address some common regimes of interest in the answer. Without loss of generality, we will take $k \leq n/2$, since for $k > n/2$, we can write $V(n, k)$ as $2^n - V(n, n-k+1)$.
First, suppose that $n$ grows while $k$ is a fixed constant independent of $n$. Then the lower order terms (terms corresponding to $i < k$) are all $O(n^{k-1})$. Since there are just $k$ of them, we can absorb all of them into a single $O(n^{k-1})$. The remaining term $\binom{n}{k}$ is a polynomial in $n$ of degree $k$ and leading coefficient $\frac{1}{k!}$.  Therefore, this term is $\frac{n^{k}}{k!}+O(n^{k-1})$. Combining these two observations,
$$
V(n,k) = \frac{n^{k}}{k!} + O(n^{k-1}).
$$

Another regime of interest is when $k$ is large. Specifically, suppose $k = \alpha n$ where $\alpha \in (0, 1/2)$. In this case, by Stirling approximation and a lot of calculations, we can show that
$$
V(n, \alpha n) = 2^{n H(\alpha) - \frac{1}{2} \log_2 n + O(1)},
$$
where the exponent $H(\alpha)$ is the Shannon entropy or the binary entropy given by:
$$
H(\alpha) = - \alpha \log_2 \alpha - (1-\alpha) \log_2 (1-\alpha).
$$
For $\alpha \in (0, 1/2)$, $H(\alpha)$ is strictly increasing and is strictly positive. I want to point out that when $k$ is so large, the $n^k$ upper bound is quite crummy: $n^k = 2^{k \log n} = 2^{\alpha n \log n}$.
This is a useless upper bound because we already know a much better upper bound of $2^n$. (For a reference to this estimate of $V(n, \alpha n)$, check Problem 9.42 in Concrete Mathematics. In many common cases, one is however content with a less precise form, such as $2^{n H(\alpha)+o(n)}$.)
There are, of course, more things that one can ask: generalization to the $q$-ary hypercube, intermediate values of $k$ (e.g., $k = O(\log n)$), values of $k$ close to $n/2$ (e.g., $\frac{n}{2} - c \sqrt{n}$) and so on. Each of these is a fruitful direction of study, but I cannot touch upon any of them here.
EDIT: The precise estimate is taken from Mike's comment. (Thanks, Mike!)
Comment: I was about to post this as an answer, but it's so close to yours that I'll leave it as a comment: Problem 9.42 in *Concrete Mathematics* has a slightly more precise expression for $V(n,\alpha n): 2^{n H(\alpha) - \frac{1}{2}\log_2 n + O(1)}$.  There's an outline of their derivation in the answer section of the book.
Comment: Thank you for such an informative answer -- I was just about to ask for $k = \alpha n$ ;-)
Comment: @Mike I will edit my answer (sometime later) to include this reference. Hope it's ok with you! :-) Thanks.
Comment: Certainly.  I think it's fairly common practice to incorporate others' comments into our answers if we find them sufficiently helpful.
Answer: Let $k$ be fixed. Then, in the "big Oh" sense, the bound is tight.
For example, let $\epsilon$ be a very small positive number.
It is easy to verify that
$$\lim_{n \to \infty} \frac{n^{k-\epsilon}}{\binom{n}{k}}=0.$$
So we cannot replace $n^{k}$ by $n^{k-\epsilon}$.  We cannot even replace $n^k$ by something that grows almost as fast as $n^k$, such as $n^k/(\log(\log n))$.
So for fixed $k$, we will not find a "cheaper" upper bound in the "big Oh" sense.  Of course, we can improve the implicit constant, by dividing by $k!$ (the terms $\binom{n}{i}$ with $i<k$ make negligible relative contribution when $n$ is large).
Comment: great point; i would up-vote if i could; thank you


Maximization of $\infty$-norm with $2$-norm constraint

Question: Suppose we have a matrix $\mathbf B \in \mathbb R^{n\times n}$.  Is there an analytical solution to the following problem?
\begin{equation}
\begin{aligned}
&\max_{\mathbf x \in \mathbb R^n} && \|\mathbf B\mathbf x\|_{\infty} \\
&\ \ \text{s.t.} && \|\mathbf x\|_2\leq 1
\end{aligned}
\end{equation}
Answer: I had a follow-up thought... By definition, $||\mathbf B\mathbf x||_\infty = \max_i \{ |\mathbf b_i^\text{T} \mathbf x|\}$, where $\mathbf b_i^\text{T}$ is the $i$th row of the matrix $\mathbf B$.  Then, if $||\mathbf x||_2 \leq 1$, we have
\begin{equation}
\begin{aligned}
||\mathbf B\mathbf x||_\infty &= \max_i \{ |\mathbf b_i^\text{T} \mathbf x|\} \\
&\leq \max_i \{ ||\mathbf b_i ||_2 ||\mathbf x||_2 \} \\
&\leq \max_i \{ ||\mathbf b_i ||_2  \}.
\end{aligned}
\end{equation}
Thus, $\max_i \{ ||\mathbf b_i ||_2  \}$ is an upper bound on the optimal value of the problem.
Let $j \equiv \arg \max_i \{ ||\mathbf b_i ||_2  \}$, and let $\mathbf y \equiv \mathbf b_j/||\mathbf b_j||_2$.  Then, $\mathbf y$ is feasible for the optimization problem, because $||\mathbf y||_2 = 1$, and
\begin{equation}
\begin{aligned}
||\mathbf B\mathbf y||_\infty &= \max_i \{|\mathbf b_i^\text{T} \mathbf y|\} \\
&\geq |\mathbf b_j^{\text T}\mathbf y| \\
& = ||\mathbf b_j||_2 \\
&= \max_i \{ ||\mathbf b_i ||_2  \}.
\end{aligned}
\end{equation}
It follows that $||\mathbf B\mathbf y||_\infty = \max_i \{ ||\mathbf b_i ||_2  \}$.  Thus, $\max_i \{ ||\mathbf b_i ||_2  \}$ is the optimal value of the optimization problem, with $\mathbf y =\mathbf b_j/||\mathbf b_j||_2$ as the optimal solution.
Answer: The objective is a convex function, so the maximum will occur at some point $x^\star$ on the sphere $\|x\|_2 = 1$.   Let $m = \|B x^\star\|_\infty$,
with $(B x^\star)_i = m$ for $i \in S_+$, $-m$ for $i \in S_-$, and $|(B x^\star)_i| < m$ for all other $i$.
If $y \perp x^\star$, then we must have $(B y)_i = 0$ for $i \in S_+ \cup S_-$,
otherwise we could increase $\|B x\|_\infty$ by moving slightly from $x^\star$ in the direction $y$ or $-y$.  But this implies that row $i$ of $B$ is a scalar multiple of $(x^\star)^T$.  Thus the only candidates for $x^\star$ are the transposes of the normalized rows of $B$.  The maximum is
obtained for the row $R$ of $B$ that maximizes $\|R\|_\infty/\|R\|_2$.


Paginating a members page

Question: Could somebody help me paginate this script? I'm not very good with it and I kept messing up.
I already tried checking the num_rows and then making it validate and stuff but it failed like 10 times :( After 2 days I've given up. I want to start from scratch.
<?php

$link = mysqli_connect("localhost", "lunar_lunar", "", "lunar_users");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
$result = mysqli_query($link, "SELECT * FROM users ORDER BY username");
while($row = mysqli_fetch_assoc($result)) {
    $id=$row['id'];
    $username=$row['username'];
    $email=$row['email'];
    $firstname=$row['firstname'];
    $lastname=$row['lastname'];
    $motto=$row['motto'];
    $bio=$row['bio'];
$result4 = mysqli_query($link, "SELECT * FROM photo where id='$id'");
$row4 = mysqli_fetch_assoc($result4);
$image=$row4['filename'];
$src = (empty($image)) ? "upload/your-photo.jpg" : "site_images/$id/$image";
$motto = (empty($motto)) ? "No motto" : $motto;
$bio = (empty($bio)) ? "No biography" : $bio;
echo "

".$username."

  ".$bio."

".$motto."

";
       }
?>

Comment: so where's your pagination?
Comment: I took it out of the script and said I want to start over. I want somebody to point me in the right direction on doing this.
Comment: If pure PHP it's tough, have you tried using [Datatables](http://datatables.net/)?
Answer: You'll have to make some adjustments to incorporate your sql query, but here's a blank navbar (hopefully this will point you in the "right direction" as requested):
<?php

print create_navbar(400, 10);

function create_navbar($count, $items_per_page = 50) {
  // Creates a navigation bar
  $current_page = $_SERVER["PHP_SELF"];
  // You could always pull this next line out and re-add $start_number as the first argument in
  // the function...
  $start_number = ($_GET && isset($_GET['start']) && !empty($_GET['start'])) ? (int) $_GET['start'] : 0;
  if (($start_number < 0) || (! is_numeric($start_number))) {
    $start_number = 0;
  }
  $navbar = "";
  $prev_navbar = "";
  $next_navbar = "";
  if ($count > $items_per_page) {
    $nav_count = 0;
    $page_count = 1;
    $nav_passed = false;
    while ($nav_count < $count) {
    // Are we at the current page position?
      if (($start_number <= $nav_count) && ($nav_passed != true)) {
        $navbar .= '[' . $page_count . '] ';
        $nav_passed = true;
        // Do we need a "prev" button?
        if ($start_number != 0) {
          $prevnumber = $nav_count - $items_per_page;
          if ($prevnumber < 1) {
            $prevnumber = 0;
          }
          $prev_navbar = ' <<Prev - ';
        }
        $nextnumber = $items_per_page + $nav_count;
        // Do we need a "next" button?
        if ($nextnumber < $count) {
          $next_navbar = ' - Next>>
';
        }
      }
      else {
        // Print normally.
        $navbar .= '[' . $page_count . '] ';
      }
      $nav_count += $items_per_page;
      $page_count++;
    }
    $navbar = $prev_navbar . $navbar . $next_navbar;
    return $navbar;
  }
}
?>

Paginating a members page


Some contradiction in an open problem

Question: Recently, I'm considerring an open problem from the paper by Ofelia T.Alas and others':On the extent of star countable spaces. It easily can be downloaded by google. The open Problem is this:

Suppose that $X$ is a (strongly) monotonically monolithic star countable space. Must $X$ be Lindelof?

Somebody has proved it is true that if $X$ is a strongly monotonically monolithic star countable space, then $X$ must be Lindelof. (see the paper: A note on the extent of two subclasses of star countable spaces by the author Zuoming Yu).
In the morning, I met acrossly an example See Dan Ma's discussion non-normal product space: there exist a separable metric space $X$ and a Lindelöf space $Y$, such that $X \times Y$ is not a Lindelöf space.
On one hand because every point-countable base space is strongly monotonically monolithic, according to Tkachuk, "monolithic spaces and D-spaces revisited", Proposition 2.5, then $X$ of course is strongly monotonically monolithic. And $Y$ is also have point-countable base, so $Y$ is also
strongly monotonically monolithic. Moreover, $X\times Y$ is strongly monotonically monolithic (see the same paper of Tkachuk: theorem 2.10).
On the other hand, The space $X$ and the space $Y$ are two star countable, clearly, their product is also star countable.
Now the contradiction comes, such space $X \times Y$ is not normal, and hence is not Lindelof, which contradicts with the result of Zuoming Yu.
I don't know what's wrong. Could somebody help? Thanks for any help.

Added: The product of 2 star-countable spaces is star-countable:
Suppose $X$ and $Y$ are both star countable. Given any open cover of basic nbhd $U\times V=\{u\times v: u \in U; v\in V\}$ of $X\times Y$. Clearly, $U$ is an open cover of $X$ and $V$ is an open cover of $Y$, therefore, there exist countable subsets $C\subset X$ and $D\subset Y$ which satisfies that $St(C,U)=X$ and $St(D,U)=Y$. Now we can get an countable subset: $C\times D$ of $X\times Y$ and easily see that $St(C\times D, U\times V)=X\times Y$.
Comment: Matveev's [_A Survey on Star Covering Properties_](http://at.yorku.ca/v/a/a/a/19.htm) appears to give some references to products of star-countable (what he calls star-Lindelof) spaces which are not star-countable (Examples 19, 20, and 21 on p.80).
Comment: @ArthurFischer: Thanks for the information!
Comment: Not all covers are of the form you describe. In general we can reduce to covers of the form $\{U_i \times V_i : i \in I \}$, and the $U_i$ firm a cover of $X$, the $V_i$ of $Y$, but the not every combination $U_i \times V_j$ is in that cover, but this is what you suggest with $U \times V = \{ u \times v: u \in U, v \in V \}$.
Comment: The link to Zuoming Yu's paper at `springerlink.com` is broken, but it can be found at [doi:10.2478/s11533-012-0030-x](https://doi.org/10.2478/s11533-012-0030-x).
Answer: Do you have a reference or proof for "the product of 2 star-countable spaces is star-countable"? I don't see that. And your $X$ and $Y$ (the Michael line but based on a Bernstein set.. as $Y$) could be a counterexample.
As to your (added) proof: pick $(x,y) \in X \times Y$. We get independent $U$ and $V$ for the   different coordinates, but we can not yet say that the product of these is in the originla cover of product sets!
Comment: However it is Lindelof, and hence it must be star countable. $Y$ is some different from the Michael line. Michael line is not Lindelof.
Comment: I don't see a proof?? You just claim it.
Comment: You are right. I am a little "of course".

Some contradiction in an open problem


How to embed existing website in my Drupal 8 site?

Question: I have a site I created with Drupal 8, lets say http://falzon.xyz/.
Elsewhere, I have a site created with Jekyll, a bunch of static pages linked to each other visible http://www.elina-noe.eu/).
I'd like to "embed" the static site as a "subsite" of falzon.xyz, i.e. accessible as http://falzon.xyz/elina-noe/, by 'simply' putting all its files in a subfolder of the D8 site.
How can I do that?
Comment: Using @GiorgosK's advice, it's working! Anybody having the base URL (http://falzon.xyz/elina-noe/) is able to navigate this 'subsite'. How can I limit the access to the users of my 'root' site (i.e. http://falzon.xyz/)?
Answer: Creating a subfolder inside your docroot folder such as docroot/elina-noe should suffice.
Put all the subsite files into this folder and if there is a index.html you can access your subsite just by visiting the subfolder http://falzon.xyz/elina-noe/
Comment: @GiorgosK Finally, I put one .htaccess file in elina-noe subfolder with `RewriteCond "%{HTTP_REFERER}" !^http://www\.falzon\.xyz [NC]`and `RewriteRule ^.*$ - [F]`in it and it seems to work.
Comment: The caveat here is your web server is configured to use `index.html` when a dir path is requested. Many default web server configs do this, but just FYI in case you see otherwise.
Comment: @GiorgosK I come back on this (old) topic to ask a new question: is there a way to restrict the access to this "subsite" to the actual users allowed to the main Drupal site?
Comment: I don't think I have the answer to it and I am not sure it is such an easy question, perhaps create a new question for that @gbmapo


How to display more than 1 chart on the same page when using Google Chart Tools?

Question: I have created a simple page (in Views) listing a series of nodes. Each node has an (EVA) field showing a pie chart.
When I use the Google Chart Tools module as a Views field format, the page shows only 1 chart (to the most recent node).
It seems that I need to do something so that multiple charts can show in the same page. But what am I missing here?
Any help would be much appreciated.
Answer: I finally managed to achieve this using the dev version of the Views Dataviz module. Of course there are other solutions but these require coding so i guess this is the easiest way of showing multiple charts in the same page.
Answer: I've been trying to place multiple charts on the same page at some point, through code. Just by mixing html code with the returned code from the charts worked for me.
In case this is of any help, which might not be the case here since you use views.
You can just create your custom module and on one of the functions have something like the example found in the Google Charts tools module, where you can get a chart with draw_chart($settings).
chart_a = draw_chart($settings_a);
$chart_b = draw_chart($settings_b);
return '
'.$chart_a.'
'.'
'.$chart_b.'
';

Answer: To answer the question about "But what am I missing here?": it seems that what might be the answer is what is described in the issue about Can't display more than 1 chart at the same page. More specifically, this is what is included in comment #2 in it:

Turn on Aggregation in Views, (Advance section of views). Then there will be a setting on the field called "Aggregation Settings". And then in the field "Aggregation Type" select "Group Results Together". Watch your overrides.

Give it a try and see what happens ...


How does one see connectedness of a covering space?

Question: Something can be proven about the loops (or their possible lifts?) in the base space which will ensure connectivity of the cover?
Comment: ... you are assuming the base is connected, yes?
Answer: a) If the base space  $X$  is connected, nothing  will ensure the (non)connectivity of a covering:
The identity $1_X:X\to X$ is always a  connected covering and given a connected covering  $Y\to X$ the obvious covering $Y\sqcup Y\to X$ is a non connected  covering of $X$.
b) If you start with a disconnected space $X$ every surjective covering of $X$ will be disconnected.
However some definitions of "covering space" (the right ones in my opinion) allow non surjective covering spaces .
In that context the inclusion $X_i\hookrightarrow X$ of a connected component $X_i$ of $X$  is a connected covering space of $X$.
Comment: I have heard stuff like, if you can find a loop in the base space such that it lifts to a loop in a non-trivial way then the cover is connected.  Can be stated in some homology terms? Can you explain?
Comment: The stuff you heard is false because you can always add to  any connected covering space,  satisfying whatever condition on loops you want, a disjoint copy of itself and get a non connected covering. Homology has nothing to do with the problem.
Comment: Elencwaig Okay - something along these lines - that for a 2-covering there has to be a homomorphism from he first homology group to $\mathbb{Z}_2$ which satisfies some properties? Like that there should be at least one loop in the base space which is mapped to $-1$ by this? (for n-lifts I think something is required about the map from the first homology group to $\mathbb{Z}_n$ to be surjective?)


Como fazer dado especifico do array nao se repetir no *ngFor ou no array

Question: Tenho um array com os dados do usuario, que são os dados que ele bateu ponto naquela data que ta no array.
array:
[
0:{CCT: "150403",CODIGO_EVENTO: "012",COLABORADOR: "FULANO",DATA: "20190110",DESCRICAO: "ATRASO AUTORIZADO", FILIAL: "01",MATRICULA: "000457", QUANTC: 0.24},
1:{CCT: "150403",CODIGO_EVENTO: "013",COLABORADOR: "FULANO",DATA: "20190110",DESCRICAO: "ATRASO ", FILIAL: "01",MATRICULA: "000457", QUANTC: 0.24},
2:{CCT: "150403",CODIGO_EVENTO: "013",COLABORADOR: "FULANO",DATA: "20190110",DESCRICAO: "ATRASO AUTORIZADO", FILIAL: "01",MATRICULA: "000457", QUANTC: 0.30},
3:{CCT: "150403",CODIGO_EVENTO: "012",COLABORADOR: "FULANO",DATA: "20190111",DESCRICAO: "ATRASO AUTORIZADO", FILIAL: "01",MATRICULA: "000457", QUANTC: 0.31},
4:{CCT: "150403",CODIGO_EVENTO: "012",COLABORADOR: "FULANO",DATA: "20190111",DESCRICAO: "HORA EXTRA AUT. 50% ", FILIAL: "01",MATRICULA: "000457", QUANTC: 0.20}
]

Aí no HTML fica assim:

DATA: {{formatDate(data)}}

QTDE. CALCULADA: {{QUANTC}}

DESCRIÇÃO: {{descri}}

aí aparece:
DATA: 20190110
dados...
DATA: 20190110
dados...

só que eu preciso que mostre só uma vez a data, assim:
DATA: 20190110
    reg1
    reg2
    reg3
DATA: 20190111
    reg1
    reg2

e assim por diante, sem ficar repetindo a data.
Tem alguma forma de fazer isso pelo proprio *ngFor ou mexendo no array? Estou perdida nesse problema
Comment: Olá. Você terá que agrupar os registros baseado nas datas. Aqui tem um artigo explicando como fazer isso com um PIPE: https://www.competa.com/blog/custom-groupby-pipe-angular-4/
Answer: Consegui responder com o comentario do Gesiel Rosa.
link: https://www.competa.com/blog/custom-groupby-pipe-angular-4/
groupByPipe.ts:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
    transform(collection: Array<any>, property: string): Array<any> {
        // prevents the application from breaking if the array of objects doesn't exist yet
        if(!collection) {
            return null;
        }

        const groupedCollection = collection.reduce((previous, current)=> {
            if(!previous[current[property]]) {
                previous[current[property]] = [current];
            } else {
                previous[current[property]].push(current);
            }

            return previous;
        }, {});

        // this will return an array of objects, each object containing a group of objects
        return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
    }
}

HTML:

 {{formatDate(dados.key)}}

  {{dados.DESCRICAO}}

 {{dados.TPMARCA}}

 {{dados.QUANTC}}

module.ts
import { GroupByPipe } from './groupByPipe';

const ROUTES: Routes = [
    {path: '', component: ManagerBhDetailComponent }
]

@NgModule({
    declarations: [ManagerBhDetailComponent, GroupByPipe],
    imports: [RouterModule.forChild(ROUTES), SharedModule],
  providers: [

  ]
})

export class ManagerBhDetailModule{}


Adicionar vários itens em uma única session

Question: Dessa forma eu adiciono um item na session
 var item = new FornecedorTipoFrete()
            {

                TipoFreteId = id,
                TipoFrete = new TipoFrete() { Descricao = tipofrete },
                FornecedorId = (fornecedorID)
            };

            HttpContext.Session.SetString("TipoFreteId", id.ToString());

Porém esse processo pode ocorrer várias vezes.
 O usuário pode adicionar vários TiposFretes, então poderia ser um ou vários, como posso adicionar todos e depois ler essa sessão com vários itens.
EDIT
Eu tentei fazendo desta forma:
Adicionei esta linha no controller
IList<string> listaFrete = new List<string>();
e então para salvar na Session fiz desta forma:
listaFrete.Add(id.ToString());
            HttpContext.Session.SetObject("Lista", listaFrete);

Porém ele sempre pega o último, não vai salvando na lista. Sempre fica apenas um item, sempre o último.
Comment: não pode adicionar um array ou list de "TipoFreteId"?
Comment: A forma hoje aceita apenas um TipoFreteId, o usuário vai poder incluir vários, e só vai salvar quando for realizado o submit, se não for ocorrer problemas, pode.
Comment: então acho que pode resolver.. só vai dar um trabalho a mais tratar a lista, e talvez remover /adicionar itens dependendo se tiver alterações
Comment: Eu preciso adicionar, adiciono via Json, e pra excluir também excluiria via Json.
Comment: se tiver muita manutenção talvez a session não seja o melhor lugar, quem sabe um banco seja melhor
Comment: Nesse caso, é pq o usuário vai incluir para salvar, ele pode incluir e decidir não terminar o cadastro. Teria alguma forma melhor de se fazer?
Comment: A session pode perder se ele fechar o navegador ou pode expirar.. uma possibilidade seria salvar numa tabela "temporaria" ou se se tiver no seu ambiente um banco noSQL por exemplo.. são opções
Comment: No caso acho que seria melhor a sessão mesmo.
Comment: Usa cookies se este é o caso. Mas ainda se preferir usar session sugiro gravar uma lista ou array do item na session
Comment: @RicardoPontual editei a pergunta.
Answer: Primeiro é o seu método que você praticamente já utiliza para adicionar a session, e segudo o método que usará para buscar um item na lista armazenada na Session.

void AddItemSession()
{
  var item = new FornecedorTipoFrete()
  {

    TipoFreteId = id,
    TipoFrete = new TipoFrete() { Descricao = tipofrete },
    FornecedorId = (fornecedorID)
  };

  List<FornecedorTipoFrete> lstFornecedorTipoFrete = new List<FornecedorTipoFrete>();

  if (Session["ListaTipoFrete"] != null)
        lstFornecedorTipoFrete = (List<FornecedorTipoFrete>)Session["ListaTipoFrete"];

  lstFornecedorTipoFrete.Add(item);
  Session["ListaTipoFrete"] = lstFornecedorTipoFrete;
}

FornecedorTipoFrente ReturnFornecedorTipoFrete(string tipoFreteId)
{
  if (Session["ListaTipoFrete"] == null)
    return null;

  return (Session["ListaTipoFrete"] as List<FornecedorTipoFrete>).FirstOrDefault(c=> c.TipoFreteId == tipoFreteId);
}
Comment: coloquei com `static` e deu certo, obrigado.
Comment: Eu não tenho a opção de `Session`, utilizo asp.net core, ele informa que não existe Session no contexto atual
Comment: Usa o HttpContext.Session.SetString() então e seta um json usando JsonConvert.SerializeObject(value). A lógica é a mesma.
Comment: Eu tentei adicionando essa linha no controller `IList listaFrete = new List();` e então fazendo assim pra pegar o valor. `listaFrete.Add(id.ToString());
                HttpContext.Session.SetObject("Lista", listaFrete);` mas ele sempre substituiu, e não inclui na lista.
Comment: Entao seta sempre em uma string só separando os ids por "," (Vírgula). Ex: "1,17,9". sempre buscando a informação e dando .Split(',') obtendo como retorno um array de ids.
Comment: Editei a pergunta, de como estou tentando fazer.
Comment: Ele está ficando sempre o último não é porque sempre cria uma nova lista? IList listaFrete = new List();
Comment: Eu não criei dentro da função. Será que mesmo assim está sendo executado?
Comment: Eu apenas declarei assim `IList listaFrete;` e dentro da função faço dessa forma: `if (listaFrete == null)
                {
                    listaFrete = new List();
                }` porém ele sempre está retornando `null`


Shouldn't the trace of an orthogonal projector be in $\mathbb{N}$?

Question: I was asked to find orthogonal projection matrix in some basis, that projects onto $W: x_1+2x_2-3x_3=0$ and give the vectors for this basis I am using.
So first I noticed that $\{(-2,1,0), (3,0,1)\}$ spans $W$ then I used Gram-Schmidt process to find $\{u_1, u_2\}$ orthogonal basis. So I took
$$u_1=(-2,1,0)
\\u_2=(3,0,1)-\langle (-2,1,0),(3,0,1)\rangle\frac{(-2,1,0)}{\langle(-2,1,0),(-2,1,0)\rangle}=\left(\frac{3}{5},\frac{6}{5},1\right)$$
finaly I formed matrix $A=(u_1|u_2)$ and found Projection matrix $P=A(A^TA)^{-1}A^T$ I got something pretty ugly so I assume I made a mistake somwhere in reasoning or calculation. The questions are:

Was it reasoning or calculation?
Should I get a symmetric matrix (since basis is orthogonal)?
Should the trace be in $\mathbb{Z}$ since eigenvalues of a projections are from the set $\{0,1,-1\}$ and projections are diagonalizable (I remember something like this, but even if they are not always diagonalizable in Jordan form they also have eigenvalues on the diagonal so my claim still holds)?

And extra question: In fact the most interesting for me.
Here Matrix of orthogonal projection User Evan Delanoy solved similar problem using normal vector to instead of basis of $W$. The way he solved it is more appealing to me than my solution, however he could not specify with respect to what basis is the matrix he obtained. Does anyone know how could I specify what basis I am working on while solving the problem using his way?
Comment: @ArnaudD. yeah right now they are. I misquoted the exercise, I've just corrected it.
Comment: How can a projection have $-1$ as an eigenvalue? It satisfies $P^2=P$, so the minimal polynomial can't have $\lambda+1$ as a factor.
Comment: $\operatorname{tr}P = \dim W$. The restriction of $P$ to $W$ is the identity map and $P$'s rank is of course equal to $\dim W$. The matrix in Delanoy's answer is clearly expressed relative to the same basis that was used to define $W$, which he assumes to be orthonormal since he interprets the defining equation as an inner product.
Answer: Original answer
A basis for $W$ is obtained by solving $x_1=-x_2+x_3$:
$$
\left\{\,
  \begin{bmatrix} -1 \\ 1 \\ 0 \end{bmatrix},
  \begin{bmatrix} 1 \\ 0 \\ 1 \end{bmatrix}
\,\right\}
$$
I don't know how you got those two vectors, which aren't in $W$ to begin with.
Applying Gram-Schmidt, we get the normalized vectors
$$
  u_1=\begin{bmatrix} -1/\sqrt{2} \\ 1/\sqrt{2} \\ 0 \end{bmatrix},\qquad
  u_2=\begin{bmatrix} 1\sqrt{6} \\ 1/\sqrt{6} \\ 2/\sqrt{6} \end{bmatrix}
$$
If $Q=[u_1\ u_2]$, then
$$
QQ^T=\begin{bmatrix}
2/3 & -1/3 & 1/6 \\
-1/3 & 2/3 & 1/6 \\
1/6 & 1/6 & 2/3
\end{bmatrix}
$$
is the projection matrix. The trace is indeed $2$, because the eigenvalues are $0$ (single) and $1$ (double).
After edit to the question
The basis you found is correct; now normalize the two vectors and consider
$$
Q=\begin{bmatrix}
-2/\sqrt{5} & 3/\sqrt{70}\\
1/\sqrt{5} & 6/\sqrt{70}\\
0 & 5/\sqrt{70}
\end{bmatrix}
$$
and compute the projection matrix ax $QQ^T$; you should get
$$
\begin{bmatrix}
13/14 & -1/7 & 3/14\\
-1/7 &  5/7 &  3/7\\
 3/14 &  3/7 & 5/14
\end{bmatrix}
$$
whose trace is $2$.
Comment: sorry there was a mistake I already edited the post
Comment: I misquoted the exercise the W equation is different. I've just corrected it now and should be alright.
Comment: @Kacper The basis you find is good. Just do the computation in the easier way shown in my answer.


Nonparametric test suggestion for distribution comparison

Question: I am not sure if this is appropriate place to ask, but I appreciate any help on this issue. I want to compare the distributions of the results of the two experiments played by the same group of people. I would like to get an advice about what are the possible non-parametric tests for this purpose. Many thanks in advance.
Answer: The standard non-parametric test for comparing two distributions is the Kolmogorov-Smirnov test. This is a well understood test which is frequently taught, and so it may well be a good place to start. The basic idea is to look at the ECDFs of the two samples, and if they are far apart, the distributions are probably different. Distance in the KS test is measured as the furthest apart the two ECDFs are.
Then there are improvements on the KS test. The Cramer-Von Mises test is more powerful in general. It consists of summing up all the distance between the ECDFs everywhere there are points in the joint sample. Anderson-Darling does the same thing but then also adjusts the differences based on our knowledge of the variance of ECDFs.
I've stayed within very agnostic tests which claim no information whatsoever about the two distributions. There are whole classes of tests which work well when you know something more -- like that the distributions are continuous, or so forth. That said -- you can do very well with a working two-sample Anderson-Darling test.
One last note -- Kolmogorov-Smirnov is notoriously underpowered in finite samples, so do try to run a version of it which is based on permutation/randomization rather than the asymtotic approximation.


TraMineR seqdplot : order states by total frequency

Question: I would like to display a state distribution plot (obtained with seqdplot) ordered by state frequency.
For instance, with the mvad dataset :
library(TraMineR)
data(mvad)

mvad.labels <- c("employment", "further education", "higher education", "joblessness", "school", "training")
mvad.scode <- c("EM", "FE", "HE", "JL", "SC", "TR")
mvad.seq <- seqdef(mvad, 17:86, states = mvad.scode,labels = mvad.labels, xtstep = 6)

seqdplot(mvad.seq, border = NA, title = "State distribution plot")

I'd like to have the states plotted in order of their global frequency (with the most frequent state at the bottom of the plot and least frequent at the top for instance, or in any specified order for that matter).
Is that possible with the seqdplot function ?
Or do you guys know other alternatives ? (ggplot2..)
Answer: The TraMineR plots retain the state order of the state sequence object. To change the order, you have to define a new state sequence object with the wanted order of the states.
You get the state frequencies with seqmeant. Once you have defined the order, you impose it by explicitly defining the alphabet in seqdef. You have also to sort accordingly short and long labels, as well as state colors.
Here is how you can do that
## Get state freq with seqmeant
mt <- seqmeant(mvad.seq)
## order of frequencies
ord <- order(mt, decreasing = TRUE)

## Sorted alphabet
alph.s <- rownames(mt)[ord]
## we need also to sort accordingly labels and colors
mvad.labels.s <- mvad.labels[ord]
mvad.scode.s <- mvad.scode[ord]
cpal.s <- cpal(mvad.seq)[ord]

## Define sequence object with sorted states
mvad.seq.s <- seqdef(mvad.seq, alphabet = alph.s, states = mvad.scode.s,
                   labels = mvad.labels.s, cpal = cpal.s, xtstep = 6)

seqdplot(mvad.seq.s, border = NA, main = "State distribution plot")


Selecionar elementos que contenham um atributo "data" em particular

Question: Na página existem diversos elementos com atributos data. Para evitar andar a adicionar classes de CSS ao elementos, tornado o código da página mais denso, gostaria de selecionar elementos pelo nome do atributo data.
Exemplo

A ideia é aplicar determinada ação via jQuery aos elementos que contenham um atributo data-my-target.
Pergunta
Como posso selecionar elementos pelo nome do atributo data?
Answer: Você pode usar o seguinte:
div[data-my-target]

Isso busca elementos que contenham esse atributo. Também é possível filtrar o atributo pelo valor. Por exemplo:
div[data-my-target="John"]

O = casa elementos cujo atributo seja a string passada. Se quiser casar parcialmente o valor "John" (por exemplo, se o valor for "John Paul"), use *=:
div[data-my-target*="John"]

Porém, acredito que a performance de usar uma classe seja melhor (não testei).
Referência útil (em inglês): MDN CSS Attribute selectors
Answer: A resposta do bfavareto é a correcta.
Só para documentar mais 2 exemplos e diferenças de performance.
1 :
$('div[data-my-target]');  // mais compatível com browsers antigos

2 :
$('div').filter('[data-my-target]');
// ou:
arrayEmCache.filter('[data-my-target]'); // no caso de já haver uma array de elementos em cache

3 :
document.querySelectorAll('[data-my-target]'); // mais rápida mas não compatível com IE<8

Answer: Modelo mais atual:
var target = $("#suaDIV").data("my-target");

Comment: como posso selecionar o valor do atributo ?


Trying to replace a button's link, work on every browser except Safari?

Question: I am trying to replace the url and do some action. If my site www.mysite.com/hello had hello, then I will replace a button link. The url detection function works, because I place alert(), it popup. so the attr replace give me the problem. It works on every browser except Safari, how can I fix this?

if(window.location.href.indexOf("hello") > -1) {
    $('#ladies_fashion').attr("href", "http://myshite.com/replace/");
}/*slim-tee*/
Fashion Inspiration
Answer: I figure it out by myself. I have to add the http://


Qual a diferença entre [a] e "a" em Haskhell?

Question: Isto está correto??
[a] = uma lista com 1 só elemento
a = uma lista com quantos elementos quiser
Ps: tenho algumas duvidas porque algumas funcoes sao do tipo [a]->a
mas leem tambem , por exemplo [2,3]
Answer: Não está correto, quando uma função qualquer diz func :: [a] -> a está nos informando que ela pega como parâmetro uma lista qualquer (de qualquer tamanho) e retorna um elemento do mesmo tipo da lista. A variável a pode ser de qualquer tipo, se a lista for de números então o resultado será um número.
Vejamos um exemplo:
O escopo da função head em Haskell (:t head):
head :: [a] -> a
head [1,2,3] -- 1
head [a,b,c] -- a

Essa função retorna o primeiro elemento de uma lista (cabeça da lista). Pode ser uma lista de qualquer tamanho, basta testar para verificar.
Já a função tail, que retorna a cauda da lista, tem um escopo ligeiramente diferente:
tail :: [a] -> [a]
tail [1,2,3] -- [2,3]
tail [a,b,c] -- [b,c]

Visto que a cauda pode ter 0 ou mais elementos.
Se fosse uma função do tipo Equals seria algo assim:
eq :: a -> a -> Bool

Ou seja, recebe dois parâmetros do mesmo tipo e retorna true/false.
Para aprender mais sobre Haskell recomendo este livro online.
Comment: Muito obrigado :p , ja entendi
Comment: Poderia marcar a resposta como aceita? Embaixo das setas ^ v tem um OK verde.


Number of different arrangements of the letters A,B,C,D,E,F

Question: How many different arrangements are there of the letters A,B,C,D,E,F in which
(a) A and B are next to each other and C and D are also next to each other?
(b) E is not the last letter?
(c) A is before B?
(d) A is before B and B is before C?
(e) A is before B and C is before D?
I got these answers for (a) and (b) but I'm not sure how to approach (c),(d) and (e).
(a) $4! \times 2! \times 2!$
(b)$6!-5!$
Comment: @Swapnil: C and D are also adjacent; a) and ) and b) are ok.
Comment: @leonbloy Sorry, I took part A as two separate parts. Thanks for pointing that out. Comment deleted.
Comment: @Swapnil Sometimes it's helpful to leave comments like that.. =)
Comment: @Delvacode How, when it was plain wrong?
Comment: @Swapnil Maybe not in this case. Haha.. I felt that one could see other approaches to the problem and see how those approaches could possibly go wrong. Not always of course, sometimes.
Answer: c) Take the set of all arrangements. One half has $A$ before $B$, the other half has $B$ before $A$
d) What fraction of all arrangements have $A$, $B$, and $C$ in this order?
e) Same idea as d)
Comment: So the answer for (c) is $6!/2$ right?
Comment: Right. For c)  you will need to divide by something else...
Comment: You mean for part d?
Comment: I'm still not sure for (d). AEFBDC is also a valid combination. So I can't see ABC as single block. Any hints?
Comment: ABCDEF ACBDEF BACDEF BCADEF CABDEF CBADEF
Comment: Still not sure, sorry. Can explain? Thanks!


How can I preserve fixed width display while hiding/showing span elements

Question: I am working with some code from BioJS of which I'd like to extend the functionality. A BioJS object forms a sequence display by creating a separate span element for each letter and creating a break after x number of letters as such (simplified):
`   var j=1;
    for (var i=1; i <= a.length; i++) {

        if( i % opt.numCols == 0) {
            str += '' + a[i-1] + '';

            str += '
';

            j = 1;

        } else {
            str += '' + a[i-1];
            str += ( j % opt.numColsForSpace == 0)? ' ' : '';
            str += (opt.spaceBetweenChars)? ' ' : '';
            str += '';
            j++;
        }
    }`

This is nice for the built-in functionality of adding highlights to specific coordinates, which just uses jQuery to find the appropriate span and change the css. I've tried to take a similar approach with hiding elements by changing them to display:none, but unfortunately this leaves the line breaks behind, and thus big holes in the text. See a picture here:
Showing/Hiding
I'd like to know if there is another way I could create a similar display that would allow me to retain the fixed-width output after hiding the elements. Ideally I would still be able to use the highlight function, but I could also re-code that as well to work in a different way.
Comment: It's unclear what you're issue is, but `display:none` will hide an element, and also cause the layout to reflow as though it never existed. `visibility:hidden` will visually hide an element, but leave its space in the document flow.
Comment: I'm already using display:none. However, the line breaks are preserved because they're inserted by the javascript. If I remove these line breaks, then I'm left with a series of span elements which overflow the parent div on the right side. Perhaps there's some CSS setting or a different type of element that can be used instead.
Answer: I found the source of the problem, which was that the javascript from BioJS was adding an inline style of whitespace: pre that was preventing the span elements from wrapping within the container. It was causing the containing element to only break on line breaks.


Is there a way to use Cells.Address as part of a range ("A1:Cells.Address") for an input to a function?

Question: I cannot seem to make this work. I have a line that finds the address of the last cell in the table of data.
r = Range(Range("A2"), Range("A2").End(xlDown)).Rows.Count
Range("A1", Cells(r + 1, 5).Address(RowAbsolute:=False, ColumnAbsolute:=False)).Select

Then using this information, later on I need to input the range A1:E35 where the E35 corresponds to:
Cells(r + 1, 5).Address(RowAbsolute:=False, ColumnAbsolute:=False))

Using Ron de Bruin's CopyRangeToJPG function,
Function CopyRangeToJPG(NameWorksheet As String, RangeAddress As String) As String
'Ron de Bruin, 25-10-2019
Dim PictureRange As Range

With ActiveWorkbook
    On Error Resume Next
    .Worksheets(NameWorksheet).Activate
    Set PictureRange = .Worksheets(NameWorksheet).Range(RangeAddress)

    If PictureRange Is Nothing Then
        MsgBox "Sorry this is not a correct range"
        On Error GoTo 0
        Exit Function
    End If

It doesn't get past the validation check. What should the RangeAddress field be? I need this to be dynamic since it won't always be A1:E35 in this case. I would have thought that the following might have worked but I guess this isn't the right way.
CopyRangeToJPG("Sheet2", "A1:(Cells(r + 1, 5).Address(RowAbsolute:=False, ColumnAbsolute:=False))").

Thanks
Answer: CopyRangeToJPG("Sheet2", _
               "A1:" & Cells(r + 1, 5).Address(RowAbsolute:=False, ColumnAbsolute:=False))


How do I create a table with a two primary keys of two foreign keys?

Question: create table Machine
(
 Machine_ID int primary key,
 Machine_Name varchar(30)
 Machine_Title varchar(30)
)
create table Part
(
 Part_ID int primary key,
 Part_Name varchar(30),
 Part_Description varchar(30)
)

//How do I make this table below?
create table Machine-Part
(
  Machine_ID int foreign key references (Machine.Machine_ID),
  Part_ID int foreign key references (Part.Part_ID)
  Factory_Note varchar(30);
)

Mysql complains there is a problem with syntax?
Desired Result: have Table 'Machine-Part' use 'Machine_ID' & 'Part_ID' as both primary keys (which are both foreign keys).
Answer: If you declare the constraint separately (table level), it makes more sense
create table Machine-Part
(
  Machine_ID int NOT NULL ,
  Part_ID int NOT NULL ,
  Factory_Note varchar(30) NULL,

  PRIMARY KEY (Machine_ID, Part_ID),
  UNIQUE INDEX (Part_ID, Machine_ID),
  foreign key (Machine_ID) references (Machine.Machine_ID),
  foreign key (Part_ID) references (Part.Part_ID)
)

Link tables almost always need a reverse index too
Answer: Something like this -
CREATE TABLE Machine(
  Machine_ID INT PRIMARY KEY,
  Machine_Name VARCHAR(30),
  Machine_Title VARCHAR(30)
)
ENGINE = INNODB;

CREATE TABLE Part(
  Part_ID INT PRIMARY KEY,
  Part_Name VARCHAR(30),
  Part_Description VARCHAR(30)
)
ENGINE = INNODB;

create table `Machine-Part`(
  Machine_ID int,
  Part_ID int,
  Factory_Note varchar(30),
  CONSTRAINT fk_Machine_ID FOREIGN KEY (Machine_ID) REFERENCES Machine(Machine_ID),
  CONSTRAINT fk_Part_ID FOREIGN KEY (Part_ID) REFERENCES Part(Part_ID)
)
ENGINE = INNODB;

You can find all information on these pages:

FOREIGN KEY Constraints
CREATE TABLE Syntax
Comment: what does ENGINE = INNODB; do/mean?
Comment: Currently only INNODB engine supports foreign keys. I specified this value explicitly.
Comment: Use these queries to view default storage engine for MySQL server: SHOW VARIABLES LIKE 'default_storage_engine'; or SHOW VARIABLES LIKE 'table_type';