text:
Q: How to return unique index value of multiple items selected in listbox I have a listbox in VB.NET that allows users to select multiple categories. I need to put these categories into a database and need the index value from the listbox of the categories as the database works off IDs. SelectedItems (with an s) does not work in the net application.
I have tried the following code:
For Each category As ListItem In CategoryListBox.Items
    If category.Selected Then
        Dim courseCategory As New CourseCategory
        courseCategory.CourseID = course.ID
        courseCategory.CategoryID = CategoryListBox.SelectedIndex
        Using courseCategoryEntities As New Eng_NWDTrainingWebsiteEntities
            courseCategoryEntities.CourseCategories.Add(courseCategory)
            courseCategoryEntities.SaveChanges()
        End Using
    End If
Next

When iterating through the loop the code that is:
courseCategory.CategoryID = CategoryListBox.SelectedIndex

works correctly the first time around.
On the second iteration of the loop, it goes to the next selected item however returns the index for the first selected value. How do I return the values of the other indexes selected?

A: It depends on what ID you need to pass to your database. If it is truly the index of the ListItem in the ListBox, then you would use:
courseCategory.CategoryID = CategoryListBox.Items.IndexOf(category);

That may not be the best approach however. Maybe the order of the ListItems changes, messing up your indexes. You probably want to store the actual CategoryID on each ListItem. The Value property works well for that. You set the column you want as the DataValueField like so:
<asp:ListBox ID="CategoryListBox" runat="server"
    DataValueField="CategoryID "></asp:ListBox>

So as you are looping through each ListItem in the ListBox and checking if it is selected, just use it's Value property.
For Each category As ListItem In CategoryListBox.Items
    If category.Selected Then
        Dim courseCategory As New CourseCategory
        courseCategory.CourseID = course.ID
        courseCategory.CategoryID = category.Value;
        Using courseCategoryEntities As New Eng_NWDTrainingWebsiteEntities
            courseCategoryEntities.CourseCategories.Add(courseCategory)
            courseCategoryEntities.SaveChanges()
        End Using
    End If
Next

A: Fixed the code by deselecting the item in the listbox after it was successfully saved.
   End Using
category.Selected = False
End If

This solved my problem.


text:
Q: Reading bluetooth low energy data from a custom app to a ble dongle(csr8510) I am having a problem connecting and sending Bluetooth low energy data from a custom built app I created in android studio to a BLE dongle. The app I created has 4 virtual push buttons and every time I press one these buttons its send a 4bit number letting the Bluetooth dongle( peripheral) know. The problem is that when I use "hcidump" in Linux I cant read anything. which I figured is how I can view this data.
One of the problems I believe I am having is that I need to advertise some command that lets the app know what information I want. If this is the case I'm unsure what to send, to notify the app that I want to read the states of the virtual pushbuttons.
I am able to bring up the ble dongle in Linux and the app is able to discovery the ble dongle as well they will connect for a short period then disconnect cause as I said the app is waiting for some kind of characteristic/service or so is what I believe?

A: I am also looking forward for something similar application where Android application sends some button command to Linux Application via Bluetooth and nearest similar example I get from github.
Here is Python application code for Linux side this is using Bluetooth RFCOMM communication.
And here is Android application main activity code you have to make sure to put your Bluetooth name in android application and also make sure UUID is same on both python and android application.
Give it a try and then you can modify both your application for multiple buttons.
Make sure you have paired your bluetooth with android first before you run application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple Angular route change animation not working on mobile? I have a basic slide-in slide-out animation for each route on enter and leave within my AngularJS app.
The animations work perfectly on desktop, although bug out on mobile. They do seem to work within the dev tools emulator though.
I have tracked it down to having something to do with the views position not being set correctly with the absolute position. Seems as if when a new view is loaded, they both exist within the page, hence making the pages width twice and large until the old view is unloaded and removed. I then tried a position relative on the parent container, although no luck.
WORKING DEMO

A: Use overflow: hidden for the container of your views, in the case of your plnkr, it's the <body>


text:
Q: Fatal Error in tm (text mining) document term matrix creation tm is throwing an error when I try to create a document term matrix
library(tm)
data(crude)

#control parameters
dtm.control <- list(
    tolower           = TRUE,
    removePunctuation = TRUE,
    removeNumbers     = TRUE,
    stopWords         = stopwords("english"),
    stemming          = TRUE, # false for sentiment
    wordLengths       = c(3, "inf"))

dtm <- DocumentTermMatrix(corp, control = dtm.control)

Error:

Error in simple_triplet_matrix(i = i, j = j, v = as.numeric(v), nrow = length(allTerms),  :
    'i, j, v' different lengths
  In addition: Warning messages:
  1: In mclapply(unname(content(x)), termFreq, control) :
    all scheduled cores encountered errors in user code
  2: In simple_triplet_matrix(i = i, j = j, v = as.numeric(v), nrow = length(allTerms),  :
    NAs introduced by coercion

What am I doing wrong?
Also:
I am using these tutorials:

*

*Basic Text Mining

*Text Mining in R
Are there better/ more recent walkthroughs?

A: You might consider a few changes in your code, especially removeStopWords and creating a corpus.  Below worked for me:
library(tm)
data("crude")

#control parameters
dtm.control <- list(
  tolower           = TRUE,
  removePunctuation = TRUE,
  removeNumbers     = TRUE,
  removestopWords   = TRUE,
  stemming          = TRUE, # false for sentiment
  wordLengths       = c(3, "inf"))

corp <- Corpus(VectorSource(crude))

dtm <- DocumentTermMatrix(corp, control = dtm.control)

> inspect(dtm)
<<DocumentTermMatrix (documents: 20, terms: 848)>>
Non-/sparse entries: 1877/15083
Sparsity           : 89%
Maximal term length: 16
Weighting          : term frequency (tf)


text:
Q: Google Cloud SQL VM refusing connection I have been stuck trying to figure out why my Cloud SQL VM is refusing my connection from my machine (whom ip address I have added as a subnet). I cann SSH into the VM but i cannot access the VM from a browser to make SQLs. I have scoured the internet for days trying to find a fix but i cannot seem to get pass this point. My apache listens to port 80. Also Id like to add that I have been connecting to my Mysql db for months through php and making sqls so I do not believe the problem is with apache. However if it is please point me to where i should be looking.

A: It sounds like you have MySQL running on a GCE VM, not an actual CloudSQL instance (that is a different service from GCE).  Is that right?
If so, then if you are trying to connect from your local machine directly to the mysql instance, you are probably getting blocked by the firewall.  Go to the networks tab (under Compute Engine) on the cloud console and see what firewall rules you have enabled.  You might need to add one for 3306 or whatever port you are using.


text:
Q: Java loop and shifting To cut a long story short, I'm trying to generate Huffman codes from a canonical Huffman list.  Essentially, the following two loops should run, and generate a binary string.  The code is:
for (int i = 1; i <= 17; i++) {
        for (int j = 0; j < input.length; j++) {
            if (input[j] == i) {
                result.put(allocateCode(i, j), j); //update a hashmap
                huffCode += (1 << (17 - i)); //Update the huffman code
            }
        }

    }

Essentially the code should look for all codes with a length of 1 and generate a Huffman code for each.  So for example, lengths of 1 should go (in order): 0, 1.  And lengths of three will go 100, 101, 110.
The allocateCode function simply returns a string that shows the result, the first run produces this:
Huffman code for code 2 is: 0 (0) length was: 1
Huffman code for code 6 is: 10 (2) length was: 2
Huffman code for code 0 is: 1100 (12) length was: 4
Huffman code for code 3 is: 1101 (13) length was: 4
Huffman code for code 4 is: 1110 (14) length was: 4
Huffman code for code 7 is: 11110 (30) length was: 5
Huffman code for code 1 is: 111110 (62) length was: 6
Huffman code for code 5 is: 111111 (63) length was: 6

This is correct, and the right Huffman codes have been generated.  However, running it on a second array of lengths produces this:
Huffman code for code 1 is: 0 (0) length was: 1
Huffman code for code 4 is: 1 (1) length was: 1
Huffman code for code 8 is: 100 (4) length was: 3
Huffman code for code 9 is: 100 (4) length was: 3
Huffman code for code 13 is: 101 (5) length was: 3
Huffman code for code 16 is: 1011000 (88) length was: 7
Huffman code for code 10 is: 10110001 (177) length was: 8
Huffman code for code 2 is: 101100011 (355) length was: 9
Huffman code for code 3 is: 101100011 (355) length was: 9
Huffman code for code 0 is: 1011001000 (712) length was: 10
Huffman code for code 5 is: 1011001000 (712) length was: 10
Huffman code for code 6 is: 1011001001 (713) length was: 10
Huffman code for code 7 is: 10110010011 (1427) length was: 11
Huffman code for code 14 is: 10110010011 (1427) length was: 11
Huffman code for code 17 is: 10110010100 (1428) length was: 11
Huffman code for code 19 is: 10110010100 (1428) length was: 11
Huffman code for code 18 is: 101100101010000 (22864) length was: 15

As you can see, the same code is generated multiple times, examples are code 8 & 9, and codes 2 & 3.
I think my problem lies within the nested loops, however I can't figure out why it works perfectly for one run, and fails on another.
I might just be missing something obvious, but I can't see it for looking.
Any advice would be greatly appreciated.
Thanks
UPDATE
After going back through my code, it seems that I was actually making a small mistake when reading in the data in the first place, hence I was getting incorrect Huffman codes!!

A: The first two codes in your second example both have length one, which leaves no other possible codes after those first two.  All prefix patterns have been used up.
Your code should keep a count of the available remaining codes to detect an erroneous input.  Simply decrement the count for each code, and double the count every time you move up to the next length one more than the current length.  (Make sure you double even if there are no codes of that length, e.g. if you move from codes of length 3 to codes of length 5, double the count for codes of length 4 even though there are none.)  Start the count at two for length one codes.
If that count ever goes negative, you have an error and you can stop right there.  It is not possible to assign codes to that set of lengths.
If at the end of the process the count is not zero, then you have an incomplete code.  That may or may not be an error depending on your application.  It means that the code is not optimal, and fewer bits could have been used to code those symbols.


text:
Q: WordNetLemmatizer: Different handling of wn.ADJ and wn.ADJ_SAT? I need to lemmatize text using nltk. In order to do this, I apply nltk.pos_tag to each sentence and then convert the resulting Penn Treebank tags (http://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html) to WordNet tags. I need to do this because WordNetLemmatizer.lemmatize() expects both the word and its correct pos_tag as arguments, otherwise it will just assume everything is a verb.
I just found that there are five different tags defined in WordNet:

*

*wn.VERB

*wn.ADV

*wn.NOUN

*wn.ADJ

*wn.ADJ_SAT

However, every example I found on the internet just ignores wn.ADJ_SAT when converting Treebank tags to WordNet tags. They are all just mapping Penn tags to WordNet tags like this:

*

*If Penn tag starts with J: convert to wn.ADJ

*If Penn tag starts with V: convert to wn.VERB

*If Penn tag starts with N: convert to wn.NOUN

*If Penn tag starts with R: convert to wn.ADV

So wn.ADJ_SAT is never used.
My question now is if there are cases where the lemmatizer returns a different result for ADJ_SAT than for ADJ. What are examples for words that are satellite adjectives (ADJ_SAT) and no normal adjectives (ADJ)?

A: The WordNetLemmatizer in NLTK does not differentiate satellite adjectives from normal adjectives.
nltk.stem.WordNetLemmatizer.lemmatize is uses "WordNet's built-in morphy function. Returns the input word unchanged if it cannot be found in WordNet."
In WordNet, a satellite adjective--more broadly referred to as a satellite synset--is more of a semantic label used elsewhere in WordNet than a special part-of-speech in nltk.
From the wordnet glossary:

Satellite Synset:
  Synset in an adjective cluster representing a concept that is similar in meaning to the concept represented by its head synset .

User tripleee points out in this question the following:

adjectives are subcategorized into 'head' and 'satellite' synsets within an adjective clutser

Also, the nltk documentation for nltk.stem.WordNetLemmatizer.lemmatize assumes the default part of speech to be a noun instead of a verb, unless otherwise specified.


text:
Q: Как нажать на элемент страницы Chromium - Delphi Пишу программу Delphi с использованием Chromium. Уже реализовывал нажатие на кнопки и ввод данных в поля. Но на один элемент не удаётся нажать программно никак. У элемента нет id и компонентов button нет. Вот код кнопки:
<div class="css-8yenei">
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" class="normal css-pw2wcz">
        <path fill="currentColor" d="M3 4h18v3H3z"></path>
        <path fill-rule="evenodd" clip-rule="evenodd" d="M15 2H9v2h6V2zm4 5H5v14h14V7zm-8.5 2H8v9h2.5V9zm3 0H16v9h-2.5V9z" fill="currentColor"></path>
    </svg>
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" class="active css-ixmls4">
        <path fill="currentColor" d="M3 4h18v3H3z"></path>
        <path fill-rule="evenodd" clip-rule="evenodd" d="M15 2H9v2h6V2zm4 5H5v14h14V7zm-8.5 2H8v9h2.5V9zm3 0H16v9h-2.5V9z" fill="currentColor"></path>
    </svg>
</div>

Это код вызова клика на этот элемент
procedure TFormRobot.Button1Click(Sender: TObject);
var CodeStr:ustring;
begin
    //CodeStr := 'document.getElementById("cancel-order").click();'
    //CodeStr := 'document.querySelector("css-8yenei").click();'
    CodeStr := 'document.getElementsByClassName("css-8yenei")[0].click();';
    Chromium1.Browser.MainFrame.ExecuteJavaScript(CodeStr, '', 0);
end;

Никак не жимается.


text:
Q: iPhone Keeps Asking for Other User iTunes Store Creds - Which Content is Causing this? I just reset my phone and restored a backup from iCloud.  Now, I keep getting prompted to sign-in to my wife's iTunes account.  No matter how many times I click cancel, it keeps popping up; over and over and over.  Which content is causing this?
I don't see any app's that didn't get restored so I'm thinking it is not an app.  Maybe it is music?  She was part of the Family Sharing and I think I downloaded some of her songs previously.  She left iOS and went onto Android and has no clue what her password is.
I've reviewed similar threads and I can't find an answer to which content is causing this.
iOS version 10.3.3, 5SE
Update
This problem happens when I'm on Wifi or when I try to sync via iTunes.  When I'm on Wifi it won't stop prompting for the credentials.  When I try to sync via iTunes it won't stop prompting and the sync won't complete.
I've deleted all music via Setting -> Music -> Downloaded Music -> Delete All Songs.
When I go into the Music app I see about 20 songs that don't have a download icon on them.  I suspect those are the problem.  I've tried deleting them from the library but they won't go away.

A: I think you're on the right track.  If you checked every app and know for sure that it was downloaded from your iCloud account, then it's probably the music.
You mentioned you used Family Sharing.  If you're the organizer, you can remove her from the group or disband the family group.  According to Apple:

When you leave Family Sharing, your Apple ID is removed from the family group, and you stop sharing music, movies, TV shows, books, and apps with any remaining family members. In addition, any photos, calendars, and reminders shared by the family group will be removed from your devices. If you chose to share your location, you'll stop sharing your location with other family members, and your devices will be removed from the family Find My iPhone device list.
Any content that your family shared with you isn't automatically removed from your device. You can purchase it again or remove it to free up space on your device. If you downloaded an app from a family member's purchase history and made In-App Purchases, you'll need to purchase the app yourself to access your In-App Purchases.
Any DRM-protected music, movies, TV shows, books, or apps that you previously downloaded from other family member's collections will no longer be usable, and other family members won't be able to use content downloaded from your collection.

The family organizer can remove anyone over 13 from the family group at any time.
Go to Settings > [your name] > Family Sharing, tap the name of the family member you want to remove, then tap Remove. If you're using iOS 10.2 or earlier, go to Settings > iCloud > Family.

Can the family organizer leave or disband a family group?
Yes. If the family organizer stops Family Sharing, it removes all family members from the family group at once.
Go to Settings > [your name] > Family Sharing, tap your name as the organizer, then tap Stop Family Sharing.  If you're using iOS 10.2 or earlier, go to Settings > iCloud > Family.


text:
Q: Binding values while or for loop In my intuition, if I bind a value in the loop, I believed UI updates automatically.
This is my test code:
binding
private string _client1 {get; set;}
public string client1
{
    get => _client1;
    set
    {
        _client1 = value;
        RaisePropertyChanged(nameof(client1));
    }
}

Function
public async void UpdateUI()
{
    await Task.Run(() =>
    {
        DispatcherHelper.CheckBeginInvokeOnUI(async () =>
        {
            for (int i = 0; i < 10; i++)
            {
                _client1 = i.ToString();
                RaisePropertyChanged(_client1);

                await Task.Delay(200);
            }
        });
    }).ConfigureAwait(false);
}

Result
0 is shown and not changed in UI.
Expected Result
0 1 2 ... 10
I want the value to be changed continuously in UI. What is the problem with this code?

A: If the control is bound to the client1 property, then that is what you should be changing, not the backing field _client1:
client1 = i.ToString();

And since the setter for client1 already calls RaisePropertyChanged, you don't need this line inside your loop:
RaisePropertyChanged(_client1);


text:
Q: Server Manager DirectAdmin Error: "There are no IPs on DirectAdmin server" - Boxbilling I am not sure if this question is related to topics of Stackoverflow. I tried to post it on BoxBilling Forum but that does not seem to work. This is why I am asking here.
By the way, I am using BoxBilling for my web hosting business that uses Directadmin.
Everything is fine just a problem, it does not create any Reseller or user accounts. Whenever I try to activate an order from Boxbilling admin, I get the following error:

Server Manager DirectAdmin Error: "There are no IPs on DirectAdmin
  server"

I am using the following extension:
http://github.com/boxbilling/extensions/blob/master/bb-library/Server/Manager/Directadmin.php
I see the extension was last updated years ago!
Is there anyone who is using Directadmin with BoxBilling ? Or do you have a working extension for Boxbilling and Directadmin ? Or can you help me anyhow to get it working ?
Your help is very much appreciated.
Thanks

A: I encountered this same issue today when setting up my Boxbilling with DirectAdmin, its an extremely simple fix.
All you need to do is go to the Boxbilling admin page, then go to "Configuration" on the left side menu, then "Hosting plans and servers" under that, then under the servers list, go to yours and press the pencil icon, then select "Yes" for "Use secure connection", then save the server settings. It should work perfectly now!
(I know this is an old post, but I feel that someone else may google this issue in the future and I want the solution to be available!)


text:
Q: How to display record in hierarchy single sql table I have one table PrimaryActivity in there table some columns present such as.

*

*PrimaryActivityID INT

*ActivityName NVARCHAR(250)
SELECT [PrimaryActivityID],[ActivityName] FROM [dbo].[PrimaryActivity] (NOLOCK)

--Current Query result
PrimaryActivityID ActivityName
----------------- -----------------------------
3                administrator
122              administrator_icon
126              administrator_icon_delete
124              administrator_icon_insert
123              administrator_icon_search
125              administrator_icon_update
121              home
131              home_clearcache
130              home_dashboard
2                mainmenu
105              mainmenu_acsession
109              mainmenu_acsession_delete
107              mainmenu_acsession_insert
106              mainmenu_acsession_search
108              mainmenu_acsession_update
1132             mainmenu_callfortopics

Expected result

PrimaryActivityID ParentActivity    ActivityName
---------------------------------------------------------------
3                 administrator      NULL
122                                  administrator_icon
126                                  administrator_icon_delete
124                                  administrator_icon_insert
123                                  administrator_icon_search
125                                  administrator_icon_update
121              home                NULL
131                                  home_clearcache
130                                  home_dashboard
2                mainmenu            NULL
105                                  mainmenu_acsession
105              mainmenu_acsession  NULL
109                                  mainmenu_acsession_delete
107                                  mainmenu_acsession_insert
106                                  mainmenu_acsession_search
108                                  mainmenu_acsession_update
1132                                 mainmenu_callfortopics

Can some help me to get the exact output?
I'll already prepare some examples but not able to get the exact output below the query.
SELECT [PrimaryActivityID]
       ,NULL [ParentActivity]
       ,[ActivityName]
FROM [dbo].[UM_PrimaryActivity] (NOLOCK)
UNION
SELECT [PrimaryActivityID]
       ,[ActivityName] [ParentActivity]
      ,[ActivityName]
FROM [dbo].[UM_PrimaryActivity] (NOLOCK)

A: Here is a way to get this done...
with data
  as (
select PrimaryActivityId
       ,case when charindex('_',ActivityName) <> 0 then
                  substring(ActivityName,1,charindex('_',ActivityName)-1)
             else ActivityName
         end as ParentActivity
       ,case when charindex('_',ActivityName) <> 0 then ActivityName end as Activityname
 from dbo.PrimaryActivity
      )
select PrimaryActivityId
      ,case when ActivityName is null then ParentActivity end as ParentActivity_mod
      ,ActivityName as ActivityName_mod
  from data

+-------------------+--------------------+---------------------------+
| PrimaryActivityId | ParentActivity_mod |     ActivityName_mod      |
+-------------------+--------------------+---------------------------+
|                 3 | administrator      |                           |
|               122 |                    | administrator_icon        |
|               126 |                    | administrator_icon_delete |
|               124 |                    | administrator_icon_insert |
|               123 |                    | administrator_icon_search |
|               125 |                    | administrator_icon_update |
|               121 | home               |                           |
|               131 |                    | home_clearcache           |
|               130 |                    | home_dashboard            |
|                 2 | mainmenu           |                           |
|               105 |                    | mainmenu_acsession        |
|               109 |                    | mainmenu_acsession_delete |
|               107 |                    | mainmenu_acsession_insert |
|               106 |                    | mainmenu_acsession_search |
|               108 |                    | mainmenu_acsession_update |
|              1132 |                    | mainmenu_callfortopics    |
+-------------------+--------------------+---------------------------+

https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=a5891b9bec680fd9332505bd20b7bfb3

A: AS an example :
SELECT PrimaryActivityID, ActivityName,
       LEFT(ActivityName, COALESCE(NULLIF(CHARINDEX('_', ActivityName), 0), LEN(ActivityName)+1)-1) AS LEADER,
       RIGHT(ActivityName, LEN(ActivityName) - CHARINDEX('_', ActivityName)) AS LAGER
FROM PrimaryActivity

Will do the job and you can use it recursively...
And with a recursive query :
WITH
T AS
(
SELECT PrimaryActivityID, ActivityName, 1 AS STEP,
       LEFT(ActivityName, COALESCE(NULLIF(CHARINDEX('_', ActivityName), 0), LEN(ActivityName)+1)-1) AS LEADER,
       RIGHT(ActivityName, LEN(ActivityName) - NULLIF(CHARINDEX('_', ActivityName), 0)) AS LAGER
FROM   PrimaryActivity
UNION  ALL
SELECT PrimaryActivityID, ActivityName, STEP + 1,
       LEFT(LAGER, COALESCE(NULLIF(CHARINDEX('_', LAGER), 0), LEN(LAGER)+1)-1) AS LEADER,
       RIGHT(LAGER, LEN(LAGER) - NULLIF(CHARINDEX('_', LAGER), 0)) AS LAGER
FROM   T
WHERE  LAGER IS NOT NULL
)
SELECT PrimaryActivityID, ActivityName, STEP, LEADER AS part, SPACE(STEP - 1) + LEADER AS part_hierarchy
FROM   T
ORDER  BY ActivityName, STEP


text:
Q: Injecting parent classes from other libraries with Guice I am trying to use Guice (4.0) to bootstrap dependencies for my executable from inside my main driver class (perhaps this is a Guice anti-pattern?):
// Groovy pseudo-code
// This Buzz class is located in a 3rd party lib that I don't have access to
class Buzz {
    int foobaz
    Whistlefeather whistlefeather

    // other stuff, include constructor, setters and getters
}

class MyApp extends Buzz {
    @Inject
    DatabaseClient dbClient

    @Inject
    FizzRestClient fizzClient

    static void main(String[] args) {
        MyApp app = Guice.createInjector(new MyAppModule()).getInstance(MyApp)
        app.run()
    }

    private void run() {
        // Do your thing, little app!
    }
}

class MyAppModule extends AbstractModule {
    @Override
    void configure() {
        bind(DatabaseClient).to(DefaultDatabaseClient)
        bind(FizzRestClient).to(DefaultFizzRestClient)

        // But how do I configure MyApp's 'foobaz' and 'whistlefeather'
        // properties? Again, I don't have access to the code, so I
        // can't annotate them with @Inject, @Named, etc.
    }
}

So my problem is that MyApp actually extends a base object living in a 3rd party (OSS) JAR. This base class (Buzz) is not set up for use with Javax Inject or Guice. But I would like Guice to be able to configure its foobaz and whistlefeather properties.... any ideas?

A: You can create and inject any bean with a @Provide method in a Guice module. For example:
@Provides
MyApp externalService(DatabaseClient dbClient, Whistlefeather wf) {
    MyApp app = new MyApp();
    app.setDatabaseCLient(dbClient);
    app.setWhitlefeature(wf);
    return app;
}

See @Provides


text:
Q: What is the maximum number of edits that can be rejected per day? While trying to submit an edit, I received the following error message:

Too many of your edits were rejected, try again in 7 days.

And now I'm wondering, how many of my edit suggestions can be rejected per day before this happens?

A: I don't see the official number of edit suggestions that you can have rejected before you are temporarily banned from submitting any more posted anywhere. But I suspect that's entirely by design.
Telling people the number would make it easier for them to exploit the system by suggesting only n–1 bad edits, where n is the number of rejected edits that trips the temporary ban.
As the FAQ on suggested edits explains:

What about abuse?
There are strict limits enforced. If a user (anonymous or registered) submits many rejected edits they will be automatically banned from suggesting edits. The fixed size queue also helps protect us from abuse.

This is because suggested edits, especially on Stack Overflow, are very expensive. They require the time, energy, and effort of at least two trusted community members. If you continually submit bad edits that don't improve the site in any way, you've just wasted everyone's time. We don't appreciate that, and we'd prefer that you take some time out and watch how others edit. And then, once you get the hang of things, we're perfectly willing to give you another chance. But please don't push your luck...
Remember, you also get a reputation boost (+2) for edits that are approved, so it's in your best interest to make quality edits, as well. If in doubt about the validity of an edit, then just don't submit it. Move along and edit something else, or stop to answer a question. Let one of the other users take care of that edit.
If you'd really like to learn how to make better edits (and thus get more of them accepted), I very much recommend watching how other users (say, those with 5000+ reputation) have edited posts in the past. Any time you come across a post that's been edited, there will be a link to its revision history at the bottom, in the center. Click on it and see what changes were made. Look at what tags were used, and try to figure out why. Look at the formatting changes that were made. Look at the grammar & spelling edits. Try to imagine what edits you would have made to a post, and compare those to the ones others have made. How do they match up? Do you know why they made the changes they did? Do you see how they improve the overall quality of the post? And already, you'll be improving as an editor.
And remember that there are plenty of simple and obvious edits to suggest while you're learning and improving. Tons of people forget to format their code in their questions. Lots more people don't capitalize things properly in their question titles. Some people forget to include a tag for the programming language that they're using. Simple edits like that are almost always going to be approved.


text:
Q: Insert slot into a component instance I have Component1
<template>
<div> <slot></slot> </div>
</template

<script>
export default {}
</script>

and Component2
<template>
<div> {{ someProp }} </div>
</template

<script>
export default {
    props: {
        someProp: String
    }
}
</script>

and I want to create those components dynamically with
var Comp1 = Vue.extend(Component1)
var Comp2 = Vue.extend(Component2)

var instance1 = new Comp1()
var instance2 = new Comp2()

How do I set/insert the Slot for instance1 as instance2? My instinct was to do this
instance1.$slots.default = instance2

But in the DOM, the slot in instance1 shows up as undefined.

A: is it compulsory that you use <slot>?
Vue comes with a directive called <component> for loading components dinamically, you can pass your component using the is special attribute.
<template>
<div>
    <component :is="dynamicComponent">
</div>
</template>

The script:
export default {
  computed: {
    dynamicComponent(){
      return Comp2 //the class, not the instance
    }
  }
}


text:
Q: How to pass an array in to an array to PHP a server? I have the next multiple field in my html view:
<select multiple="multiple" name="search[cpuUsage[]]"
    id="search_cpu_usage"
    class="form-control">
    {% for statu in status %}
        <option value="{{ statu }}">{{ statu }}</option>
    {% endfor %}
</select>

i need all possible values that user select, and i try save in search[cpuUsage[]], but this not work because php only get the last selected value. if i use only cpuUsage[] without search[] works perfectly.
For send to server i use jquery.serialice.
any idea of how do for work search[cpuUsage[]]

A: You need to have name attribute as an array
So change
name="search[cpuUsage[]]"

To:-
name="search[cpuUsage][]" //or name="search[]" or name="cpuUsage[]"

And you are good to go


text:
Q: Why are some blank cells seen as zero in Excel? We have Excel documents that date back years. Some of the document sheets haven't been touched for over 15+ years (or to the very early versions of Excel). They've had a new sheet added each year - using the same formatting as last year.
As we've begun to import the whole 40+ sheets into a database we've noticed that sometimes blank cells from years 1993 and before act strangley. Although they are blank they have imported as zeros in our database.
Is there an explination for this?
I'm not sure if someone has gone back a limited amount of years and updated some formats, but it seems strange that this happens in most of the doucments we have.
And how do we go about making blanks cells "really blank", without having to do this cell by cell? (...I don't think my soul could manage it!)
Thanks Michael.

A: In some versions of Microsoft Excel, if a cell is formatted as a "number" cell, it will fill in 0 when it is blank and has been active (the cursor has been on it, etc).
You might try selecting all the cells and re-formatting them to text or no formatting by right-clicking.


text:
Q: RequestDispatcher - when is a response committed? I'm writing some basic code as I learn about the RequestDispatcher. I understand that when rd.forward() is called, control (and response handling) is forwarded to the resource named in the path - in this case another servlet. But why doesn't this code throw an IllegalStateException (not that I want one) due to the out.write() statements earlier in the code?
I guess what I'm really asking is, how or when would these out.write() statements be committed?
Thanks,
Jeff
public class Dispatcher extends HttpServlet{
  public void doGet(HttpServletRequest request, HttpServletResponse response)
           throws IOException, ServletException{

    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    out.write("In Dispatcher\n");

    String modeParam = request.getParameter("mode");
    String path = "/Receiver/pathInfo?fruit=orange";
    RequestDispatcher rd = request.getRequestDispatcher(path);
    if(rd == null){
        out.write("Request Dispatcher is null. Please check path.");
    }
        if(modeParam.equals("forward")){
            out.write("forwarding...\n");
            rd.forward(request, response);
        }
        else if(modeParam.equals("include")){
            out.write("including...\n");
            rd.include(request, response);
        }
    out.flush();
    out.close();
}

}

A: Because you haven't called flush.
Everything will be cleared out before forwarding if you haven't flushed. Otherwise, you'll get an excpetion you expect.
As in the docs:

For a RequestDispatcher obtained via getRequestDispatcher(), the
  ServletRequest object has its path elements and parameters adjusted to
  match the path of the target resource.
forward should be called before the response has been committed to the
  client (before response body output has been flushed). If the response
  already has been committed, this method throws an
  IllegalStateException. Uncommitted output in the response buffer is
  automatically cleared before the forward.

A: Read the docs.

Calling flush() on the PrintWriter commits the response.

Now, as per your curiosity that why there is no IllegalStateException thrown. It's simply because PrintWriter.flush() doesn't throw this or any checked exception. And, we know that the response was not committed when rd.forward() is invoked, since flush() comes later in the method.

A: You did not make call to flush() before forward. So it does not shows any exception. If you write flush() before request is forwarded then it will throw exception.
When We call flush(), then all what was in buffer is sent to the browser and buffer is cleared.
In following scenario we will get exception.
response.getWriter().print('hello...');
response.getWriter().flush();
request.getRequestDispatcher("/index.").forward(request, response);


text:
Q: Embed PHP in Javascript I need to embed PHP into Javascript so that when the user selects Countries it would display the result from the query alphabatically and if he selects Numbers then list based on numbers in descending.
Having researched, I have applied this (echo concept into my code) but doesn't seem to work.
I have the following query written in PHP that output staffs' country of birth( no of staff born in number of countries) in ascending order:
$querytest = "select x , COUNT( * )  from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "'  AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) ASC ";

Then, I have a dropdown in HTML:
<form>
    Sort by:
    <select id="sortByDropdown" onchange="sortBy(this);">
      <option value="alphabatically">Countries</option>
      <option value="numbers">Number</option>
    </select>
</form>

Furthermore, I have a Javascript function sortBy()
function sortBy(){
    var sortByDrpdownDiv =  document.getElementById('sortByDropdown');

if (sortByDrpdownDiv[sortByDrpdownDiv.selectedIndex].value == 'numbers'){
    alert("yo in if statement");
    <?php $querytest = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "'  AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) DESC ";
    $result = mysql_query($querytest);

    while ($row = mysql_fetch_assoc($result)) {
            echo "";
            echo $row['x'];
            echo ":  ";
            echo $row['COUNT( * )'];
            echo "
";
        }?>
    document.getElementById('staffbirthplaces').innerHTML = <?php echo $row?>;
    }
}

First I am going only for Numbersbecause the same logic will apply to the Countries. Any help will be appreciated

A: So, i finally did it! Used switch instead of IF statement. Below is the code:
   function sortByAlphabetsOrNumbers(obj){

    var selectedValue = obj.options[obj.selectedIndex].value
switch(selectedValue)
{
    case "numberOfStaff":
        document.getElementById('sortBy').innerHTML =
        "<?php
            include 'connection.php';

            $staffNumbersDesc = "select x , COUNT( * )  from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "'  AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) DESC";
            $result = mysql_query($staffNumbersDesc);
            while ($row = mysql_fetch_assoc($result))
            {
                echo "";
                echo $row['x'];
                echo ":  ";
                echo $row['COUNT( * )'];
                echo "
";
                }
        ?>";
        document.getElementById('birthCountriesAlphabaticalOrder').style.display = "none";
        break;

    case "countries":
        document.getElementById('sortBy').innerHTML =
        "<?php
            include 'connection.php';

            $alphabaticalOrder = "select x , COUNT( * )  from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "'  AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x";
            $result = mysql_query($alphabaticalOrder);
            while ($row = mysql_fetch_assoc($result))
            {
                echo "";
                echo $row['x'];
                echo ":  ";
                echo $row['COUNT( * )'];
                echo "
";
                }
        ?>";
        document.getElementById('birthCountriesAlphabaticalOrder').style.display = "none";
        break;
}
};

Hope it helps someone


text:
Q: Fastest way to subset sub-elements of lists in R Say I have a list of lists where each sub-list is a move:
movies <- list(list("Jurassic Park", "Steven Spielberg", "Action"),
               list("Avatar", "James Cameron", "Action"),
               list("Schindler's List", "Steven Spielberg", "Biography")
           )

What is the best/fastest way (preferably without dependencies, but tidyverse would be fine) to subset that list based on the sub-list elements? That is, if director is always the second element in the sub-list, what's the fastest way to get a vector of the names of movies that Spielberg directed?
Hoping to do this across very large lists many times.
Thanks in advance!!

A: sapply(movies, `[[`, 2)
# [1] "Steven Spielberg" "James Cameron"    "Steven Spielberg"

Benchmark: this answer is the fastest.
bench::mark(purrr = map_chr(movies, pluck, 2),
            getElement = sapply(movies, getElement, 2),
            `[[` = sapply(movies, `[[`, 2))

  expression      min  median itr/s…¹ mem_a…² gc/se…³ n_itr  n_gc
1 purrr        21.7µs  28.2µs  31773.      0B    6.36  9998     2
2 getElement   16.6µs  18.6µs  45652.      0B    4.57  9999     1
3 [[           14.9µs  17.2µs  47417.      0B    4.74  9999     1

A: Dependency free and readable:
sapply(movies, getElement, 2)
# [1] "Steven Spielberg" "James Cameron"    "Steven Spielberg"

Fast but not readable and assumes each sublist is length 3:
unlist(movies)[-1L:(length(movies) * 3L-2L) %% 3L == 0L]

Playing with Rcpp (perhaps not optimal)
Rcpp::cppFunction('
  Rcpp::CharacterVector foo(Rcpp::List lst, int idx, int n) {
      idx--;
      Rcpp::CharacterVector res(n);
      for (int i = 0; i < n; i++) {
        Rcpp::List tmp = lst(i);
        res(i) = Rcpp::as<String>(tmp(idx));
      }
      return res;
  }
')

Benchmark with 100k sublists:
bench::mark(purrr = map_chr(movies, pluck, 2),
            getElement = sapply(movies, getElement, 2),
            `[[` = sapply(movies, `[[`, 2),
            unlist = unlist(movies)[-1L:(length(movies) * 3L-2L) %% 3L == 0L],
            Rcpp = foo(movies, 2L, length(movies))
  )

#   expression      min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time result          memory              time            gc
#   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl>   <bch:tm> <list>          <list>              <list>          <list>
# 1 purrr       234.6ms 236.78ms      4.15   781.3KB     13.8     3    10      723ms <chr [100,000]> <Rprofmem [42 × 3]> <bench_tm [3]>  <tibble>
# 2 getElement  73.06ms  77.53ms     12.8     3.29MB     14.6     7     8      548ms <chr [100,000]> <Rprofmem [5 × 3]>  <bench_tm [7]>  <tibble>
# 3 [[          28.09ms  30.43ms     27.1     3.29MB     10.2    16     6      590ms <chr [100,000]> <Rprofmem [5 × 3]>  <bench_tm [16]> <tibble>
# 4 unlist       7.81ms   8.16ms    105.      8.01MB     17.8    53     9      506ms <chr [100,000]> <Rprofmem [7 × 3]>  <bench_tm [53]> <tibble>
# 5 Rcpp        11.91ms  12.86ms     70.8   783.79KB     15.7    36     8      508ms <chr [100,000]> <Rprofmem [2 × 3]>  <bench_tm [36]> <tibble>

A small function out of the comment below movies that includes filtering:
return_movies <- function(list, title_position, comparison_position, comparison_string) {
  sapply(movies, getElement, title_position)[
        sapply(movies, getElement, comparison_position) == comparison_string
         ]
}

return_movies(movies, 1, 2, "Steven Spielberg")

[1] "Jurassic Park"    "Schindler's List"

A: library(purrr)

map_chr(movies, pluck, 2)
#> [1] "Steven Spielberg" "James Cameron"    "Steven Spielberg"

A: A vectorized base R approach that doesn't assume vector lengths inside the list:
bigmovies <- rep(movies, 1e4)

fsub1 <- function(x, i) unlist(x)[c(i, cumsum(lengths(x)[-length(x)]) + i)]
fsub2 <- function(x, i) sapply(x, `[[`, i)

microbenchmark::microbenchmark(unlist = fsub1(bigmovies, 2),
                               sapply = fsub2(bigmovies, 2),
                               check = "identical")
#> Unit: milliseconds
#>    expr    min      lq     mean  median      uq     max neval
#>  unlist 1.8197 1.86370 2.113037 1.90760 2.15050 11.7461   100
#>  sapply 7.5128 7.68515 8.309795 7.90885 9.01275 13.5639   100

A: You can try the following base R option
> (d <- do.call(cbind, movies))[1, colSums(d == "Steven Spielberg") > 0]
[[1]]
[1] "Jurassic Park"

[[2]]
[1] "Schindler's List"


text:
Q: How to loop through a specific category on single.php in Wordpress? I've created a custom page and it is set as my homepage, within this custom page I am pulling out the latest post from a specific category, I've also created a form of pagination which when clicked upon will take the user to single.php. My intention for the single.php is to have two custom loops.
Custom loop one
I want single.php to distinguish that it has came from the homepage and loop through all of the posts tagged with the same category as the one on the homepage.
Some of these posts will have to be tagged with more than one category, so the loop will have to know to ignore the other categories and just pay attention to the category in question. Does that make sense?
Custom loop two
If the user hasn't arrived from the homepage, single.php will just act as it normally does i.e, if the user comes from index.php (the blog) they will be taken to this second loop (blog post)
However I don't seem to be able to make the distinction between the two loops, I might be over complicating matters, as I've got a loop which wraps everything together and then I have a loop for my custom pagination.
Here is the code below to show you what I'm talking about
custompage.php (set to home) - This works just fine but I'll post it just incase anyone is able to tidy it up
<?php query_posts('cat=1'); ?>

<?php
$myPosts = new WP_Query();
$myPosts->query('showposts=1');

if (have_posts()) :
while ($myPosts->have_posts()) : $myPosts->the_post();
?>

<div id="post-<?php the_ID(); ?>" class="info">

<?php the_title(); ?>

           <?php query_posts('posts_per_page=1&offset=1'); the_post(); ?>

<a href="<?php the_permalink() ?>">Previous

            <?php wp_reset_query(); ?>

<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>

single.php - Currently broken
<?php if( in_category('1') ) { ?>

   <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <div id="post-<?php the_ID(); ?>" class="info">

<?php the_title(); ?>

<?php previous_post_link('%link', ' ', 'true', '1') ?>

<?php next_post_link('%link', ' ', 'true', '1'); ?>

    <?php endwhile; else: ?>
    <?php endif; ?>

<?php }else{ ?>

   <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
      <div <?php post_class() ?> id="post-<?php the_ID(); ?>">

<?php the_title(); ?>

            <?php the_content('
Read the rest of this entry »
'); ?>

   <?php comments_template(); ?>
   <?php endwhile; else: ?>

Sorry, no posts matched your criteria.

    <?php endif; ?>

<?php } ?>

The problem I seem to be running into is when a post has been tagged with two categories, wordpress doesn't seem to be able to make the distinction between the two categories and instead of carrying on to the next category it breaks and defaults to the second loop.

A: how about this?
HOMEPAGE
<?php
$myPosts = new WP_Query();
$myPosts->query('showposts=1&cat=1');

if (have_posts()) :
while ($myPosts->have_posts()) : $myPosts->the_post();
?>

<div id="post-<?php the_ID(); ?>" class="info">

<?php the_title(); ?>

           <?php query_posts('posts_per_page=1&offset=1'); the_post(); ?>

<a href="<?php the_permalink() ?>">Previous

           <?php wp_reset_query(); ?> <-- not sure if this will reset the overall query

<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>

the queryposts('cat=1') at the top of your query wont run with that category, the category would have to be set inside your custom query
$myPosts->query('showposts=1&cat=1');

the 2nd page (SINGLE.PHP) with 2 loops..
if the user is coming from the homepage to a single page you want to attach the current category to the query, without this wordpress (while on the singles page will default to loop through all posts)
so for the singles page would the below be any good?
<?php if( in_category('1') ) { ?>

   <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <div id="post-<?php the_ID(); ?>" class="info">

<?php the_title(); ?>

             <php global $post;
              $my_query = get_posts('numberposts=1&cat=1&offset=-1');
              foreach($my_query as $post) :
          setup_postdata($post);
          $link = get_post_meta($post->ID, 'site-url', true); ?>

                <a href="<php echo $link; ?>"><php the_title(); ?>

            <php endforeach; ?>
            <php global $post;
              $my_other_query = get_posts('numberposts=1&cat=1&offset=1');
              foreach($my_other_query as $post) :
          setup_postdata($post);
          $link = get_post_meta($post->ID, 'site-url', true); ?>

                <a href="<php echo $link; ?>"><php the_title(); ?>

            <php endforeach; ?>

    <?php endwhile; else: ?>
    <?php endif; ?>

<?php }else{
    include('standard-wp-singles-page-stuff.php');
} ?>

then once your singles page loads it will check for the current category in that post, if its in category 1, then it will load your custom loop, then it will loop through 2 posts, in the same category? giving you 2 links to other posts. also using an offset on that query should give you a link forward and a link backwards?
hope that helps..
fixing code layout.. didnt work too well :P


text:
Q: Find the maximum and minimum of $\cos x\sin y\cos z$.
Given $x\geq y\geq z\geq\pi/12$, $x+y+z=\pi/2$, find the maximum and minimum of $\cos x\sin y\cos z$.

I tried using turn $\sin y$ to $\cos(x+z)$, and Jensen Inequality, but filed. Please help. Thank you.
*p.s. I'm seeking for a solution without calculus.

A: (Edit 2017-01-14. This answer is incorrect. When I gave the answer, I misread the first requirement as $x,y,z\ge\pi/12$ --- it should be $x\ge y\ge z\ge\pi/12$. But I will leave it unmodified because the solution for the problem with the relaxed constraint is still interesting.)
You may rewrite the problem as finding the extrema of $f(x,z)=\cos(x)\cos(z)\cos(x+z)$ with $x, z \ge \pi/12$ and $x+z \le 5\pi/12$. Note that
$$\cos(x)\cos(z)\cos(x+z)=\frac12 [\cos(x+z)+\cos(x-z)] \cos(x+z)$$
and so
\begin{align*}
& [\cos(5\pi/12)+\cos(3\pi/12)] \cos(5\pi/12)\\
\le& [\cos(5\pi/12)+\cos(x-z)] \cos(5\pi/12)\\
\le&[\cos(x+z)+\cos(x-z)] \cos(x+z)\\
\le& [\cos(\pi/6)+\cos(x-z)] \cos(\pi/6)\\
\le& [\cos(\pi/6)+\cos(0)] \cos(\pi/6).
\end{align*}
Hence the maximum of $f$ occurs at $x=z=\pi/12$ and the minima occur at $(x,z)=(4\pi/12,\,\pi/12)$ or $(\pi/12,\,4\pi/12)$.

A: Let $$P=\cos x\sin y\cos z=\frac{\cos z}{2}\bigg[2\cos x \sin y\bigg] = \frac{\cos z}{2}\bigg[\sin(x+y)-\sin(x-y)\bigg]\leq \frac{\cos z}{2}\cdot \sin (x+y)$$
So $$P\leq \frac{\cos z \cdot \cos z}{2}=\frac{1}{4}(1+\cos 2z)\leq \frac{1}{4}\bigg[1+\cos 2\cdot \frac{\pi}{12}\bigg] = \frac{2+\sqrt{3}}{8}$$
Above equality hold when $\sin (x-y) = 0\Rightarrow x=y$ and given $\displaystyle x+y = \frac{\pi}{2}-z$ and $\displaystyle x\geq y \geq z\geq \frac{\pi}{12}$
And for $\max(P),$ We must have $\displaystyle z = \frac{\pi}{12}$ and $\displaystyle x=y = \frac{5\pi}{24}$


text:
Q: can tmux watch a particular pane for keys pressed? (to then issue `send-keys`) I want to have a pane with asciinema "video" (literally it's animated plain text) playing while in another pane the user can be doing miscellaneous stuff (typing commands, writing scripts, or whatever).  The user can switch to the asciinema pane and hit < space > key to pause/play the video.  I'd like to watch that pane and when the user pauses/plays the recording to then run tmux send-keys to pause/play an mp3 file that's playing in cmus in another window.
I haven't been able to find anything like tmux watch-pane or tmux listen.  Does something like that exist?  For this use case it'd need to distinguish between spaces being entered via asciinema and actual button presses by the user.
I'm using tmux 2.1, and don't see anything about watch or listen in the man page.  But maybe in a newer version there are commands provided?

A: There are a few ways you could try to do this, of varying complexity:

*

*You could bind the Space key in the root table to do what you want if pressed in the pane you want, perhaps something like:
bind -n Space if -F '#{m:*asciinema*:#{pane_current_command}}' 'send -t:mycmuswindow Space; send Space' 'send Space'

Or pane_title or whatever if pane_current_command won't work.

*You could turn on monitor-silence in the asciinema pane and use the alert-silence hook to similarly send a Space to the cmus pane.

*You could write a script that uses control mode to listen to data from the asciinema pane and send the Space, this is assuming it prints something you can recognise (like "paused") into the pane you can look for.


text:
Q: What's the benifit of filter in servlet? i'm new in servlet and want to know that what's the benifit of filter in servlet? and don't understand exactly what's the use of Filter? can you explain me with an example?
help would be appreciated!!

A: Filters not create a response like servlet. A filter is an object that can transform a request or alter a response before it reaches to a servlet and can process response before it leaves to a servlet.

*

*A filter can intercept a servlet's invocation before the servlet is
called
.

*Can examine a request before a servlet is called.

*Can modify the request headers and request data by providing a
customized version of the request object that wraps the real request.

*Can modify the response headers and response data by providing a
customized version of the response object that wraps the real
response.

*Intercept a servlet's invocation after the servlet is called.


text:
Q: Firebase setData not saving to Firestore Attempting to update values in my database. I checked and the type of ema.updatedIngredients that I'm passing to saveFunctions is a valid type in firestore.
The saveRecipe function works fine if I would use updateData. It deletes the documents as expected, but I know I'm pointing to the right document.
I can also add documents fine, it is when I am deleting an ingredients and updating the data where it doesn't work.
Save Recipe function to Firebase
func saveRecipe(ingredientList: [String: String], currentRecipe: String){
        guard let uid = FirebaseManager.shared.auth.currentUser?.uid else {
            return
        }
        FirebaseManager.shared.firestore
            .collection("users")
            .document(uid)
            .collection("userRecipes")
            .whereField("recipeID", isEqualTo: currentRecipe)
            .getDocuments() { (querySnapshot, err) in
                    if let err = err {
                        print("Error getting documents: \(err)")
                    } else {
                        for document in querySnapshot!.documents {
                            FirebaseManager.shared.firestore
                                .collection("users")
                                .document(uid)
                                .collection("userRecipes")
                                .document(document.documentID)
                                .setData(["ingredientItem" : ingredientList], merge: true)

                            print("Updated Recipe")
                        }
                    }
                }
            }

Where I call saveFunction
.toolbar{
            ToolbarItem(placement: .navigationBarTrailing){
                    Button(action: {
                        ema.editMode.toggle()
                        //if user is saving when complete is on the button
                        if !ema.editMode {
                        //saving to firestore
                            rm.saveRecipe(ingredientList: ema.updatedIngredients, currentRecipe: recipeID)
                        }
                    }){
                        HStack{
                            Image(systemName: !ema.editMode ? "pencil.circle" : "")
                                    .foregroundColor(.black)
                            Text(!ema.editMode ? "Edit" : "Complete")
                                .foregroundColor(.black)
                            }
                        }
                    }
                }
            }
        }

My View
struct RecipeIngredients: View {
    @State private var sheetMode: SheetMode = .quarter
    @State private var sizing = ""
    @State private var description = ""

    @ObservedObject var rm = RecipeLogic()
    @ObservedObject var ema: EditModeActive

    @Binding var currentRecipeID: String
    @Binding var ingredients: [String: String]

    //turn into Ordered Dictionary so I can grab ingredients key
    func turnIntoDictionary(regularDictionary: [String: String]) -> OrderedDictionary <String, String>{
        var dict = OrderedDictionary <String, String> (
            uniqueKeys: regularDictionary.keys,
            values: regularDictionary.values
        )
        dict.sort()
        return dict
    }

    private func listContent(for keys: [String]) -> some View {
        ForEach(keys, id: \.self) { key in
            HStack{
                Text(key)
                    .font(.title2)
                    .foregroundColor(.green)
                    .fontWeight(.bold)
                Text(turnIntoDictionary(regularDictionary: ingredients)[key] ?? "default")
                    .font(.title3)
            }
        }
        .onDelete { indexSet in
            if ema.editMode{
                let key = turnIntoDictionary(regularDictionary: ingredients).keys[indexSet.first!]
                self.ingredients.removeValue(forKey: key)
                ema.updatedIngredients = ingredients
            }
        }
    }

    var body: some View {
        ZStack{
            VStack{
                if ema.editMode{
                    HStack{
                        TextField("ex. 1 cup", text: $sizing)
                            .font(.body)
                            .padding(.leading, 30)

                        TextField("ex. Chicken Breast", text: $description)
                            .font(.body)
                    }
                    .padding(.top, 25) //set to give space from ingredient/direction section

                    Button(action: {
                        if (sizing != "" && description != ""){
                            ingredients[sizing] = description
                            ingredients[sizing] = description

                            ema.updatedIngredients[sizing] = description
                                sizing = ""
                                description  = ""
                        }

                    })
                       {
                        Image(systemName: "plus.circle.fill")
                            .foregroundColor(.blue)
                            .padding(.leading, 20)
                            .padding(.top, 20)
                            .opacity(!sizing.isEmpty && !description.isEmpty ? 1.0 : 0.5)
                           Spacer()

                    }
                       .padding(.top, -10)
                       .padding(.bottom, 10)
                }
                List{
                    self.listContent(for: Array(turnIntoDictionary(regularDictionary: ingredients).keys))

                }
                .onAppear{
                    ema.updatedIngredients = ingredients
                }
                .listStyle(SidebarListStyle())

                }
            }
        }
    }

EDIT: For further confusion, if I print right before calling the function, it prints the correct keys/values.

print(ema.updatedIngredients)

rm.saveRecipe(ingredientList: ema.updatedIngredients, currentRecipe: recipeID)

A: Almost ashamed to admit the simplicity of this solution. Once I went from setData to updateData it worked as expected.
Figured I would share in case someone runs into a similar issue.

A: I don't know how in Swift, but in JavaScript you need to pass {merge: true} as a second positional argument into .setData(), and it will update the document like .updateData() does.
Example:
...
.setData(["ingredientItem": ingredientList], {merge: true})

A: There are two methods for updating:
1 .  set() - Sets data on the document, overwriting any existing data. If the document does not yet exist, it will be created.
2 . update() - Updates data on the document. Data will be merged with any existing document data. If no document exists yet, the update will fail.
== In flutter ==

*

*To update a value in the document
var collection =
FirebaseFirestore.instance.collection('collection');
collection
 .doc('doc_id')
 .update({'key' : 'value'}) // <-- Updated data
 .then((_) => print('Success'))
 .catchError((error) => print('Failed: $error'));

*To add a new value to the existing document.
var collection =
FirebaseFirestore.instance.collection('collection');
collection
  .doc('doc_id')
  .set(yourData, SetOptions(merge: true)); // <-- Set merge to true.

So in your case update() is more suited than set()


text:
Q: The number of primes in an interval What is the smallest known $c$ so that for any $n\geq 2$ there are at least $n/\log_2{n}$ primes between $n$ and $cn$ (inclusive)?
The prime number theorem seems to give an asymptotic result so I am not sure how to get a particular constant from it.

A: Terry Tao's notes give a version of the prime number theorem in short intervals:
$$
\sum_{x\le n\le x+y}\Lambda(n)\sim y
$$
for $x\to\infty$ and $x^{3/4+\varepsilon}\le y\le x.$ So with $y=x\log 2$
$$
\sum_{x\le n\le x+y}\Lambda(n)\sim y
$$
and thus
$$
\pi(x+y)-\pi(x)\sim y/\log(x+y)+O(\sqrt{x+y})\sim x\log 2/\log x
$$
and so 'all' that is required is finite checking. As Daniel Fischer suggests in a comment, 13/6 may suffice.


text:
Q: From ASP.NET can I access all Sessions? I want to enumerate all the Sessions. Are they available, or do I have to keep references to them manually from Session_Start in Global.asax?

A: You can create your own session provider which gives you access to all the sessions via some special command. The built-in session handlers don't, however.
I wonder why you want to do this, though? It seems like an unusual requirement, and a possible security issue as well.


text:
Q: Laurent Series Problem
Basically for this question, I only know

But I do not quite understand what I have to do with different domains
Any useful advice is welcome, thanks in advance!

A: So with $1<|z|$, then $\left|\dfrac{1}{z}\right|<1$, so
\begin{align*}
\dfrac{z-1}{z(1+z^{2})}&=\dfrac{1-\dfrac{1}{z}}{1+z^{2}}\\
&=\dfrac{\dfrac{1}{z^{2}}-\dfrac{1}{z^{3}}}{1+\dfrac{1}{z^{2}}}\\
&=\left(\dfrac{1}{z^{2}}-\dfrac{1}{z^{3}}\right)\left(1-\left(\dfrac{1}{z^{2}}\right)+\left(\dfrac{1}{z^{2}}\right)^{2}-\cdots\right).
\end{align*}


text:
Q: Solving an equation of the form $f = T(f)$, Alternative to fixed point iteration Let $T$ be some integral operator and suppose $f:[0,\infty) \rightarrow [0,\infty)$ is a function which satisfies:
$$f = T(f).$$
A popular method for finding $f$ is to take some arbitrary $f_0$ and then set $f_{n+1} = T(f_n)$ for each $n$ (a fixed point iteration). However, convergence does not always hold (especially when you start with a bad choice for $f_0$). Are there some alternative methods for solving these type of equations numerically?

A: It depends on the operator $T$ and the underlying space $X$.
For instance, if $X$ is a Hilbert space and $T$ is nonexpansive,
then your iteration may not work: indeed, if $T$ is the negative identity, then you only bounce back and forth unless you start at the unique fixed point $0$.
If $T$ is nonexpansive in the Hilbert space $X$, a much better iteration is
$$f_{n+1} = \tfrac{1}{2}f_n + \tfrac{1}{2}T(f_n).$$
This Krasnoselskii-Mann iteration will converge at least weakly to a fixed point provided there exists one.

A: To expand on Max's answers if you want more degrees of freedom. Any mean preserving smoothing operator will have stabler convergence properties.
For example convolution with the weighted mean:
$$f_{n+1}= \beta T(f_n) +\displaystyle\sum_{k=0}^N \alpha_k f_{n-k}$$
where
$$\displaystyle \beta + \sum_{k=0}^N \alpha_k = 1$$
Examples:
$\beta =1, \alpha_k = 0$ gives your fixed point iteration.
$\beta = 1/2, \alpha_0 = 1/2, \alpha_{>0} = 0$ gives Max's answer.


text:
Q: Forms: How to add dropdown choice at the end of an input text field? I am building a HTML form for a subdomain maker. I am not great in using javascript, so my question may be silly. But I ask here as this is the place that has given me the best answers yet :-)
The subdomain will consist of {users-input}.{oneofmanypredefined.domains}
The user will be able to make a subdomain where they can
1) enter any value (a-z,0-9,-) in a text field,
and
2) then choose what predefined main domain they want to add the subdomain to.
I have made it work now by using a input text field + a select options. This way I need to mix them into one hidden field on the next page (form action="nextpage.php")
Possible solution 1:
Is there a way where I can make ONE text field has one part that is like a normal text field, and then one part that is a dropdown, but with the same id and name?

I tried to post an image, but need more reputations: http://bildr.no/image/cSsyNWdQ.jpeg
I have googled and searched here, but not found any solution for this. It may because there is none, but at least I can ask :-)
The reason I ask is if this exists, then it will help me save time redoing all javascript and all other code built on this one input field.
Possible solution #2: Is there is a good way to use javascript to combine "on the fly" a value entered into a text field + a value chosen in a select, so I can use that combined value to enter into all javascript. So that every time I write in a text field, or make a new select choice, the javascript updates on the fly?

A: The possible solution #2 is likely to be realistic.
This is an init state:
var combined_value = '';
var input_field = $('#subdomain'); // <input type="text" id="subdomain" ... >
var select_field = $('#domain_list'); // <select id="domain_list" ... >

Then two onchange events can be defined:
input_field.change(update_combined_value);
select_field.change(update_combined_value);

function update_combined_value() {
    combined_value = input_field.val() + select_field.val();
}

Thus after every change the variable combined_value contains the whole subdomain.

A: Using jQuery and the (HTML5 required attribute), you can use this:
<form action="anything.html" target="_blank">
    <input type="text" id="field1" name="par1" required  />
    <input type="text" id="field2" name="par2" required />

    <input type="text" id="willbehidden" name="concatpars" />

    <button>send</button>
</form>

$("form").on("submit", function() {
    $("#willbehidden").val( $("#field1").val() + $("#field2").val() )
});

JSFIDDLE here: http://jsfiddle.net/chrisbenseler/6xw3f8mq/
Form is posted only if the first 2 inputs are not blank.


text:
Q: Cant get past Ubuntu emergency mode w/ Windows 7 dual boot after running Boot-repair I am new to Ubuntu and I apologize if the answer to my problem is easy, but I assure you all that I have search thoroughly for the answer and could not find it.
For the past 5 days I have been trying to set up a Dell t3500 dual boot Ubuntu/Win7 rig. My current issue is every time I boot from grub, Ubuntu goes straight into emergency mode, this happened after running "boot-repair". Windows 7 runs just fine.
I originally ran boot-repair because I could not get into Ubuntu, after installing windows because it would just go straight into Win7 without giving me the option of choosing Ubuntu. I had the same issue not being able to get into windows but I booted a flashUSB and auto-updated from there. That seemed to fix the boot menu issues. The code below is from the journalctl -xb (All RED errors).
My OS's are both on the same HD, and I used Gparted to partition them. Again, apologies if I am not including enough information or if this has been answered before but I'm having a really hard time.
  Jun 04 20:53:18 ubuntu kernel: sd 6:0:0:0: [sdc] No Caching mode page found
Jun 04 20:53:18 ubuntu kernel: sd 6:0:0:0: [sdc] Assuming drive cache: write through
Jun 04 20:53:19 ubuntu kernel: dell_smbios: Unable to run on non-Dell system
Jun 04 20:53:31 ubuntu pulseaudio[2051]: [pulseaudio] pid.c: Daemon already running.
Jun 04 20:53:56 ubuntu pulseaudio[1961]: [pulseaudio] bluez5-util.c: GetManagedObjects() failed: org.freedesktop.DBus.Error.NoReply: Did not receive a reply. Possible causes include: t
Jun 04 20:54:00 ubuntu ubiquity[1851]: log-output -t ubiquity debconf-copydb configdb targetdb -p ^oem-config/ --config=Name:targetdb --config=Driver:File --config=Mode:0644 --config=F
Jun 04 20:54:00 ubuntu ubiquity[1851]: log-output -t ubiquity debconf-copydb configdb targetdb -p ^keyboard-configuration/ --config=Name:targetdb --config=Driver:File --config=Mode:064
Jun 04 20:54:01 ubuntu ubiquity[1851]: log-output -t ubiquity debconf-copydb configdb targetdb -p ^console-setup/ --config=Name:targetdb --config=Driver:File --config=Mode:0644 --confi
Jun 04 20:54:06 ubuntu spice-vdagent[6053]: Cannot access vdagent virtio channel /dev/virtio-ports/com.redhat.spice.0
Jun 04 20:54:12 ubuntu colord-sane[6149]: io/hpmud/pp.c 627: unable to read device-id ret=-1

/home/ubuntu/Downloads/IMG_2486.JPG


text:
Q: How to matlab continue processing while waiting for user input Suppose we have the following for loop:
for i=1:100
    % image processing calculation
    % show image to the user and ask for his rating
    rating(i) = input('Enter rating of the shown image\n');
end

Obviously, the input command will wait for the user input and the for loop won't continue until the user has provided his input. The image processing code I'm running in the for loop is time consuming so I'd like to know if there's a way to make MATLAB continue calculations - in the background - for the following loop iteration while waiting for the user's input.

A: This is the idea I mentioned in my comment.
num_im = 3; % Number of images

% Initialize
rating = zeros(num_im,1);
fig = zeros(num_im,1);
txt = zeros(num_im,1);

% Main loop
for i = 1:num_im
    % image processing calculation
    pause(1); % a dummy calculation
    % Open a figure
    fig(i) = figure('Name', ['Image #' num2str(i)],...
        'CloseRequestFcn', [... % read the text edit
        'temp = str2double(get(txt(' num2str(i) '), ''String'')); ',...
        'if isnan(temp), errordlg(''Please enter the rating.''); ',... % Error if invalid
        'else, rating(' num2str(i) ') = temp; delete(fig(' num2str(i) ')); end']);

    subplot(2,1,1, 'position', [0 0.5 1 0.5]);

    % Show your image
    [im, map] = imread('trees.tif');
    imshow(im, map);
    % Text edit
    txt(i) = uicontrol('Units','Normalized',...
        'Style','edit',...
        'Position', [0.3 0.2 0.4 0.2]);
end

Make sure to click somewhere else after you enter the ratings so that the text box detects your input.
It will store all the ratings in rating matrix.
However this does not limit the number of open figures.
Refer to the Edit if you want to limit them.

Edit
To limit the number of opened figures. I suggest you to put all the images after calculation in a Queue and set a timer to ask the user rating in the background until all the ratings are asked.
Main.m
num_im = 4; % Number of images
max_num_figs = 2; % maximum number of open figures

% Initialize
rating = zeros(num_im,1);
fig = zeros(num_im,1);
txt = zeros(num_im,1);
show_idx = 0; % Number of shown images
Calc_idx = 0; % Number of images in Queue
num_open_figs = 0; % number of open figures

Queue = cell(num_im, 1);
% Main loop

% Start a timer for asking the user rating in background
tmr = timer('ExecutionMode', 'fixedRate',...
    'Period', 0.5, 'TimerFcn', 'tmr_callback');
start(tmr);

for k = 1:num_im
    % image processing calculation
    pause(1); % a dummy calculation

    % Put the image and its data into a Queue ith
    [im, map] = imread('trees.tif');
    Queue{Calc_idx+1} = {im, map};
    Calc_idx = Calc_idx + 1;
end

tmr_callback.m
% Create a GUI if there is any unshown images in the Queue
% and if open figures are less than maximum number of figures
if show_idx < Calc_idx && num_open_figs < max_num_figs
    num_open_figs = num_open_figs + 1;
    show_idx = show_idx + 1; % Number of shown images
    % Open a figure
    fig(show_idx) = figure('Name', ['Image #' num2str(show_idx)],...
        'CloseRequestFcn', [...
        'temp = str2double(get(txt(' num2str(show_idx) '), ''String'')); ',... % Read the text edit
        'if isnan(temp), errordlg(''Please enter the rating.''); ',... % Error if invalid
        'else, rating(' num2str(show_idx) ') = temp; delete(fig(' num2str(show_idx) ')); ',...
        'num_open_figs  = num_open_figs - 1; end']);

    subplot(2,1,1, 'position', [0 0.5 1 0.5]);
    imshow(Queue{show_idx}{:});
    % Text edit
    txt(show_idx) = uicontrol('Units','Normalized',...
        'Style','edit',...
        'Position', [0.3 0.2 0.4 0.2]);
    % turn off the timer if all ratings are asked.
    if (show_idx == num_im)
        stop(tmr);
    end
end

I also suggest to write the data(rating) into a file after the user enters each of them. You can use dlmwrite for example.


text:
Q: Html tables within div export to excel   <script type="text/javascript">
        $(document).ready(function () {
            //getting values of current time for generating the file name
            $(".toExcelButton").click(function(){
            var dt = new Date();
            var day = dt.getDate();
            var month = dt.getMonth() + 1;
            var year = dt.getFullYear();
            var hour = dt.getHours();
            var mins = dt.getMinutes();
            var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
            //creating a temporary HTML link element (they support setting file names)
            var a = document.createElement('a');
            //getting data from our div that contains the HTML table
            var data_type = 'data:application/vnd.ms-excel';
            var table_div = document.getElementById('dvData');
            var table_html = table_div.outerHTML.replace(/ /g, '%20');
            a.href = data_type + ', ' + table_html;
            //setting the file name
            a.download = 'exported_table_' + postfix + '.xls';
            //triggering the function
            a.click();
            //just in case, prevent default behaviour
            e.preventDefault();
                })
        });
    </script>

Need to export div tables to excel. The above code works fine in Chrome but not working in IE. Can anyone help me out on the same.

A: In IE a dynamically created anchor tag needs to be added to the DOM to execute its click event. Furthermore the download attribute is not supported in the IE:
Download attribute on A tag not working in IE
Edit:
Recently I posted many answers handling this issue, here are two of those:
image does not download with it's own extension
JS Base64 string to downloadable pdf - Edge
Basically you have to use msSaveOrOpenBlob() in IE:
var tF = 'Whatever.xls';
var tB = new Blob(..);

if(window.top.navigator.msSaveOrOpenBlob){
    //Store Blob in IE
    window.top.navigator.msSaveOrOpenBlob(tB, tF)
}
else{
    //Store Blob in others
    var tA = document.body.appendChild(document.createElement('a'));
    tA.href = URL.createObjectURL(tB);
    tA.download = tF;
    tA.style.display = 'none';
    tA.click();
    tA.parentNode.removeChild(tA)
}

In the case above:
var tT = new XMLSerializer().serializeToString(document.querySelector('table')); //Serialised table
var tF = 'Whatever.xls'; //Filename
var tB = new Blob([tT]); //Blob

if(window.top.navigator.msSaveOrOpenBlob){
    //Store Blob in IE
    window.top.navigator.msSaveOrOpenBlob(tB, tF)
}
else{
    //Store Blob in others
    var tA = document.body.appendChild(document.createElement('a'));
    tA.href = URL.createObjectURL(tB);
    tA.download = tF;
    tA.style.display = 'none';
    tA.click();
    tA.parentNode.removeChild(tA)
}

https://jsfiddle.net/23ao1v0s/1/

A: Please check the below given link. I think you will get a solution for your question
https://github.com/rainabba/jquery-table2excel


text:
Q: Cannot install node.js under Windows 7: "the specified path is too long" Using the newest node.js installer from https://nodejs.org, I run into the same error every time when it reaches the npm installation. npm 3.x was supposed to deal with this issue, but apparently it doesn't help the node.js installer. The node developers have essentially refused to do anything about it, as this problem has been around for about two years already. Unfortunately, I can't seem to find a work around. How can I get this to install?

A: This might happen, when you install nodejs (or its component) in a very long  path, like this:
c:\something_folder_blabla\another_folder_longname\another_still_folder\something_folder_blabla\another_folder_longname\another_still_folder\.............................nodejs\

or unicode(UTF-8) chars containing path:
c:\სპეციალცჰარაქტერს\\another_folder\nodejs

So, install in a shorter and English-charactered path


text:
Q: Colunas das tabelas sql server não são reconhecidas no php Tenho colunas que foram gravadas no sql server com letra maiúscula, quando recebo no php precisava que ele reconhecesse elas tanto minusculas quanto maiúsculas.
Por exemplo:
select * from rzv_aluno

registros:
AL_NOME, AL_EMPRESA... etc

no php só consigo ver os registros se eu apontar
$r->AL_NOME

gostaria que não houvesse diferença entre
$r->AL_NOME e $r->al_nome


text:
Q: Attempt to present View Controller Warning I have the following ViewControllers that present the next ViewController when something is finished:
Nr1: My GameViewController checks that the game has finished and call CheckGameFinished:
-(void) checkGameFinished {
if ([self.gameModel isGameOver]) {

    double delayTimeInSeconds = 3.5;
    dispatch_time_t popTimeDelay = dispatch_time(DISPATCH_TIME_NOW, delayTimeInSeconds * NSEC_PER_SEC);
    dispatch_after(popTimeDelay, dispatch_get_main_queue(), ^(void){

    [progressBarTimer invalidate];

    level2ViewController *govc = [self.storyboard instantiateViewControllerWithIdentifier:@"level2ViewController"];

    [self.finishAudio play];

    [self presentViewController:govc animated:NO completion:^(){
        [self.gameModel clearGameData];

    }];
          });
}
}

Then level2ViewController appears:
- (void)viewDidLoad {
[super viewDidLoad];

double delayTimeInSeconds = 2;
dispatch_time_t popTimeDelay = dispatch_time(DISPATCH_TIME_NOW, delayTimeInSeconds * NSEC_PER_SEC);
dispatch_after(popTimeDelay, dispatch_get_main_queue(), ^(void){

    GameViewController *gvc = [self.storyboard instantiateViewControllerWithIdentifier:@"gameViewController"];

    [self presentViewController:gvc animated:NO completion:nil];

});

}

and called the next ViewController, and so on.
Now I get overtime the following Warnings:

Warning: Attempt to present GameViewController on level2ViewController
  whose view is not in the window hierarchy!

A: Don't present a view controller from viewDidLoad, instead call from viewDidAppear:. Also using dispatch_after like that (assuming you are using it to hopefully make sure the view is on screen and not for gaming purposes) is a very bad practice.
When the view controller that is being loaded has done being presented (that happens when viewDidAppear: is called) you can present a different one:
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    GameViewController *gvc = [self.storyboard instantiateViewControllerWithIdentifier:@"gameViewController"];
    [self presentViewController:gvc animated:NO completion:nil];
}

A: I was getting this when my segue type was modal, changing to push fixed it for me


text:
Q: Using iOS storyboarding I can't place label in spot I want on view controller Dragging immediately drops it somewhere in the beginning where I don't want it... I'm looking to put it in the top center.

A: @Jaime It's a solution but not best. The top bar called UINavigationBar which already has title to display in the top center. So you should drag out a navigation item to view controller and set its title.

A: Doh, problem was the ViewController did not have a view on it. Adding a view and dragging the label on top of it fixed it.


text:
Q: InvalidPathException when integrating Apache Jena into Web Application project I want to use Jena inside a JSF Web Application.
My pom.xml contains the depencency for jena-arq version 3.9.0 and dependencies for JSF.
I have created an IndexView backing Bean with an init method, annotated with @PostConstruct.
Everything works fine without calling Jena API.
On adding to init method this simple line
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
these exception are thrown:
javax.servlet.ServletException
...
Caused by: java.lang.ExceptionInInitializerError
...
Caused by: java.nio.file.InvalidPathException: Illegal char <:> at index 4: file:location-mapping.rdf

I've tried to change the Jena version used with an older version and I've noticed that until version 2.11.0 everything works. With newer versions the above exceptions are thrown.
It seems that the file: prefix is the problem. I've found this related topic link but it says that the bug has been fixed.

A: The stack trace shows that classloader is specific to the environment - it is calling org.jboss.modules.ConcurrentClassLoader.getResourceAsStream which is probably why code that has not changed in many versions does not work here.
Why this classloader is throwing InvalidPathException from the filesystem when it is a classloader is strange and different behaviour to the standard Java OpenJDK (getResourceAsStream returns null for file:location-mapping.rdf).
If you don't need files remapped, you try adding a call disable this feature:
import org.apache.jena.util.LocationMapper;

(note there are two classes called "LocationMapper")
and use the call:
LocationMapper.setGlobalLocationMapper(new LocationMapper());

This must be called very early, before any other Jena code.


text:
Q: Inverting a linear transformation from $L^2$ to $R^N$ Let $f(t) \in L^2$ and $\{\alpha_i(t)\}$ be a set of $N$ linearly independent functions in $L^2$. Let the $i$th entry of $b \in R^N$ equal $\int f(t) \alpha_i(t)dt$.
Is there a general method for solving for $f(t)$ given $b$? I realize that the solution is in general not unique, but I was wondering if there was a general way to find any such solutions (perhaps the minimum norm solution?).

A: Do a Gram-Schmidt orthogonalization of the $\alpha_i$. Let be $\{\beta_i\}_{i=1}^N$ the new subspace basis. Write the coefficients $c_i = \int f\beta_i$ depending on the $b_i = \int f\alpha_i$. The sum $\sum_{i=1}^N c_i\beta_i$ will be a solution of your problem.


text:
Q: check if value exist in database array not working need to check if the value exist in array , the array created from database table, it just not working with me keep getting error says "in_array() expects parameter 2 to be array, string given"
can someone please help ?
PHP code
<?php
    $lang='en';
    $query_rsLanguages = "SELECT * FROM languages";
    $rsLanguages = mysql_query($query_rsLanguages);
    $languages_array = array();
    while($row = mysql_fetch_array($rsLanguages)){
      $languages_array[] = "\"".$row['language_sign']."\"";
    }
    $languages_string = implode(",", $languages_array);
    if (in_array($lang, $languages_string)) {
        echo 'found' ;
        }
?>

A: You are imploding $languages_array to a string and passing that to in_array, which is incorrect and unnecessary. As the error says you need to pass an array to search in. You just need to build the array of languages from your result and check that:
<?php
    $lang='en';
    $query_rsLanguages = "SELECT * FROM languages";
    $rsLanguages = mysql_query($query_rsLanguages);
    $languages_array = array();
    while($row = mysql_fetch_array($rsLanguages)){
      $languages_array[] = $row['language_sign'];
    }

    if (in_array($lang, $languages_array)) {
        echo 'found' ;
    }
?>

A: This will check if the String $lang exists inside your $languages_array or not
if (in_array($lang, $languages_array)) {
        echo 'found' ;
}

A: The above error is saying that the second parameter of the in_array should be an array, by using implode you are making it a string use the code below.
<?php
    $lang='en';
    $query_rsLanguages = "SELECT * FROM languages";
    $rsLanguages = mysql_query($query_rsLanguages);
    $languages_array = array();
    while($row = mysql_fetch_array($rsLanguages)){
      $languages_array[] = $row['language_sign'];
    }

    if (in_array($lang, $languages_array)) {
        echo 'found' ;
    }
?>

Hope this helps you


text:
Q: ignore files ending with numbers with 0-3 digits This question must have been asked before, but I was not able to find an answer.
I want to use .gitignore to ignore all of the following files:
dsmodelext.c
dsmodelext1.c
dsmodelext2.c
dsmodelext23.c
dsmodelext107.c

Currently I put four lines in my .gitignore file:
dsmodelext.c
dsmodelext[0-9].c
dsmodelext[0-9][0-9].c
dsmodelext[0-9][0-9][0-9].c

Is there a way to express the same on a single line?

A: Gitignore takes it's syntax from fnmatch/glob, which is specified in man glob(7).
There doesn't seem to be a way to indicate a certain number of characters need to be matched, like you could with the regular expression dsmodelext[0-9]{0,3}.c
You could decide to be lenient and just defined dsmodelext*.c to be ignored.

A: given the files
dsmodelext.c
dsmodelext1.c
dsmodelext2.c
dsmodelext23.c
dsmodelext2x3.c
dsmodelext107.c
dsmodelext107foo.c

The glob pattern dsmodelext*[0-9].c would match
dsmodelext1.c
dsmodelext2.c
dsmodelext23.c
dsmodelext2x3.c
dsmodelext107.c

For some of these number usecases this is a good enough approximation.


text:
Q: sql loader requires dat file to load the data I have a folder with several file s but they are not .dat. For my surprise i Could  load one file but only when I renamed to .dat . What Am I doing wrong or I need to rename all my files to .dat ?   My Files does not have  extensions
Thanks guys
controlfile
load data
infile 'D:\pageviews\year=2016\month=06\*'
replace
into table test
fields terminated by whitespace
trailing nullcols
(
c1,
c2,
c3,
c4
)

A: As far as I can tell, INFILE clause you use is wrong.
You should name a file you're loading. Asterisk is used when data (you're about to load) is contained within the control file itself (after the BEGINDATA keyword).
If you don't specify a file extension, then it defaults to .dat (that's why you managed to load the file).
Possible cases (copied from the documentation):

*

*Data contained in the control file itself: INFILE  *

*Data contained in a file named foo with a default extension of .dat: INFILE  foo

*Data contained in a file named datafile.dat with a full path specified: INFILE 'c:/topdir/subdir/datafile.dat'
Do read documentation; it'll be much more clear what you should (not) do.


text:
Q: Concrete5 "Area" causing blank screen On a relatively straightforward concrete5 website, I have the following code:
        $a = new Area('Full width');
        $a->display($c);

The second line is breaking the page, but I cannot work out why.  If you comment it out the page is rendered (clearly without the content showing),  with it the page is completely blank (nothing in the source at all).
There's nothing relevant in either the concrete5 log, or the php error log and I'm all out of ideas of how to find out what could have gone wrong (which I can only assume is a data issue as the rest of the website is fine).
I'm hoping someone may have experienced something similar with ideas on how to debug or diagnose this.
(this is not a duplicate of other more generic "php white screen of death" - I have followed these and they do not have the answer to this, probably more specific, question)

A: If you're on a newer version of C5 try without the $c as that's not necessary anymore and might cause a problem depending on your PHP settings.

A: You shouldn't use the global $c anymore (you don't say what version) but set it explicitly:
$c = \Page::getCurrentPage();

Also, you can try this (view the source after page render):
// $a->display($c);
echo '<!--<pre>'. print_r($c, 1). '</pre>-->';

You should also turn on debugging during development (Output error info & Show debug):
http://yoursite.com/index.php/dashboard/system/environment/debug
@Nour - I thought the $c should not be used with Global Areas only...


text:
Q: How do I unsubscribe from a Firestore listener in React-Native? How do I unsubscribe from a Firestore listener in React-Native? I have a function where I am fetching and listening to changes in Firestore:
_fetchPatientsList() {
        var query = firestore().collection('Collection').doc().collection('public');
        query = query.where('act', '==', 1);
        query = query.where('city', '==', this.state.selected_city);
        query = query.orderBy('update_time', 'desc');
        query = query.limit(10);

        query.onSnapshot({
            error: (e) => this.setState({ errorMessage: e, refreshingPatients: false }),
            next: (querySnapshot) => {
                ///do something
            },
        });
 }

And I would like to unsubscribe when I log out:
    _logOutHandler = () => {
    auth()
        .signOut()
        .then(() => {
            console.log('User signed out!')
        });
    let unsub = firestore().collection('Collection').doc().collection('public').onSnapshot(() => {
    });

    // Stop listening for changes
    unsub();
}

Is this the proper way of doing it?

A: you have to save a listener reference const unsubRef = query.onSnapshot
use the reference, example:
const unsubRef = query.onSnapshot({
 error: (e) => this.setState({ errorMessage: e, refreshingPatients: false }),
 next: (querySnapshot) => {
   ///do something
 },
});

//just make it to unsubscribe
unsubRef();

to stop listener on other function, you can make this:

import from ....

//variables
let unsubRef;

// function to stop listener
stopListener = (unsubRef) => {
   unsubRef();
};

//save the reference for this query
unsubRef = query.onSnapshot({
            error: (e) => this.setState({ errorMessage: e, refreshingPatients: false }),
            next: (querySnapshot) => {
                ///do something
            },
        });

//other function you want cancel listener
otherFunc = async() => {
   // some code

   //stop the listener
   await this.stopListener(unsubRef);
   //signout code
};

you can see more details here:
https://rnfirebase.io/firestore/usage#realtime-changes
or
https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener


text:
Q: how to create ini file as HDFS on linux I am new to linux. Cloudera documentation has mentioned creating sentry-provider.ini file on cloudera CHD 5.4 as HDFS file.  I am not finding good article on how to create ini file on linux.
I am trying to configure Apache Sentry on cloudera setup to have role based security on hive metadata
how to create ini file as HDFS on linux?

A: Simple way is: You can create this "sentry-provider.ini" file on your local (on linux terminal)
vi sentry-provider.ini

Then put the content specified at this link in the file by pressing i and then pasting the content.
After this put the file on HDFS file system using command :
hdfs dfs -copyFromLocal sentry-provider.ini etc/sentry/

Remember that the path etc/sentry/ is the path on HDFS from your user's home directory which is typically /user/username/


text:
Q: how can i use functions that needs a ui thread without giving it context in android? I'm using a service class in my app which runs for long time period and i sometimes need a ui thread to do my work such as finding a contact name which make me create a cursor variable, that cursor variable needs a content resolver which needs a context.
how i can do this work freely without any ui thread?

A: You won't be able to get the UI thread from another thread (obviously), but you'll be able to get a Context, which is certainly what you need.
And a Service is a Context, so you have access to any method like getResource() or getContentResolver() with a Service reference.


text:
Q: Benchmarking Code Runtime with Trace32 I have an embedded system with code that I'd like to benchmark. In this case, there's a single line I want to know the time spent on (it's the creation of a new object that kicks off the rest of our application).
I'm able to open Trace->Chart->Symbols and see the time taken for the region selected with my cursor, but this is cumbersome and not as accurate as I'd like. I've also found Perf->Function Runtime, but I'm benchmarking the assignment of a new object, not of any particular function call (new is called in multiple places, not just the line of interest).
Is there a way to view the real-world time taken on a line of code with Trace32? Going further than a single line: would there be a way to easily benchmark the time between two breakpoints?

A: The solution by codehearts, which uses the RunTime commands, is just fine if you don't have a real-time trace. It works with any Lauterbach tool and any target CPU.
However if you have a real-time trace (e.g. CPU with ETM and Lauterbach PowerTrace hardare), I recommend to use the command Trace.STATistic.AddressDURation <start-addr> <end-addr> instead. This command opens a window which shows the average time between two addresses. You get best results, if you execute the code between the two addresses several times.
If you are using an ARM Cortex CPU, which supports cycle-accurate timing information (usually all Cortex-A, Cortex-R and Cortex-M7) you can improve the accuracy of the result dramatically by using the setting ETM.TImeMode.CycleAccurate (together with ETM.CLOCK <core-frequency>).
If you are using a Lauterbach CombiProbe or uTrace (and you can't use the ETM.TImeMode.CycleAccurate) I recommend the setting Trace.PortFilter.ON. (By default the port-filter is set to PACK, which allows to record more data and program flow, but with a slightly worse timing accuracy.)

A: Opening the Misc->Runtime window shows you the total time taken since "laststart." By setting a breakpoint on the first line of your code block and another after the last line, you can see the time taken from the first breakpoint to the second under the "actual" column.


text:
Q: Groovy Nested Templates - Cannot invoke methods in class from within template I'm trying to use Groovy's SimpleTemplateEngine to generate some output instead of StringBuilders, but I can't get templates to call other methods in my class successfully (which ultimately invoke other Templates to form a nested chain).
When the template (example below) invokes the method <% generateItemOutput(itemDescriptor.itemList) %> I get an exception:
groovy.lang.MissingMethodException: No signature of method:
SimpleTemplateScript1.generateItemOutput() is applicable for
argument types: (java.util.ArrayList)

I've tried making all the methods static, and adding an import to the static method in the template (as suggested here) but I get unable to resolve class ... to the import I use:
SimpleTemplateScript1.groovy: 1: unable to resolve class uk.co.e2x.convert.XMLToSlurp.generateItemOutput
 @ line 1, column 20.
   out.print(""""""); import uk.co.e2x.convert.XMLToSlurp.generateItemOutput ;
                      ^

Here's a sample of what I'm doing without the statics:
public String generateItemDescriptorOutput(itemDescriptor) {
    def params = [itemDescriptor: itemDescriptor]
    def template = new groovy.text.SimpleTemplateEngine().createTemplate(itemDescriptorTemplate())
    def writeable = template.make(params)
    return writeable.toString()
}

public String generateItemOutput(itemList) {
    ...
}

public String itemDescriptorTemplate() {
    return = '''\
${itemDescriptor.name} {
repository = "${itemDescriptor.repository}"
props = [
    <% generateItemOutput(itemDescriptor.itemList) %>
]
}
'''
}

I invoke it with java -cp ... but got same problem invoking via groovy. The reason I moved to invoking it through java was I can't work out the package path to a static method in a groovy script.
Has anyone got any concrete examples of calling your own script/classes methods from within a template, or can tell me what I'm doing wrong?
Cheers.

A: Ok, I managed to get it working and it was fairly simple in the end. I had to use statics for all the generate and template methods and then add the fully qualified package name to the methods inside the template instead of trying to do an import.
Also found I was missing a print in the command too. Here's the fixed template:
public static String itemDescriptorTemplate() {
    return = '''\
${itemDescriptor.name} {
repository = "${itemDescriptor.repository}"
props = [
    <% print uk.co.e2x.convert.XMLToSlurp.generateItemOutput(itemDescriptor.itemList) %>
]
}
'''

A: I include nested templates inside a parent template using a static utility method like this:
class TemplateUtils {

    static String generateOutput(String templateFilename, Map templateBinding) {
        URL templateResource = TemplateUtils.classLoader.getResource(templateFilename)
        assert templateResource : "Resource for '${templateFilename}' not found"
        new GStringTemplateEngine().createTemplate(templateResource).make(templateBinding)
    }
}

Then in the parent template:
Dear $to
<% out.println(com.example.TemplateUtils.generateOutput("letterContent.template", variables)) %>
Regards $from

The parent template's bound variables are relayed to the 'letterContent' template in the variables variable.