text:
Q: Inbox Rule to Send Alert When Rate of Emails Increases I receive hundreds of automated alerts everyday (for things like CPU/Memory spikes, SQL Blocks). However, usually, there's nothing that I can/want to do when these alerts come in; I only care when there is a surge of alerts, because that's abnormal. I do at least have them going to separate folders, but that's still distracting, because I have to always be somewhat mindful of that unread email number.
Is there some way to alert me when I get, say, more than X number of emails from sendername within N minutes?
Using Outlook, Office 365
I tried looking for Outlook add-ins, but it's a difficult question to describe to Google. I know a tiny bit of VBA, but not enough to get me started on this.

A: Basically, you have to run a timer to periodically run a scanner for the number of emails arrived in your inbox. In the event handler fired by the timer (usually called Tick) you can use the Find/FindNext or Restrict methods of the Items class.
The simplest and fastest way is to create a VBA macro. See Getting started with VBA in Office and Using Visual Basic for Applications in Outlook articles to get started quickly.
The following articles can help you with coding the required algorithm on top of described methods for looking Outlook items:

*

*How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

*How To: Use Restrict method to retrieve Outlook mail items from a folder

*Advanced search in Outlook programmatically: C#, VB.NET
To run a timer periodically you can use the SetTimer function.
See Outlook VBA - Run a code every half an hour for the sample code.
Public Declare Function SetTimer Lib "user32" (ByVal HWnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
 Public Declare Function KillTimer Lib "user32" (ByVal HWnd As Long, ByVal nIDEvent As Long) As Long

 Public TimerID As Long, TimerSeconds As Single
 Dim Counter As Long

 ' Start Timer
 Sub StartTimer()
    ' Set the timer for 1 second
    TimerSeconds = 1
    TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
 End Sub

 ' End Timer
 Sub EndTimer()
    On Error Resume Next
    KillTimer 0&, TimerID
 End Sub

 Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, ByVal nIDEvent As Long, ByVal dwTimer As Long)
   Debug.Print Now
   ' call your code here
 End Sub

A: I assume from your question that you were hoping someone had already developed a solution to your problem.  Perhaps they have but I think it is unlikely that they would post that solution for others to find.  I think you will have to develop your own solution.  The approach I have developed is very different from Eugene's.  Between us, we offer some interesting ideas for you to select from.
I do not believe the VBA needed is particularly advanced.  You may already know enough, particularly with two answers to study.  If not, I would start with Excel VBA.  I have failed to find an Outlook VBA tutorial I like but have seen of several Excel VBA tutorials that look good.  I prefer books.  I visited a good library, looked at several Excel VBA Primers and borrowed the most promising to try at home.
You will also need to understand the Outlook Object model.  An Excel VBA tutorial will teach you about workbooks, worksheets, ranges, cells and so.  For Outlook, you need to understand stores, folders, mail items, calendar items and so on.  As I said, I have failed to find an Outlook VBA tutorial I like and I do not like the high recommended book I bought.  I learnt my Outlook VBA by experimentation.  Eugene has included explanations in his answer and I will include explanations in mine.  Hopefully between us we will give you enough of a start.  You might be lucky to find a post that explains topics A, B and C together.  I find it better to look up topics individually and then write experimental macros that combine them.  If you fail with an experimental macro, post it here with an explanation of what you are trying to achieve and what is going wrong; you will almost certainly get help.
To emulate your problem, I picked four suppliers that email me often enough to develop and test my monitoring code.  You say you use rules to move these emails to separate folders which seems a good idea to me.  Rules offer a number of classifications by which an email can be selected and I gather you can select these emails from your input stream.  Rules also offer a number processing options.  You have used "Move to a folder".  Another is "Run a script".  A script in this context is an Outlook VBA macro with a specific structure.  I was confident, I could create a macro to perform the monitoring you require.  However, there is a problem: Outlook runs the macro before it moves the email to the new folder.  This is not a big problem but it means you cannot use the rule to move the email.  You must get the macro to move the email which is not difficult.
I created a rule for each supplier for which the summary was:
Apply this rule after the message arrives
from Xxxxx
  and on this computer only
run Project1.Yyyyy
  and stop processing more rules

"Xxxxx" is the name of a supplier and "Yyyyy" is the name of the macro that will process the email.  I am a home user so "and on this computer only" has no effect for me but it might for you.  Without "and stop processing more rules" you will get messages saying the email cannot be found because Rule X moves the email then Rule Y cannot find it in Inbox.
Macro Yyyyy is of the form:
Public Sub Yyyyy(ByRef itm As MailItem)

  Call CountAndWarn("test folders\Xxxxx", itm, 2, 180, 3, 600)

End Sub

The names of the macros are not important.  Clearly if a rule says run macro Yyyyy there must be a macro Yyyyy but the value of Yyyyy is not important.  I named my macros after Outlook's names for the suppliers but you will presumably have to name them after the type of email.
The format of the first line, Public Sub Yyyyy(ByRef itm As MailItem) is more or less fixed for a macro to be run by a rule.  The first parameter must be the MailItem.  There are further optional parameters for which I have never had a use.
CountAndWarn is a macro I have written to process all these emails.  It has at least four parameters but can have six or eight or more if that would be helpful for a particularly type of email.
"test folders\Xxxxx" identifies the folder to which the email is to be moved.
If you look at your Outlook folder pane, you will see at least one name against the left edge.  Under that, but indented, will be system folders such as Inbox, Deleted Items, Sent Items and Outbox.  Under any of the system folders, you can have private subfolders.  You can also have private folders, at the same level as the system folders, any of which can have sub-folders and sub-sub-folders to any depth.  The name against the left edge identifies a store.  A store is a file in which Outlook stores emails, appointments, tasks and so on.  You will have at least one store into which your emails are loaded.  You may also have shared stores which can be public to your entire organisation or private to your team or department.  You can have at many private stores as you wish.
On my system, I have one store per email address (I have three) plus several private stores.  In "test folders\Xxxxx", "test folders" is the name of a private store I use for experimentation.  Within "test folders" I have created four folders, one per supplier I am monitoring.  Within each of these folders, I have a sub-folder "Old" which I will explain later.  So within my folder pane, I have a section that looks like:
test folders
  Xxxxx
    Old
  Wwwww
    Old
 Vvvvv
    Old
  Uuuuu
    Old

As I have said, "test folders\Xxxxx" identifies a folder.  The format of this string is "StoreName\FolderName\SubFolderName\SubSubFolderName …".  I have placed my folders in an experimental store; you have probably placed your folders in your main store.  You can place them anywhere you have write permission.  This string must specify the entire name of the folder starting with the store name.  Your names might be: "YourMainStore\Inbox\CPU Spikes" and "YourMainStore\Inbox\SQL Blocks".
Returning to Call CountAndWarn("test folders\Xxxxx", itm, 2, 180, 3, 600).
The second parameter, itm, passes the email to CountAndWarn so it can move the email to the specified folder.
The remaining parameters are one or more pairs of integers of which the first is a count of emails and the second is a number of minutes.  My parameter list means I wished to be warned if:

*

*2 emails have arrived in the last 180 minutes from supplier Xxxxx

*3 emails have arrived in the last 600 minutes from supplier Xxxxx

I do not receive many of these emails per day so my counts are low and my periods are long.  Your counts will be much higher and your periods much shorter.
I do not know if you might wish to monitor different periods but there was little extra code to allow for several periods so I included it.  You must have at least one count and one period but you can have as many extra pairs as you wish.  If you have multiple periods, they must be in ascending sequence with the longest period last.
The macro CountAndWarn does the following:

*

*Locate the named destination folder, for example, "test folders\Xxxxx".

*Locate the corresponding "old" folder, for example, "test folders\Xxxxx\Old".

*Move the email to the destination folder

*Count the emails in each period.  If an email is older than the end time of the last period, move it to the "old" folder so it is not checked every time a new email arrives.

*If any of the counts exceeds the maximum for its period, a message box like the following is displayed.

These macros could be ideal if all you want is an instant warning of every spike during the day.  Deficiencies include:

*

*While a spike continues, you will be warned about each new email.

*You will not be warned about a spike in the middle of the night.

The first deficiency could not be fixed without keeping records.  For example, macro CountAndWarn counts the emails in a folder and reports a high count.  It does not record that it warned you about the current spike ten seconds ago when the last email arrived.  Keeping records in a text file would not be difficult but you will need to think about what records will help you analyse the spikes.
Spikes in the middle of the night will require analysis of the old emails.  The current macro just counts emails in the last X minutes.  Reviewing last night's emails will involve counting the emails in every X minute period since close of play yesterday.  That analysis probably will not require any obscure VBA but will require some careful design.
Come back with questions, if you do not understand anything in the following macros:
Option Explicit
Public Sub Argos(ByRef itm As MailItem)

  Call CountAndWarn("test folders\Argos", itm, 2, 180, 3, 600)

End Sub
Public Sub Guardian(ByRef itm As MailItem)

  Call CountAndWarn("test folders\Guardian", itm, 1, 600, 2, 1200, 3, 1800)

End Sub
Public Sub Amazon(ByRef itm As MailItem)

  Call CountAndWarn("test folders\Amazon", itm, 2, 600)

End Sub
Public Sub Wayfair(ByRef itm As MailItem)

  Call CountAndWarn("test folders\Wayfair", itm, 2, 600)

End Sub
Sub CountAndWarn(ByVal FldrDestName As String, ByRef itm As MailItem, _
                 ParamArray CountPeriod() As Variant)

  Dim CountsCrnt() As Long
  Dim CountsTgt() As Long
  Dim FldrDest As Outlook.Folder
  Dim FldrDestNamePart() As String
  Dim FldrOld As Outlook.Folder
  Dim InxC As Long
  Dim InxCS As Long
  Dim InxFldrName As Long
  Dim InxItem As Long
  Dim LB As Long
  Dim Msg As String
  Dim NumCounts As Long
  Dim Periods() As Date
  Dim Recent As Boolean
  Dim Warn As Boolean

  FldrDestNamePart = Split(FldrDestName, "\")
  LB = LBound(FldrDestNamePart)   ' Should be zero but just in case

  ' Set FldrDest to Store
  On Error Resume Next
  Set FldrDest = Session.Folders(FldrDestNamePart(LB))
  On Error GoTo 0
  If FldrDest Is Nothing Then
    Debug.Assert False  ' Store doesn't exist
    Exit Sub
  End If

  ' Set FldrDest to destination folder
  For InxFldrName = LB + 1 To UBound(FldrDestNamePart)
    On Error Resume Next
    Set FldrDest = FldrDest.Folders(FldrDestNamePart(InxFldrName))
    On Error GoTo 0
    If FldrDest Is Nothing Then
      Debug.Assert False  ' Subfolder doesn't exist
      Exit Sub
    End If
  Next

  'Set FldrOld to the Old folder for FldrDest
  On Error Resume Next
  Set FldrOld = FldrDest.Folders("Old")
  On Error GoTo 0
  If FldrOld Is Nothing Then
    Debug.Assert False  ' No subfolder "Old" within destination folder
    Exit Sub
  End If

  ' Move new email from Inbox to FldrDest
  itm.Move FldrDest

  'Debug.Print "CountPeriod";
  'For InxCS = LBound(CountSince) To UBound(CountSince)
    'Debug.Print " " & CountSince(InxCS);
  'Next
  'Debug.Print

  ' Determine number of counts and periods in CountPeriod
  ' No check for an odd number of values in CountPeriod
  NumCounts = (UBound(CountPeriod) - LBound(CountPeriod) + 1) / 2

  ' Size arrays according to number of counts
  ReDim CountsCrnt(1 To NumCounts)
  ReDim CountsTgt(1 To NumCounts)
  ReDim Periods(1 To NumCounts)

  ' Initialise arrays and convert periods in minutes to a time
  InxC = 1
  For InxCS = LBound(CountPeriod) To UBound(CountPeriod) Step 2
    CountsTgt(InxC) = CountPeriod(InxCS)
    CountsCrnt(InxC) = 0
    Periods(InxC) = DateAdd("n", -CountPeriod(InxCS + 1), Now())
    InxC = InxC + 1
  Next

  'Debug.Print FldrDest.Name
  'Debug.Print "New " & itm.ReceivedTime
  For InxItem = FldrDest.Items.Count To 1 Step -1
    With FldrDest.Items(InxItem)
      'Debug.Print .ReceivedTime & " ";
      Recent = False
      For InxC = 1 To NumCounts
        If .ReceivedTime > Periods(InxC) Then
          CountsCrnt(InxC) = CountsCrnt(InxC) + 1
          Recent = True
          Exit For
        End If
      Next
    End With
    If Recent Then
      'Debug.Print "Index " & InxC & " Count " & CountsCrnt(InxC)
    Else
      'Debug.Print "Old: Moved"
      FldrDest.Items(InxItem).Move FldrOld
    End If
  Next

  ' Check counts to see if warning required
  Warn = False
  For InxC = 1 To NumCounts
    If InxC > 1 Then
      ' Add in count of more recent emails
      CountsCrnt(InxC) = CountsCrnt(InxC) + CountsCrnt(InxC - 1)
      'Debug.Print "CountsCrnt(InxC) := " & CountsCrnt(InxC)
    End If
    If CountsCrnt(InxC) >= CountsTgt(InxC) Then
      Warn = True
    End If
  Next

  If Warn Then
    ' At least one count in excess of maximum
    Msg = "Warning. Emails in " & FldrDestName
    For InxC = 1 To NumCounts
      Msg = Msg & vbLf & CountsCrnt(InxC) & " since " & Format(Periods(InxC), "ddd h:mm:ss")
    Next
    Call MsgBox(Msg, vbOKOnly)
  End If

End Sub


text:
Q: Run only one build per node on Jenkins, multiple pipelines Currently have multiple pipelines (A, B, C) on Jenkins with nodes (X, Y, Z). We enabled the Throttle Concurrent Builds plugin to make sure only one build from a pipeline is run on a single node.
The problem is, with this approach, builds from different pipelines can collide (for example, pipeline A could already be executing on node X, and we don't want any other pipelines executing on node X until pipeline A is done). The TCB plugin makes sure that multiple builds from a single pipeline doesn't run on one node, but it doesn't prevent multiple pipelines spawning one build on a single node.
How do I configure Jenkins so that nodes can only run one build, NOT per pipeline?

A: You can configure the Node to have just 1 executor. You can achieve this from:

Manage Jenkins -> Manage Nodes -> Select the node you want to restrict
  -> Set 'No of Executors to 1' -> Save.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show $x_i
I'm not getting how  to show the first half of the inequality  in the yellow highlighted text.
Please help!!

A: It follows from partition norm $\lt \delta$. That means $|x_{i-1} - x_i| \lt \delta$ which implies $x_{i} - x_{i-1} \lt \delta$


text:
Q: Exception Handling using while loop i am using postgreSql and Java , here is the error shown in eclipse console
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "km_rel_user_test_details_pkey",

Here the cause of the error is(i guess ) due to duplicate key present in database ,
I have written a while loop to handle this exception, i just want to know, whether this approach is correct and will work for every situation, any error found/ ask for improvement will be appreciated, thanks in advance, here is my java method.
 public String saveConceptTestDetails(String testId,String userId,String selected_ans, String check_user_save, String conceptTestOrder , int ans) {

    boolean isInserted=false;
    String newId1=null;
    while(!isInserted){
        try{
            newId1=getNextVal(DBKeys.SEQ_REL_USER_TEST_DETAILS); // this is what generatres new Id
            Hashtable resultHash=executeUpdate(new StringBuffer(" insert into "+DBKeys.TABLENAME_REL_USER_TEST_DETAILS+" ("+DBKeys.COLUMNNAME_REL_USER_TEST_DETAILS_ID+","+DBKeys.COLUMNNAME_REL_USER_TEST_DETAILS_TESTID+","+DBKeys.COLUMNNAME_REL_USER_TEST_DETAILS_USERID+","+DBKeys.COLUMNNAME_REL_USER_TEST_DETAILS_CREATEDDT+","+DBKeys.COLUMNNAME_REL_USER_TEST_DETAILS_MODIFIEDDT+","+DBKeys.COLUMNNAME_REL_USER_TEST_DETAILS_SELECTED_ANS+","+DBKeys.COLUMNNAME_REL_USER_TEST_DETAILS_CHECK_USER_SAVE_TEST+","+DBKeys.COLUMNNAME_REL_USER_TEST_DETAILS_TEST_TYPEORDER+","+DBKeys.COLUMNNAME_REL_USER_TEST_DETAILS_TEST_VERSION+","+DBKeys.COLUMNNAME_REL_USER_TEST_DETAILS_SAVEANS+")values ("+newId1+","+testId+","+userId+",current_date,current_date,"+selected_ans+","+check_user_save+","+conceptTestOrder+",0,"+ans+")"));
            isInserted=true;
        }
        catch (Exception e) {
            System.out.println("Exception");
            isInserted=false;
        }
    }
    return newId1;
  }

A: The reason for using a generator is to avoid this problem, it's supposed to make sure you get only unused ids. If you can't rely on that here, you could add a workaround:

*

*You could query first to find the maximum id in the table. If the generator allows setting a nextvalue then change it so it starts from there, otherwise call the generator over and over until you get a key higher than that maximum.

*You could write a query that gets the existing row numbers and have insert code check that the id is not in the list (assumes this is the only thing doing inserts).

*You could execute a select count before each insert to make sure the id is unused.
Reusing IDs used by previously-deleted rows, just so you can fill in the gaps, has the potential to cause confusion and should be avoided. It seems like a lot of trouble to go to with not much benefit. If you want sequential numbers then add a specific field for that.
Your exception-handling is not distinguishing between different kinds of SQLExceptions.
Not all your SQLExceptions will be from constraint violations; if you have something go wrong that is not related to your generated key (such as having the database go down, or filling up the transaction log) then your code will loop endlessly.
You can distinguish between different kinds of SQLExceptions based on their SQLState property. For Postgres, SqlStates starting with 23 refer to constraint issues.
If you want to catch constraint exceptions then you should check the sqlstate and rethrow the exceptions that don't match, so that they will end the process (because something went wrong that is nonrecoverable).
For SQLExceptions that extend SQLTransientException it might be worthwhile to retry them. That is about the only case where using a loop for inserts like this would be justified.
Your insert SQL does not seem to have its values quoted, where you are concatenating a value where are no single quotes surrounding it, so the result will not be correct (unless you're counting on single-quotes being included as part of the passed-in string). You'd be better off using PreparedStatements, they not only protect against SQL injection but also handle quoting of parameter values for you, so they are much less error-prone.

A: You will have endless loop if you have the same exception.
check which exceptions can be thrown by executeUpdate and add the appropriate catch blocks with appropriate messages.
Example:
   catch (PSQLException) {
        System.out.println("The key is already exist");
        isInserted=true;
    }
    catch (SQLException e) {
        System.out.println(e);
        isInserted=false;
    }catch (SQLTimeoutException e) {
        System.out.println(e);
        isInserted=false;
    }


text:
Q: Add 2 data files in pyinstaller and use them as variables in the function written in the script My aim is to create a one executable file using pyinstaller by converting a .py or .ipynb file. I'd like the user to enter their excel file pathway(2 files) when they run the exe file in their computer. The exe should then run my written python code which takes in their data files entered as my function arguments  for data manipulation purpose and return's my function output(manipulated csv file)  to the end-user using this application.
def manipulated_data(df,df5,df10):
    df2=df.copy()

    df4=df2.pivot_table(columns=df2[df2.columns[6]],index=df2[np.r_[df2.columns[0:6],df2.columns[9:17],df2.columns[18:]]],values=df2[df2.columns[7:9]],fill_value='')

    df4=df4.reset_index()

    #Combining multi-index names
    df4.columns = [' '.join(col).strip() for col in df4.columns.values]

    df7=df5.melt(id_vars=df5[df5.columns[0:5]],value_vars=df5[df5.columns[6:15]],value_name='Values')

    df7=df7.replace('Zone 9`','Zone 9')

    ind=df7.variable.unique()

    df8=df7.pivot_table(columns=df7[df7.columns[4:6]],
                    index=df7[df7.columns[0:4]]
                    , values=df7.columns[6],aggfunc=('first'),fill_value='')

    df8=df8.reindex(ind,axis=1,level=1)

    df8.columns = [' '.join(col).strip() for col in df8.columns.values]

    df8.reset_index(inplace=True)

    df9=pd.merge(df4,df8,how='inner',on=['Store ID','Store Name','State'])

    df9.fillna('',inplace=True)

    dfcoles=pd.concat([df9,df10], axis=0,ignore_index=False,sort=False)

    dfcoles.fillna('',inplace=True)

    coles_ind=df10.columns

    dfcoles=dfcoles.reindex(coles_ind,axis=1)

    return dfcoles

df_trial=pd.read_csv('C:/Users/Abdul.Qavi/Downloads/Day 14 data/Part 3.csv',keep_default_na=False)

df_part4=pd.read_csv('C:/Users/Abdul.Qavi/Downloads/Day 14 data/Part 4.csv',keep_default_na=False)

df_coles=pd.read_csv('C:/Users/Abdul.Qavi/Downloads/Coles Service SF.csv',keep_default_na=False)
 ##This file wouldn't be entered by the user. It would always be a part of the script.

dfx=manipulated_data(df_trial,df_part4,df_coles)

A: Based on my understanding of the question

*

*you want the user to input the path for 2 csv files

*read the files and pass it as an argument

*perform some operations using manipulated_data() function

*return/save the output - say in a csv file format.

The general version would look like this -
app.py
import pandas as pd
import os

def manipulated_data(df1,df2):
    #perform operations using df1 and df2
    #......
    #......
    #for example -
    df_coles = pd.concat([df1,df2], axis=0,ignore_index=False,sort=False)
    return df_coles

# get file paths from the user
path1 = input("enter path for the 1st file")
path2 = input("enter path for the 2nd file")

#read the csv files
data1 = pd.read_csv(path1)
data2 = pd.read_csv(path2)

#execute manipulated_data() function-
df_final = manipulated_data(data1,data2)

#create an output directory
if not os.path.exists('output'):
    os.makedirs('output')

#save csv file in the output directory or your prefered location
df_final.to_csv('./output/manipulated_data1.csv')

# Open excel to display the csv file
os.system("start excel output/manipulated_data1.csv")

# To prevent the app from closing abruptly -
input("Press enter to continue...")

And then create the application -
pyinstaller app.py

Side note - You can use os.getcwd() to read files from or save the file to the current directory.


text:
Q: PaperJS remove symbol from array I wanted to create a function which, by each call, creates another rain drop that falls down the screen and gets deleted when at the bottom.
So far I managed to do this with PaperJS, but as soon as I want to delete one rain drop when it hit the bottom, the whole funtion crashes, since it's losing an element in the array [i].

<script type="text/paperscript" canvas="myCanvas">

  // The amount of raindrops we want to spawn:
  var count = 0;

  // Drawing Layer for only the rain
  var rainlayer = new Layer();

  // Create a raindrop symbol, which we will use to place instances of later:
  var drop = new Path.Rectangle({
   x: 0,
   y: 0,
   width: 2,
   height: 16,
   fillColor: 'white',
   opacity: 1
  });
  var symbol = new Symbol(drop);

  // Place the instances of the symbol when this function is called:
  function placeDrops(drops)
  {
   for (var i = 0; i < drops; i++) {
    // The center position is a random point in the top of the view:
    var center = new Point(Math.random()*view.size.width, 0);
    var placedSymbol = symbol.place(center);
   }
  }

  // The onFrame function is called up to 60 times a second:
  function onFrame(event) {
   // Run through the rainlayer's children list and change the position of the placed symbols:
   for (var i = 0; i < count; i++) {
                    // safe the current rain drop as the item var so we don't have to type too much code
        var item = rainlayer.children[i];
     // Move the item 5 times of its width to the bottom.
     item.position.y += item.bounds.width * 5;
     // If the item has left the view on the bottom, remove it from the canvas
     if (item.bounds.bottom > view.size.height) {
                        //!!!
                        //THIS IS WHAT CAUSES THE ERROR 'TypeError: item is undefined' as soon as
                        //the first rain drop hits the bottom
                        //!!!
      item.remove();
      rainlayer.removeChildren(i);
     }
    }
  }

  function onMouseDown(event)
  {
   count = count + 1;
   placeDrops(1);
  }
</script>

As soon as the first rain drop hits the bottom, it gets removed (as it should) but then as the loop comes to its position again, there is no rainlayer.children[i]; left at this position which can be saved to the var item, so I get the console error TypeError: item is undefined from my understanding of this.
I'm pretty new to all this, so there might been an easier way to make things happen or to solve this error. Thank you very much for your help!

A: I believe the problem is that you remove all the children from rainlayer with the line rainlayer.removeChildren(i).
You only want the line item.remove() - that removes the item from the project so it is no longer in the layer. There is no need to remove children from the layer.
rainlayer.removeChildren(from [, to]) is the syntax with an argument so it removes all children from the layer when called with from = 0.


text:
Q: how to check if the post id has a new comment? how to check if the post id has a new comment?
this is something goes on my mind
if (hasnewcomment(post->id)){
//echo something
}

any suggestion or help will do.
using get the total comment
or anything
please help
thankyou

A: There is a WordPress hook comment_post to retrieve recently added comment and to pass comment id to get_comment you will get the post id.

add_action( 'comment_post', 'show_message_function', 10, 2 );

function show_message_function( $comment_ID, $comment_approved ) {

  $comment_array = get_comment($comment_ID );

  $comment_post_id = $comment_array->comment_post_ID;
}

A: As standard if you turn on manual comment moderation in Settings: Discussion the author of a post will be emailed whenever a comment to their post is made.


text:
Q: Redireccionar cuando se pulsa un boton en Laravel estoy haciendo un login y register en laravel con vue. La idea es que cuando pulse el botón de registrarte, te redireccione al login y cuando pulses el boton de login, te redireccione al home (obviamente si se cumple).
Este es el controlador, se supone con la instrucción de return, te mandaría al login, pero no lo hace.
public function register(RegisterRequest $request){
    $user = User::create($request -> validated());
    return redirect('/login');
}

Y este es el fragmento de codigo de la vista en vue, donde mando por axios el request al controlador
axios.post('/register', this.form)
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          console.log(error);
        });

Por que no me redireccionara y como lo puedo hacer que funcione? Gracias

A: Estas realización una petición POST mediante Javascript, por lo que el servidor siempre te devolverá un valor pero por mucho que trates de hacer un redireccionamiento no te va a funcionar.
En este caso debes hacer el redireccionamiento en tu lado de cliente, en este caso cuando haces la llamada POST.
Antes de nada tendrías que cambiar la respuesta de tu controlador.
public function register(RegisterRequest $request){
    $user = User::create($request -> validated());

    if($user) {
      response('El usuario se ha registrado correctamente', 200)
    } else {
      response('El usuario no se ha podido registrar', 403)
    }
}

Puedes obtener más información de response en la documentación oficial de Laravel
Una vez modificada la respuesta del lado de servidor procedemos a manejar los datos en el componente de Vue
axios.post('/register', this.form)
  .then((response) => {
     // Si se cumple el registro redireccionas el usuario al login.
     window.location.href = "/login";
  })
  .catch((error) => {
     // En caso de que no se complete el registro muestra el mensaje de error que necesites
     console.log(error);
  });

De este modo que si se devuelve un error en el servidor podrás gestionarlo con VueJS con facilidad desde la petición axios.


text:
Q: Karma gives me a __karma__.start adapter error without any other error I don't know how to fix this issue. I get no errors other than the one above. Here are my config files:
./webpack.config.js
var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: './src/app/app.jsx',
  output: { path: __dirname, filename: 'app.js' },
  port: 9090,
  devServer: {
    contentBase: './src',
    hot: true,
    port: 9090,
    publicPath: '/assets/',
    noInfo: false
  },
  resolve: ['.js', '.jsx', ''],
  module: {
    loaders: [
      {
        test: /.jsx$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};

./karma.conf.js
var webpackConfig = require('./webpack.config');
webpackConfig.devtool = 'inline-source-map';

module.exports = function(config) {
  config.set({

    frameworks: ['mocha', 'chai', 'sinon', 'sinon-chai'],
    plugins: [
        'karma-chrome-launcher',
        'karma-mocha',
        'karma-chai',
        'karma-sinon',
        'karma-sinon-chai',
        'karma-sourcemap-loader',
        'karma-webpack'
    ],
    files: [
      'tests.webpack.js'
    ],
    exclude: [],
    preprocessors: {
        'tests.webpack.js': ['webpack', 'sourcemap']
    },

    webpack: webpackConfig,
    webpackMiddleware: {
        noInfo: true
    },

    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_DEBUG,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: true,
  });
}

./tests.webpack.js
'use strict';

require('babel-polyfill');
require('core-js/fn/object/assign');

var context = require.context('./test', true, /Test\.jsx$/);
context.keys().forEach(context);

An example test file (test/app/AppTest.jsx):
'use strict';

var TestUtils = require('react-addons-test-utils');
import {expect} from 'chai';

describe('App', () => {

    it('should display correct text on render', () => {
        let component = TestUtils.renderIntoDocument(<App/>);
        expect('hello').to.equal('hello');
    });

});

Here is karma debug output (I removed the times, so it was more readable):
DEBUG: [config]: autoWatch set to false, because of singleRun
DEBUG [plugin]: Loading plugin karma-chrome-launcher.
DEBUG [plugin]: Loading plugin karma-mocha.
DEBUG [plugin]: Loading plugin karma-chai.
DEBUG [plugin]: Loading plugin karma-sinon.
DEBUG [plugin]: Loading plugin karma-sinon-chai.
DEBUG [plugin]: Loading plugin karma-sourcemap-loader.
DEBUG [plugin]: Loading plugin karma-webpack.
DEBUG [web-server]: Instantiating middleware
DEBUG [preprocessor.sourcemap]: base64-encoded source map for /Users/gasim/Stack/gasim/gasim-frontend/tests.webpack.js
INFO [karma]: Karma v1.1.0 server started at http://localhost:9876/
INFO [launcher]: Launching browser Chrome with unlimited concurrency
INFO [launcher]: Starting browser Chrome
DEBUG [temp-dir]: Creating temp dir at /var/folders/0q/z4cbhb7x49jgk2ycw4f9hxd00000gn/T/karma-37005516
DEBUG [launcher]: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome --user-data-dir=/var/folders/0q/z4cbhb7x49jgk2ycw4f9hxd00000gn/T/karma-37005516 --no-default-browser-check --no-first-run --disable-default-apps --disable-popup-blocking --disable-translate --disable-background-timer-throttling http://localhost:9876/?id=37005516
DEBUG [web-server]: serving: /Users/gasim/Stack/gasim/gasim-frontend/node_modules/karma/static/client.html
DEBUG [web-server]: serving: /Users/gasim/Stack/gasim/gasim-frontend/node_modules/karma/static/karma.js
DEBUG [karma]: A browser has connected on socket /#ZLT5diBbmtOJweMIAAAA
DEBUG [web-server]: upgrade /socket.io/?EIO=3&transport=websocket&sid=ZLT5diBbmtOJweMIAAAA
DEBUG [web-server]: serving: /Users/gasim/Stack/gasim/gasim-frontend/node_modules/karma/static/favicon.ico
INFO [Chrome 51.0.2704 (Mac OS X 10.11.5)]: Connected on socket /#ZLT5diBbmtOJweMIAAAA with id 37005516
DEBUG [launcher]: Chrome (id 37005516) captured in 2.52 secs
DEBUG [middleware:karma]: custom files null null
DEBUG [middleware:karma]: Serving static request /context.html
DEBUG [web-server]: serving: /Users/gasim/Stack/gasim/gasim-frontend/node_modules/karma/static/context.html
DEBUG [web-server]: serving: /Users/gasim/Stack/gasim/gasim-frontend/node_modules/karma/static/context.js
Chrome 51.0.2704 (Mac OS X 10.11.5) ERROR
  You need to include some adapter that implements __karma__.start method!

What really interests me is the following line in the debug output:
DEBUG [middleware:karma]: custom files null null

Why does it say null null? Does this mean files for tests are empty or something?

A: The problem here in this line here:
frameworks: ['mocha', 'chai', 'sinon', 'sinon-chai'],

There is no need to include chai or sinon. They were the ones giving me errors. So, I only kept mocha and sinon-chai and I just load chai and sinon from within my test scripts.


text:
Q: Can I use parallel python 2.7 and python 3.7 in the same Intellij project directory? I use in my Intellij (Ultimate 2019.1) project python 2.7 and 3.7 in the same directory.
If I set projectdir > File > Project structure > Project Settings > Facets > Python > Python Interpreter > Python 2.7
My python 2.7 files show syntax OK but python 3.7 are wrong.
If I change the Interpreter to Python 3.7 my python 3.7 are fine the 2.7 not?

A: Python code cannot be mixed. All libraries and code should support the version you are working with. If some is not compatible with that version you can not use that code.
Always use libraries that are compatible with the python version you are using.


text:
Q: Firebase reCAPTCHA has already been rendered in this element Authenticate with Firebase with a Phone Number (JS) requires a mandatory reCAPTCHA verifier, it takes the ID of the container. For the ID of the container, I am generating a random one -

firebase_recaptcha_container: "recaptcha-container",

firebase_recaptcha_reset: function() {

            if (typeof appVerifier != "undefined") {
                appVerifier.reset()
                appVerifier.clear()
            }

            let id = loadJS.firebase_recaptcha_container

            let newID = loadJS.randomString(10)
            $("#"+id).contents().remove()
            $("#"+id).prop("id", newID)
            loadJS.firebase_recaptcha_container = newID
            return newID

        }

then requesting for the RecaptchaVerifier and upon receiving I set this as a global variable window.appVerifier .

firebase_recaptcha: function(name_r="default") {
            let promiseD = new firebase.auth.RecaptchaVerifier(name_r, {
                'size': 'invisible',
                'callback': function(response) {
                    resolve(response)
                },
                'expired-callback': function(r) {
                    console.log("expired", r)
                },
                'isolated' : false
              });

            return promiseD
        },

_____________________

let container_recaptcha = $utils.firebase_recaptcha_reset()

window.appVerifier = await $utils.firebase_recaptcha(container_recaptcha)

It works totally fine for the very first time. But its a honest mistake for users not to use correct phone number. So for next time, I am doing the same thing again and getting error while generating the RecaptchaVerifier -

reCAPTCHA has already been rendered in this element

Which sadly does not make sense as the new element is totally different and also clear, reset methods were called following the documentation. I am neither using any other reCaptcha on this page. Refreshing the page might be a possible solution but that I really hate. Any insight would be helpful.
Thanks!

A: Finally found the solution, looks like it was a stupid mistake!
Invoking firebase.auth.RecaptchaVerifier adds new recaptcha scripts, every time! Hence all needed to be done is, calling it once, it does the rest on its own.

A: This won't get fixed just by implementing recaptchaVerifier.clear() method.
In the callback where you are passing this appVerifier, you'll have to implement the above clear method and add that "recaptcha-container" using ref
The below would be the element in render method:

GenerateCaptcha function:
  const generateRecaptcha = () => {
appVerifier = new RecaptchaVerifier(
  "recaptcha-container",
  {
    size: "invisible",
  },
  authentication
);

Inside submit Callback:
if (appVerifier && recaptchaWrapperRef.current) {
        appVerifier.clear();
        recaptchaWrapperRef.current.innerHTML = `<div id="recaptcha-container"></div>`;
      }

      // Initialize new reCaptcha verifier
      generateRecaptcha();


text:
Q: Call a C++ function from C A very simple question. I was trying to call a c++ function from a c file. I always seem to get "undefined reference to the function" error.
C file:
test.c
#include "link.h"
#include <stdio.h>

int main(){
    print();
    return 0;
}

C++ file:
print.cpp
#include <iostream>
#include "link.h"

extern "C"
void print(){
   std::cout<<"hello from cpp";
}

Header file:
link.h
 #ifndef HEADER_FILE
 #define HEADER_FILE

 #ifdef __cplusplus
     extern "C" {
 #endif
         void print();
 #ifdef __cplusplus
     }
 #endif

 #endif

I don't know what's wrong with the above code. Also, how do I compile the above in terminal? I'm assuming I need to use the gcc compiler (gcc -o test test.c link.h)
Any inputs will be highly appreciated. Thanks,


text:
Q: I changed Volumegroup name via Webmin, now I can't boot. Stuck on initramfs I will summarise how I created this error.
I created a lvm, then changed the name of volumegroup. It was ubuntuvm-vg I renamed it ubuntuvmvg. I mounted lvm volume fine and to make sure it also auto mounts I rebooted my ubuntu server running on Vmware. Now I'm stuck on initramfs screen.
This is my test server, there's nothing important in it. But instead of reinstalling the server I'd rather know how to fix this issue.
Here's a screenshot if that helps
http://i.imgur.com/WcdhCVF.png

A: You need to update initramfs
First start from a live USB-Device or DVD.
You need to install lvm:
$ sudo apt-get install lvm
Now mount it:
$ sudo mount /dev/sdX /mnt
where X is your ubuntu partition.
Change into your ubuntu system:
sudo mount -o bind /dev /mnt/dev
sudo mount -o bind /sys /mnt/sys
sudo mount -t proc /proc /mnt/proc
sudo cp /proc/mounts /mnt/etc/mtab
sudo chroot /mnt /bin/bash
sudo update-initramfs -k all -u
sudo reboot
Now it should work.


text:
Q: why the size of string is same as number of char but length is one more than number of char? I used the following code:
#include <stdio.h>
#include <string.h>
void main()
{
  char c[] = {'J', 'O', 'H', 'N'};
  printf("size (bytes)=%d\n", sizeof(c));
  int len = strlen(c);
  printf("Length = %d\n", strlen(c));
  printf("%s", c);

The output size of the string is 4, but the length is 5. is the string not supposed to have /0 at the end? So the output size of the string should be 5, but the length is 4.
If I write code as char c[] = {'J', 'O', 'H', 'N', \0}; or c[] = "JOHN" then I got output size of the string is 5, the length is 4

A: In C, a string is a sequence of character values including a 0-valued terminator - the string "JOHN" would be represented as the sequence {'J', 'O', 'H', 'N', 0 }.
Strings are stored in arrays of character type - because the you need to store the terminator in addition to the characters of the string, the size of the array has to be at least one more than the length of the string.  IOW, to store the 4-character string "JOHN" you need an array that's at least 5 elements wide.
Had you initialized the array as
char c[] = "JOHN";

then the terminator would have properly been accounted for.
If the terminator isn't present, then what you have isn't a string and the various str* library functions won't handle it properly.  In your case above, strlen looked through the elements {'J', 'O', 'H', 'N'} and didn't find the 0 terminator, so it kept looking past the end of the array until it saw a zero-valued byte.

A: The definition of a string in C is that it is an array of characters, terminated by a null character, or '\0'.
You wrote:
char c[] = {'J', 'O', 'H', 'N'};

So let's see.

*

*array of char: ✅

*terminated by a null character: ❌

So c is not a string.  So it's not valid to call strlen on it, and it's not valid to print it out using printf's %s format.
You could make it a proper string by changing the initialization to:
char c[] = {'J', 'O', 'H', 'N', 0};

or equivalently
char c[] = {'J', 'O', 'H', 'N', '\0'};

Or it would be easier and clearer to just write
char c[] = "JOHN";

When you use a string literal (that is, a string in double quotes) as an initializer for a character array like that, the compiler automatically does exactly the same thing for you as if you had written {'J', 'O', 'H', 'N', '\0'};, but it's obviously a lot less typing.


text:
Q: How to cancel previous fetch request in new fetch request in react? I have a situation where I need to do an API request on each character change of input in react. When I type 3 letters 3 API requests are triggering. But there is no order of finishing the requests. Most of the time my last request is finishing first and then the old requests. As per my requirements, I want to cancel any previous calls before a new API call.

A: I found a way to cancel the previous request and accept only the response from the latest request. I am using redux-thunk as the middleware. I can use a controller as AbortController and send a signal to the fetch request and then I can cancel the previous request using this controller.

return (dispatch, getState, serviceManager) => {

      const { controller } = getState();

      controller.abort(); //cancel the previous request

      let newController = new AbortController();
      let signal = newController.signal;

      //set a new AbortController instance to the reducer
      dispatch({type: "SET_NEW_CONTROLLER", payload: newController})

      //pass the signal to the fetch request
      const result = await fetch(url, {...options, signal});
}

you can store a instance of AbortController in the reducer and beginning of the request you can simply abort the controller and set the new controller to the reducer and pass the signal to the fetch request.


text:
Q: Why does adding 6.1 seconds display as having added 6.099? Why does adding 6.1000000 seconds to a DateObject display as having added 6.099?

If I copy the Out[20] element from this picture, it contains the correct value:
DateObject[{2014, 11, 7}, TimeObject[{8, 0, 6.1}], CalendarType -> "Gregorian"]

...but why does it display as 6.099 instead of 6.100?
More to the point, how can I make it display the correct answer?

A: This is the only 'fix' I could find.
Initialize the following:
$DateStringFormat = {"Year", "-", "Month", "-", "Day", "T", "Hour", ":", "Minute", ":", "SecondExact"};

System`DateStringDump`convertDateStringForms[{__, s_}, _, _, "Millisecond"] :=
  ToString[Floor[1000000 Round[FractionalPart[s], .00001]]]

Run your command:
DateObject[{2014, 11, 7, 8, 0, 0}] + Quantity[6.100000, "Second"]

A: This boils down to floating point error.
In binary, 0.1 does not have a finite decimal expansion, so your computer must round.
This is a problem at a hardware level and can only be fixed by setting a precision higher than machine precision.
Here is what the fractional part of your float really looks like:
FractionalPart[6.1] // FullForm
(* 0.09999999999999964` *)

Here is what the fractional part of a higher precision number looks like:
FractionalPart[6.1`20] // FullForm
(* 0.1`18.214670164989236 *)

(The number after the ` is the precision)

A: Here is the answer that, with @Chip's and @Michael's help, I came to:
$DateStringFormat = {"Year", "-", "Month", "-", "Day", " ", "Hour", ":", "Minute", ":", "Second", ".", "Foo"};
System`DateStringDump`convertDateStringForms[{__, s_}, _, _, "Foo"] := Module[{n = 6}, StringTake[ToString[PaddedForm[N[Round[s, 10^-n]], {30, n}]], -n]];
DateObject[{2014, 11, 7, 8, 0, 0}] + Quantity[6.100000, "Second"]
DateObject[{2014, 11, 7, 8, 0, 0}] + Quantity[6.0000107, "Second"]
DateObject[{2014, 11, 7, 8, 0, 0}] + Quantity[6.0000108, "Second"]
DateObject[{2014, 11, 7, 8, 0, 0}] + Quantity[6.12345671, "Second"]
DateObject[{2014, 11, 7, 8, 0, 0}] + Quantity[6.12345672, "Second"]

Still, two things bother me: (1) I can't find documentation about "DateStringDump" in the Mathematica documentation, or anywhere on Google! (2) Why does Round[_,10^-6] yield .0000107→.000010 and .0000108→.000011; and why .12345671→.123456 and .12345672→.123457? I see no pattern here. ...Maddening.


text:
Q: Get gcc version and store it in a variable in batch file I have my gcc compiler inside 'D:/Cygwin/bin' .
I created a batch file for deriving the version number of the gcc.
set gccPath=D:/Cygwin/bin
for /f %%i in ('%gccPath%/gcc.exe -v') do @set versionInfo=%%i
if defined versionInfo (echo found) else ^
echo not found

Here i am trying to store the output of the statement gcc -v to the variable versionInfo. But when i run this batch file, the output of the command is not stored in the variable. How can i store the information to the variable versionInfo?.

A: set "gccPath=D:\Cygwin\bin"
set "versioninfo="
for /f %%i in ('%gccPath%\gcc.exe -v') do if not defined versioninfo set versionInfo=%%i
if defined versionInfo (echo found) else (echo not found)

\ is path-separator on windows; / is switch-indicator.
You appear to have a trailing space on the set gccpath line. This would be included in the value assigned. The format with quotes is designed to prevent this exact thing - trailing spaces are not included in the value assigned.
The @ is not required in a set (or any other) statement. @echo off is the traditional start to a batch - it means "turn echo off and don't echo this statement".
Batchers rarely use the ^ terminal to continue lines. I'd advise against it.
The extra if not defined statement gating the setting of the variable ensures that the variable is set but once and if there are no further lines (you haven't shown us a typical output from gcc -v) the set is ignored, otherwise it would be overwritten by whatever is on the next line


text:
Q: How to rephrase this sentence in order to be more American style? I want to rephrase this sentence:

A challenge that it needs to address is how to best
      perform feature selection.

If the sentence looks like this, how to rephrase it:

A challenge that it needs to address is how to best
      perform feature selection in order to ...

it refers to a new method. Can anyone give me a help?

A: Get rid of the fluff.  Get to the point.

Feature selection needs to be addressed.

An economical and understated style popularized by American author Ernest Hemingway.

A: I would use a more conventional word order and get rid of the passive "is". "It needs to address the challenge of how to best perform feature selection..."


text:
Q: Wait for script to finish before starting function In a Wordpress page I have a Wordpress plugin (Showoff) that loads DOM elements onto the page. I want to create a way to link to these DOM elements from outside that page using this code:
var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

var gotoProduct = function gotoProduct() {
    var productID = getUrlParameter('product');
    var showoffInit = showoff().init;
    if ($(productID).length) {$('.'+productID).click();}
}

but any link will be invalid unless all the DOM elements have been loaded. I tried various methods posted here but none seem to work for me. I think part of the problem might be that the code called by the plugin is called after the DOM is ready only.
So I need to find a way to wait for these DOM elements to finish loading before calling my function.
Any suggestions will be most welcome!

A: You can try .load() method of jquery to check whether the DOM element is already loaded then call your method.
$(window).load(function() {
   //perform required call
});

Hope this might help.


text:
Q: How to set timeout for gcc compilation of .c file on linux I am trying to compile a C code through my php script using gcc on a linux machine. But if the C code contains an infinite loop , the compiler gets stucked.
my PHP script goes like this ..
shell_exec('gcc input.c -o output 2> compile.txt');
$output=shell_exec('./output');

The 'input.c' file goes like this..
#include<stdio.h.
void main()
{
      while(1)
      prinf("This is infinite loop");
}

When I compile the PHP code , it gives an
**PHP Fatal error:  Out of memory (allocated 403177472) (tried to allocate 804896768 bytes)**

I've tried timeout 5s :
    $output=shell_exec('./output');
but it doesn't work although it works if i do ..
 int i;
 while(1)
 {
      scanf("%d",&i);
 }

..in my input.c file. I have seached a lot but in vain..
What am I doing wrong.?

A: The first point is that, it is not the compiler which is getting stuck. The compiler compiles code fine. It is during execution that your code is going into a infinite loop. So, incase of your first code, it just keeps executing without any pause or exit and hogs the CPU all the time which gives a feeling of "being stuck".
With regard to how your second code works, it is because you are pausing for getting an input. But, again, in that case, you have failed provide an exit for your program. So, effectively, the second code is same as your first code, but it just doesn't hog the CPU.
There is only one way for you to correct this problem, that is by modifying your 'C' code not to have an infinite loop without any exit.
Example:
int i;
while(1)
{
  scanf("%d",&i);
  if(0 == i)
  {
    break; //Just an example as to how you can exit from an infinite loop
  }
}

A: You can use ulimit in the invocation of the program. E.g. the following will limit output to 1 second of CPU time:
shell_exec("ulimit -t 1; ./output")

It might be a good idea to limit other resources too, so that output can't use all your memory etc.
(Note that this limits CPU time, not absolute time. If you want to do that, you should look at a program like timelimit, which would be called like shell_exec("timelimit -T 1 ./output"), I think.)

A: Jay explains much of it very well. The rest of it is that your first program not only goes into an infinite loop, but also produces an infinite amount of output, all of which you try to store in $output. I'd say you're lucky you didn't crash your computer, but PHP probably saved you with a built-in memory limit.

A: What you are looking for is possible theoretically:
You can read about the halting problem
However, you can probably use something like PHP's set_time_limit


text:
Q: IntelliJ IDEA hangs while "Finished, saving caches" Each time I do a make (a Java project) in IDEA, the compile process is hanging stating "Finished, saving caches". I have to kill this process before I can continue. I tried to use File -> Invalidate Caches without success.
Any ideas?

A: According to JetBrains,

IntelliJ IDEA caches a great number of files, therefore the system cache may one day become overloaded. In certain situations the caches will never be needed again, for example, if you work with frequent short-term projects. Also, the only way to solve some conflicts is to clean out the cache.

Go to the menu File | Invalidate Caches/Restart and take it from there.
https://www.jetbrains.com/help/idea/2016.3/cleaning-system-cache.html

A: One more workaround is adding your mac's hostname to /etc/hosts file along with localhost like the following:
127.0.0.1 localhost <hostnameOfMac>
::1       localhost <hostnameOfMac>

This solved the problem for me.

A: I got this same problem after installing Bitdefender.
The suggestion with adding those lines in /etc/hosts doesn't solve it in my case.

A: I'm in the same boat as RBrink.  Company recently installed Bitdefender on all Macs and the hostname solution doesn't work.
Only workaround I've been able to use to get me past it is to simply click the little 'X' next to where is says "Finished, saving caches".  It's annoying, but it works.  Wish there was a better option, but I can't for the life of me figure it out.

A: A colleague of mine also had this problem during debugging (Intellij frozes on 'finished, updating caches'). His server was configured to  'update classes and resources' on the 'on frame deactivation' option. Once he set this option to 'Do nothing' he could switch to another program to look something up and continue to debug later on.

A: Just based on circumstances, I get the impression it might be SBT related. When I have sbt running in intellij (to run a play server), I get this issue. If I restart intellij, the issue goes away.
Admittedly, its hard to prove this connection, but after three uses of this solution, it appears valid.
(The hosts solution did not work for me)

A: @manyata-goyal 's solution worked for me.
Adding steps for those who are trying this on a Windows system:

*

*Get your hostname: Go to My PC -> Properties (System Properties) -> scroll down to 'Full computer name' -> copy the full computer name

*Edit hosts file: Go to C:\Windows\System32\drivers\etc open hosts file

*Uncomment the lines and add hostname as mentioned in the answer above


text:
Q: Swift 5 storing and passing KeyPaths Let's say I have the following class:
class User: NSObject {
  var name = "Fred"
  var age = 24
  var email = "fred@freddy.com"
  var married = false
}

I want to be able to write a generic function that takes in a list of KeyPaths for a known class type, read the values and print to screen. The problem is, the I can't get the following code to compile as the type of the KeyPath's Value is not known, and will be different for each time. What do I have to do to make this work generically?
Consider the following:
struct KeyPathProperties<T> {
  var name: String
  var relatedKeyPaths: [KeyPath<T, Any>]
}

extension KeyPath where Root == User {
  var properties: KeyPathProperties<Root> {
    switch self {
      case \Root.name:
        return KeyPathProperties(name: "name", relatedKeyPaths: [\Root.age, \Root.email])
      default:
        fatalError("Unknown key path")
    }
  }
}

This line fails to compile:
return KeyPathProperties(name: "name", relatedKeyPaths: [\Root.age, \Root.email])

with this error:
Cannot convert value of type 'KeyPath<User, Int>' to expected element type 'KeyPath<User, Any>'
This is what I wish to be able to do, for instance:
let myUser = User()

var keyPathProps = KeyPathProperties(name: "name", relatedKeyPaths: [\User.age, \User.email])

for keyPath in props.relatedKeyPaths {
  print("Value: \(myUser[keyPath: keyPath])")
}

The above won't compile of course. Essentially I want to store keyPaths in an array at runtime, so I can generically at some point in time get values out of the User. I need to know if I can re-write the above in some way where the compiler can safely and correctly determine the type of the keyPath's value at runtime.
This is a conceptual use case for a much more complex architectural issue I'm trying to solve with hopefully less code.
MORE INFORMATION:
At runtime I wish to keep track of the properties that get modified - these properties are held in a modifiedProps array in each object / instance. At some point at runtime, I wish to be able to enumerate over this array of KeyPaths and print their values like so:
for modifiedKeyPath in self.modifiedProps {
  print ("\(self[keyPath: modifiedKeyPath])"
}

In short - I need to be able to capture the generic type of the KeyPath within KeyPathProperties. How do I achieve this?
SIDE NOTE: I can already easily achieve this by using Swift 3 style string based KeyPaths (by adding @objc to the class properties). I can store an array of keyPaths as strings and later do:
let someKeyPath = #keyPath(User.email)
...

myUser.value(forKeyPath: someKeyPath)

I just cannot do this with Swift 4 KeyPaths generically.

A: The error tells you what your misconception is:
Cannot convert value of type 'KeyPath<User, Int>'
    to expected element type 'KeyPath<User, Any>'

You seem to think that you can use a KeyPath<User, Int> where a KeyPath<User, Any> is expected, ostensibly on the grounds that an Int is an Any. But that's not true. These are generic types, and generic types are not covariant — that is, there is no substitution principle for generics based on their parameterized types. The two types are effectively unrelated.
If you need an array of key paths regardless of their parameterized types, you would need an array of PartialKeyPath or AnyKeyPath. It seems that in your use case the root object is the same throughout, so presumably you want PartialKeyPath.


text:
Q: How can I filter an MVC Telerik Grid using a selected value of a Telerik ComboBox? I have an ASP.NET MVC 3 page (Razor) that consists of a Telerik ComboBox and a Telerik Grid. I cannot figure out how to get values from the combo box using jquery and then use the value to filter (or rebind) the grid data.
My Telerik ComboBox is loaded with *category_id*, *category_name*, and I've got it coded so that it filters itself on the fly as I type the category_name until a perfect match is found or I select an item.
Any guidance about the best way to do this, or tips about making jquery easier (intellisense for jquery?) would be appreciated.
Here is one code section of jquery code that results in an error, and the page will not load any data. The error message (from firebug) is: $("#Customers").data("tComboBox") is undefined, but I'm doing this exactly as described on the Telerik site, and when I looked at the page source I saw this:
 jQuery('#Categories').tComboBox...snipped the  rest

Here is my function that fails:
 function dataBinding(args) {
   var categoryName = $("#Customers").data("tComboBox").value();
   args.data = $.extend(args.data, { categoryName: categoryName });
}

A: You can add intellisense for jQuery, read this post for how to do it:
jQuery Intellisense Setup
To retrieve the selected value from the Telerik Combo Box do the following:
View Markup
// Assumed defenition of the combobox
<%= Html.Telerik().DropDownList()
        .Name("DropDownList")
        .BindTo(new SelectList(Model, "ProductID", "ProductName"))
        .HtmlAttributes(new { style = "width: 200px; float: left; clear:both; margin-bottom: 230px;" })
%>

Client Script
// Will Get Selected Text
$("#DropDownList").data("tDropDownList").text()
// Will Get Selected Value
$("#DropDownList").data("tDropDownList").value()

To clarify further "DropDownList" in $("#DropDownList").data("tDropDownList").text() is the name assigned to the control in the helper method (Html.Telerik().DropDownList().Name("DropDownList")) so you should change the code you posted above to $("#Customers").data("tCustomers").value() and it should work.
PS:More information on Telerik ASP.NET MVC ComboBox API can be found at Telerik API


text:
Q: A file which may contain Python tests was detected in the ... workspace, but the test framework is disabled I'm working in Visual Studio Community 2019 v. 16.9.3. I'm on Windows 10. I recently starting getting this message in Visual Studio.

A file which may contain Python tests was detected in the ... workspace, but the test framework is disabled

If I close it out it doesn't seem to have any effect on any of my scripts. But, every time I start up Visual Studio and choose the folder to work from where my python 3x scripts reside I get this message.
I also have a few python environments to choose from. If I switch between environments the message doesn't go away.
I'm wondering if clicking "Don't show this message again" is the best option. As far as I know I've never used pytest or unittest for that matter, nor am I even sure how to implement them. The programs I write are pretty much used for simple automation.

A: I also started getting the same notification once I created a Python project that contained "Test" in the project name.
After searching a little bit I found that two testing frameworks, namely pytest and unittest, are supported for Python in Visual Studio from version 16.3.
You can set up unit testing anytime, hence, if you don't wish it now you can select "Don't show this message again". More details are at:
Set up unit testing for Python code


text:
Q: How to run programs in python2 and python3 I have python 2.6.6 and python 3.1.3 currently installed on my machine (Windows Vista 64 bit)
My path variable includes the directory of both versions. How can I specify which python I want to run a program in. For instance, if I want to run a program in python 3, it works but if I want to run a different program in python2 I get a syntax error. So how can I run a python 2 program in the cmd?
Typing python in my command line, python 3.1.3 is the only one that shows up.

A: You can specify the version in the executable name python2.6 and python3.

A: Instead of just typing "python" on the command line, use the full path the python.exe that you want to run: FULL_PATH_TO_PYTHON_2.6.6\python.exe or FULL_PATH_TO_PYTHON_3.1.3\python.exe should distinguish between the two.

A: The Python Launcher is probably what you need.  I used it with 2.7 and 3.2.

A: You can also use: 'py -main_version script_name.py args'
Example:
py -2 script_name.py args for Python 2.X
py -3 script_name.py args for Python 3.X
To test both are working or not, you can try,
>> py -2
Python 2.7.16 (v2.7.16:413a49145e, Mar  4 2019, 01:37:19) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>> py -3
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

A: The shell will read the PATH from left to right, so you most likely defined Python 3.1.3 before Python 2.6.6. Specify the full path for each to use both versions.

A: If someone is using jupyter, and you have both python installed, you can also select which kernel to use


text:
Q: get last inserted record's primary key using LAST_INSERT_ID() I can get the primary key of last inserted raw using LAST_INSERT_ID() function.but I want to know when two pcs insert a record at same time what happened to result of above function?is there any possibilty to give an wrong result?it means one pc insert a record and before get the id 2nd pc insert a record at same time,and above function will gives 2nd records id?is it happen?

A: I think you could find your answer in this statement from the MySql documentation

The ID that was generated is maintained in the server on a
  per-connection basis. This means that the value returned by the
  function to a given client is the first AUTO_INCREMENT value generated
  for most recent statement affecting an AUTO_INCREMENT column by that
  client. This value cannot be affected by other clients, even if they
  generate AUTO_INCREMENT values of their own. This behavior ensures
  that each client can retrieve its own ID without concern for the
  activity of other clients, and without the need for locks or
  transactions.

No, the id returned to your connection is just yours

A: The MySQL LAST_INSERT_ID function returns the first AUTO_INCREMENT value that was set by the most recent INSERT or UPDATE statement that affected an AUTO_INCREMENT column.


text:
Q: Computing the number of circles a cell is contained in
Suppose we have given n cirlces, which construct cells Ci.
The midpoint (x-y coordinates) and radius of every cirlce are given.
A cell is characterized by its arcs which bound that cell.
For every arc the following informations are given:
1. The midpoint of the circle it belongs to
2. The source point and target point as x-y coordinate, where the arc starts from and ends.
3. The midpoint of the arc itself is also given with its x-y coordinates.
For Cell1 I have colored the arcs in yellow, blue and brown. Also, I tried to point out the midpoint, target and source of an arc on the picture.
Now, I want to compute the number of circles every cell is contained in with running time O(n²).
For instance, Cell C1 is contained in only 1 circle, Cell C11 in 2 and C5 in 3.
The idea I have computes it in O(m), where as m:= number of arcs.
I think in general the number of arcs can exceed the n².
Any help or idea will be really appreciated! Thanks in advance.

A: I think in general the number of arcs can exceed the n².
Why do you think that?
Any pair of circles intersect in at most two places.  So a single circle will be divided into at most 2n - 2 arcs by the other circles.  Since there are n circles, there are at most 2n2 - 2n = O(n2) arcs.


text:
Q: Add the next command line after validating the first command Is it possible to enter the next command line like this:
command1 ; command2;

After validating command1?
For example I do:
make

And it takes a long time!
I want to say: after this command: do ./myprogram
So I can go take a coffee, and not just wait until it finishes to launch the next command.

A: Sure you can do that, simply add an && or || at the ending of the line depending you want the action be done if the previous command succeeds or fails. So for the following example I use the usual upgrade stuff but it works with almost every command.
#!/bin/bash
# an example upgrade script, call with sudo ./scriptname.sh
apt-get update &&
apt-get -y dist-upgrade &&
apt-get -y autoremove &&
apt-get clean

This would be for a script which only forwards on succession of the commands before. note that the last line has no &&, that is because it would throw you an error if it where there, because there is no next command to jump to.
Now an example for a failure, shall we? Taking again the same example but I want my computer to tell me how silly my action was (kidding):
#!/bin/bash
# an example upgrade script, call with sudo ./scriptname.sh
apt-get update &&
(apt-get -y dist-upgrade &&) || echo "THIS was not working right"
apt-get -y autoremove &&
apt-get clean

So this would in case the command fails output something, for more reading on the bash shell scripting you can visit the links I included here:
http://tldp.org/LDP/Bash-Beginners-Guide/html/index.html
http://mywiki.wooledge.org/BashGuide

A: For that you require to put && between the consecutive commands so that they execute one by one


text:
Q: Passing file path argument to a CherryPy In CherryPy how do you pass an argument like file path (i.e. /abc/def/ghi) through a URL? I want to do something like http://...../filepath="abc/def/ghi". Thanks.

A: Well, .../a/b/x=y is the wrong way to send a value regardless of whether it is a file name or not. The correct way would be .../a/b?x=y
or .../a/b/?x=y which would make x a standard query parameter  and cherrypy would treat it as such. Thereafter whether there were slashes in the value of x or not would be moot. They would get through to your code just fine.

A: What about using ~ as a delimiter and then just replace ~ in the string with /...
http://...../filepath=abc~def~ghi

def SomePage(self, filepath=None):
    filepath.replace('~', '/')
    return 'HelloWorld'

Hope this helps,
Andrew


text:
Q: Nesting too deep exception ATG I am getting following Exception while trying to invoke my customized Actor chain  :
CONTAINER:atg.service.response.output.OutputException:      atg.service.filter.bean.Resources-   >atg.service.response.output.JSONOutputCustomizer.errorUnableToGetPropertyValue; SOURCE:atg.json.JSONException: Nesting too deep. atg.service.filter.bean.Resources->atg.service.response.output.JSONOutputCustomizer.errorUnableToGetPropertyValue
Any help would be greatly appreciated.

A: You can change the value of the MaxNestingDepth in the component for /atg/dynamo/service/response/output/JSONOutputCustomizer. The default value is 15. If you make it -1 it will be 'unlimited'.
Here is a reference to the docs for arguably the same thing.


text:
Q: If Hashset 'add' complexity is O(1), then how unique elements are stored? Big-O - In order to add an element to a HashSet the complexity is O(1), then how does a HashSet determine if the element to be added is unique or not ?

A: This depends on the choice of hash table, but in most traditional implementations of hash tables (linear probing, chained hashing, quadratic probing, etc.) the cost of doing an insertion is on expectation O(1) rather than worst-case O(1). The O(1) term here comes from the fact that on average only a constant number of elements in the hash table need to be looked at in the course of inserting a new value. In linear probing, this happens because the expected length of the run of elements to check is O(1), and in chained hashing it's because there are only on expectation O(1) elements in the bucket in question. The hash table then can check whether the newly-inserted element is equal to any of these values when performing an insertion. If so, we know it's a duplicate. If not, then we know the new element can't be a duplicate; we've checked every element that could possibly be equal to it. That means that on average the cost of an insertion is O(1) and we can check for uniqueness at the time of insertion.


text:
Q: Cordova login with facebook I am a beginner in develop cordova ,i use this exemple
https://github.com/nraboy/ng-cordova-facebook-example but in error are
display :!JavaScript ERROR: 'undefined' is not an object (evaluating 'e.hasOwnProperty')
http://localhost:58578/js/ng-cordova.min.js:10

A: That happens because you are running it inside the browser where the facebook app doesnt not exits. In that case you need to run it on real device (not emulator) where you have the facebook app installed and the error should be gone.

A: The example you are trying, dont open the Facebook-App to Auth. it is opening a inAppBrowser it just work in your device of emulator


text:
Q: using std::equal_range to search the vector within some ranges I have a std::vector with the element as pair and need to find all the elements with the first component within some ranges, for example, to find all elements such that abs(value of first component - reference)<0.01, I got the code from other post that
bool comp(pair<double, double> v1, pair<double, double> v2)
{
  return (abs(v1.first-v2.first)<0.001);
}

vector< pair<double, double> data;
for (int i=0; i<10; i++)
{
  double a, b;
  // a & b are initialized randomly (the code was not shown here)
  data.push_back(make_pair(a, b));
}

// we sort the vector here based on the pair.first (code not shown)

// compval is used as reference value, i.e. we are going to find all elements with     abs(pair.first-ref.first)<0.01
pair<double, double> ref
ref.first = 0.5;
ref.second = 0.5;

std::pair< vector< pair<double, double>::iterator, vector< pair<double, double>::iterator> const range = std::equal_range(data.begin(), data.end(), ref, comp);

but if you look at all elements given by the resulting ranges, you will see that all elements of the data instead of the one satisfying abs(pair.first-ref.first)<0.01 will be returned. Is that anything I miss in the code? Thanks.

A: equal_range requires a sorted range.
The order implied by your comparison function does not match the order that you sorted the range into - and so the call to equal_range has undefined behaviour.
For example - say your list contained {{.5, 0}, {.6, 0}} (these are sorted), and you then applied std::bind(comp({.5,.5},_1)) to each element.
comp({.5,.5},{.5,0}) would return true.
comp({.5,.5},{.6,0}) would return false.
Your sort order is saying: ".5 is less than .6", but at the same time your comp function is saying ".6 is less than .5" (because a there is a value which is less than .5 but not less than .6). This is contradictory, and the cause of your problems.
To actually find all the elements such that std::bind(comp({.5,.5}, _1)) returns true, you could use std::copy_if(data.begin(), data.end(), some_output_iterator, std::bind(comp(ref, std::placeholders::_1))) (although there are a variety of different ways of doing this, depending on your exact needs).

A: I think you should use fabs instead of abs in function comp().

A: Your comparison function does not satisfy the requirements of strict weak ordering, i.e. for two elements say a and b, if comp(a, b) == true then comp(b, a) should be false.
You maybe want something more like this:
struct Comp {
  double target;
  bool operator()(const pair<double, double>& lhs,
                  const pair<double, double>& rhs) const {
    return abs(lhs.first - target) < abs(rhs.first - target);
  }
};

vector< pair<double, double> > data;
data.push_back(make_pair(0.1, 1.0));
data.push_back(make_pair(0.15, 1.2));
data.push_back(make_pair(0.189, 2.1));
data.push_back(make_pair(0.19, -2.1));
data.push_back(make_pair(0.192, 3.1));
data.push_back(make_pair(0.2, 0.1));
data.push_back(make_pair(0.205, 0.1));
data.push_back(make_pair(0.205, 0.0));
data.push_back(make_pair(0.206, 12.1));
data.push_back(make_pair(0.21, -12.9));
data.push_back(make_pair(0.3, 3.4));
data.push_back(make_pair(0.5, 7.5));
// We *must* sort the vector using the same comparison function that we're
// about to use to get the lower and upper bounds
Comp comp;
comp.target = 0.2;
sort(data.begin(), data.end(), comp);

// Get the lower bound
pair<double, double> low(make_pair(comp.target, 0.0));
vector< pair<double, double> >::iterator lower =
    lower_bound(data.begin(), data.end(), low, comp);

// Get the upper bound
pair<double, double> up(make_pair(comp.target + 0.01, 0.0));
// N.B. use "lower_bound" here to get upper bound of target + 0.01 exclusive.
//      If we want to include target + 0.01, use "upper_bound"
vector< pair<double, double> >::iterator upper =
    lower_bound(data.begin(), data.end(), up, comp);

for_each(lower, upper, [](const pair<double, double> &data_point) {
  cout << data_point.first << "\t" << data_point.second << "\n";
});

which outputs:
0.2     0.1
0.205   0.1
0.205   0
0.206   12.1
0.192   3.1
0.21    -12.9


text:
Q: The Star Rating widget with jQuery ajax load It works fine when the page first loads into browser

However, problem starts when the the DIV container contains this star rating, was loaded again with Ajax load. It was reset to its original radio button:

The code to made this rating star works was just as simple as following:
Star Rating Widget Plugin:
$("#stars-wrapper").stars({
  cancelShow: false,
  disabled: true
});

<span id="stars-wrapper">
                <input type="radio" id="rate1" name="newrate" value="1" title="Poor" />
                <input type="radio" id="rate2" name="newrate" value="2" title="Not that bad" />
                <input type="radio" id="rate3" name="newrate" value="3" title="Average" />
                <input type="radio" id="rate4" name="newrate" value="4" title="Good" />
                <input type="radio" id="rate5" name="newrate" value="5" title="Perfect" />
 </span>

Ajax Load:
$('#content_pane').load( href );

Does anyone have idea how to tackle this problem? It seems to be not working well with Ajax load.

A: The problem you're encountering is that you're currently only binding to elements that already exist on the page. When you load new data into the page using an AJAX request, your stars widget is not live and is thus not bound to these new elements.
You would need to re-bind to these elements within your AJAX load like so:
$('#content_pane').load( href, function() {
  $("#stars-wrapper").stars({
    cancelShow: false,
    disabled: true
  });
});

Perhaps your widget includes a live API, but live has since been deprecated in jQuery.


text:
Q: List item default value based on another item in the same list + value How do I set the default value of a list item to be based on another item's value + value?
For example:
List A: duedate, reminderdate
once the user enters a value in the list-->
duedate = 1/1/2016
then it automatically updates this value -->
reminderdate = 1/1/2016 + 4 months
I'm thinking of using workflows but is there any other way to do it?

A: You can use a calculation for this. Create the column reminderdate as a calculated column of the Date and Time type.
Then use the following calculation: =DATE(YEAR([dueDate]),MONTH([dueDate])+4,DAY([dueDate]))
If you are using another regional language than english, you may have to replace all commas (,) with a (;).
Every time the column dueDategets a new value, the calculation in the reminderdate will get updated.
The result will looks like this.

Calculated Field Formulas


text:
Q: Using C# update the document name in a draft DocuSign envelope I'm leveraging the C# API's EnvelopeDefinition and EnvelopesApi to create envelopes in DocuSign in DRAFT status. I would like to know how I could rename the document that is actually part of the envelope in Draft status. Appreciate your help.

A: This can be done with the EnvelopesApi.UpdateDocuments() method documented here: https://developers.docusign.com/esign-rest-api/reference/Envelopes/EnvelopeDocuments/updateList
UpdateDocuments() takes an Envelope Definition object, so in this example I create the Document object to be modified and apply it to an empty EnvelopeDefinition. Using the existing envelope's definition wouldn't be recommended as it comes with extra baggage that's irrelevant to what we're doing here.
        string draftEnvelopeId = "000-000-000-000";

        string documentId = "1";
        string newFileName = "document.pdf";

        Document renamedDocument = new Document
        {
            DocumentId = documentId,
            Name = newFileName,
        };
        Document[] documentList = new Document[] { renamedDocument };
        EnvelopeDefinition emptyEnvelope = new EnvelopeDefinition
        {
            Documents = new List<Document>(documentList)
        };

        EnvelopeDocumentsResult result = envelopesApi.UpdateDocuments(accountId, draftEnvelopeId, emptyEnvelope);


text:
Q: Mean.js Node.js background processes I've got a mean.js app I'm writing and I am conceptually confused about background processes.
I need to have some processes that run continuously in the background that operate on the mongodb database and do stuff like cleanup, email, tweets, etc.
I need a lot of the same functionality and libraries I have in my web app available to these background procs.
What is the best way to do this?  Do I start with a brand new source base and treat these worker procs like a separate app?  Or do I create, say, a daemon folder and fork the background procs when I start the server.js with grunt?
I think I am confusing myself and probably making this more complicated than it should be.   I have looked at node daemon and child_processes and simple_daemon.  But I'm not sure what path to take.
Thanks for your help.

A: You can use setInterval() to run scheduled or repeating tasks within the mean.js app. Because of the way node.js works, as long as node is running your app, any callback defined to run in setInterval() or setTimeout() will run once loaded. This means you can keep your background logic inside your controllers/models or in an adjacent file. You can include your background script, e.g. require()-ing it from the main app.js file, or from anywhere within your controllers, models, etc.
e.g.
app.js:
require('tasks/doStuff');
require('express');

/* express/app stuff here */

tasks/doStuff.js:
require('mongoose');
require('some/other/stuff');

setInterval( function() {
    console.log('interval happened');
}, 1000);

This approach does require some design/architectural considerations. Namely, your tasks are now tied to the successful execution of your node mean.js app. If your mean.js app crashes/dies, your tasks will have also died.


text:
Q: Getting SocketTimeOutException , what is diff between results I'm getting for 2 different time outs On test and prod environment getting lot of socketTimeOut Exception when the timeout limit was 2sec the error rate was a lot 37% but there were successful calls as well not all of them failed.
As a trail we tried increasing timeout limit to 10sec the error rate is 0.9% with still lot of SocketTimeOUtException in the logs , here again there are many successful calls as well.
So my question is, if the service get response in 2Sec for few request does it mean the server is capable of serving the request within 2 sec? and there could be a bottle neck at the server side so it is not responding.
Recently it has started occurring. Also I could see this generally happens between 12 pm to 4 pm when there is lots of request.
Can I assume if there are few requests which are successful, does it means all the connection related majors are in place correctly for eg. the port it is trying to connect to
Will it be a good try to see by creating an extra kubernetes pod when there is load on the service during peek time.
java.net.SocketTimeoutException: timeout

at okio.Okio$4.newTimeoutException(Okio.java:232)

at okio.AsyncTimeout.exit(AsyncTimeout.java:286)

at okio.AsyncTimeout$2.read(AsyncTimeout.java:241)

at okio.RealBufferedSource.indexOf(RealBufferedSource.java:358)

at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:230)

at okhttp3.internal.http1.Http1ExchangeCodec.readHeaderLine(Http1ExchangeCodec.java:242)

at okhttp3.internal.http1.Http1ExchangeCodec.readResponseHeaders(Http1ExchangeCodec.java:213)

at okhttp3.internal.connection.Exchange.readResponseHeaders(Exchange.java:115)

at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:94)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)

at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:43)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)

at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:94)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)

at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)

at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:88)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)

at datadog.trace.instrumentation.okhttp3.TracingInterceptor.intercept(TracingInterceptor.java:35)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)

at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:223)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)

at com.product.composition.client.config.ExceptionTranslatorInterceptor.intercept(ExceptionTranslatorInterceptor.java:15)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)

at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)

at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:229)

at okhttp3.RealCall.execute(RealCall.java:81)

at retrofit2.OkHttpCall.execute(OkHttpCall.java:186)

at com.product.billing.platform.retrofit.adapter.UnwrappedCallAdapterFactory$BodyCallAdapter.adapt(UnwrappedCallAdapterFactory.java:51)

at retrofit2.HttpServiceMethod.invoke(HttpServiceMethod.java:89)

at retrofit2.Retrofit$1.invoke(Retrofit.java:147)

at com.sun.proxy.$Proxy134.generatePDF(Unknown Source)

at com.product.main.composition.service.PdfGeneratorServiceImpl.lambda$null$0(PdfGeneratorServiceImpl.java:56)

at reactor.core.publisher.MonoCallable.subscribe(MonoCallable.java:56)

at reactor.core.publisher.FluxRetryPredicate$RetryPredicateSubscriber.resubscribe(FluxRetryPredicate.java:124)

at reactor.core.publisher.MonoRetryPredicate.subscribeOrReturn(MonoRetryPredicate.java:51)

at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:57)

at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)

at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64)

at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:150)

at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:173)

at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1782)

at reactor.core.publisher.MonoCompletionStage.lambda$subscribe$0(MonoCompletionStage.java:86)

at java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:774)

at java.util.concurrent.CompletableFuture.uniWhenCompleteStage(CompletableFuture.java:792)

at java.util.concurrent.CompletableFuture.whenComplete(CompletableFuture.java:2153)

at java.util.concurrent.CompletableFuture.whenComplete(CompletableFuture.java:110)

at reactor.core.publisher.MonoCompletionStage.subscribe(MonoCompletionStage.java:61)

at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64)

at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:150)

at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1782)

at reactor.core.publisher.MonoFlatMap$FlatMapInner.onNext(MonoFlatMap.java:241)

at reactor.core.publisher.FluxHide$SuppressFuseableSubscriber.onNext(FluxHide.java:127)

at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:73)

at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1782)

at reactor.core.publisher.MonoFlatMap$FlatMapInner.onNext(MonoFlatMap.java:241)

at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:114)

at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:73)

at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1782)

at reactor.core.publisher.MonoCallable.subscribe(MonoCallable.java:61)

at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64)

at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:150)

at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1782)

at reactor.core.publisher.MonoFlatMap$FlatMapInner.onNext(MonoFlatMap.java:241)

at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:73)

at reactor.core.publisher.FluxRetryPredicate$RetryPredicateSubscriber.onNext(FluxRetryPredicate.java:82)

at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1782)

at reactor.core.publisher.MonoCallable.subscribe(MonoCallable.java:61)

at reactor.core.publisher.FluxRetryPredicate$RetryPredicateSubscriber.resubscribe(FluxRetryPredicate.java:124)

at reactor.core.publisher.MonoRetryPredicate.subscribeOrReturn(MonoRetryPredicate.java:51)

at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:57)

at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)

at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64)

at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:150)

at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:173)

at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1782)

at reactor.core.publisher.MonoCompletionStage.lambda$subscribe$0(MonoCompletionStage.java:86)

at java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:774)

at java.util.concurrent.CompletableFuture.uniWhenCompleteStage(CompletableFuture.java:792)

at java.util.concurrent.CompletableFuture.whenComplete(CompletableFuture.java:2153)

at java.util.concurrent.CompletableFuture.whenComplete(CompletableFuture.java:110)


text:
Q: symfony: using generator.yml, is there any way to hide the fields of the i18n forms in the admin? using generator.yml, is there any way to hide the fields of the i18n forms in the admin?
Javi

A: In the form object try the useFields method
$this->useFields(array("field", "names", "you", "want", "to", "edit"));

In generator.yml
In the form section, or the fields/edit/new section. (Take your pick)
display: [field, names, you, want, to, edit]


text:
Q: Confusion Matrix colors match data size and not classification accuracy I am using ConfusionMatrixDisplay from sklearn library to plot a confusion matrix on two lists I have and while the results are all correct, there is a detail that bothers me. The color's density in the confusion matrix seem to match the number of instances rather than the accuracy of the classification.
This is the code I am using to plot the confusion matrix:
target_names = ['Empty', 'Human', 'Dog', 'Dog&Human']
labels_names = [0,1,2,3]
print(classification_report(y_true, y_pred,labels=labels_names, target_names=target_names))
cm = confusion_matrix(y_true, y_pred,labels=labels_names)
disp = ConfusionMatrixDisplay(confusion_matrix=cm,display_labels=target_names)
disp = disp.plot(cmap=plt.cm.Blues,values_format='g')
plt.show()

Now the results I get from both the report and the confusion matrix are:

As you can see, both the classes "Dog" and "Dog&Human" achieved a precision 1, but the color of the class "Dog" is the only one with a dense blue. Even the class "Empty" which has some mis-classified instances has a darker color making it seem like the classification was better. This is obviously due to the number of data in each class, but then, shouldn't the color depend on the performance of classification and not the number of instances correctly detected ?
I tried normalizing the confusion matrix and it solves the issue, but then I would prefer having a matrix that shows the actual number and not a percentage. Is there any solution for this? Thanks a lot.

A: confusion_matrix function allows you to normalize the matrix either by row or column, which helps in dealing with the class-imbalance problem you are facing. Instead of:
confusion_matrix(y_true, y_pred,labels=labels_names)

Simply pass:
confusion_matrix(y_true, y_pred,labels=labels_names,normalize='true')

... to normalize by rows, which I think is what you want. normalize='pred' will allow you to normalize by columns. Check here for further details.


text:
Q: ListView with Separators
Possible Duplicate:
Android : How to populate a ListView with alphabet indexer and fastscroll as in contacts app.?

i need to do a listView with separators. It's easy, but I also need that separators have this behavior:

The separator doesn't disapear until the next separator reachs it.
How can I do it?


text:
Q: Cant run PHP files after installing wampserver.. Although i can run the localhost,etc I've installed wampserver. Its installed and I can see its icon on the tray. But I cannot open a simple PHP file. I saved the file in  C:\wamp\www and I'm trying to open it by using the following URL in the browser using localhost. But I'm getting Error 404 File not found on the server! I tried restarting the PC and the wampserver services but to no avail. Please help me. I'm a newbie. Please help me.

A: Did you write the correct URL Path ? If you drop the file into e.g :
C:/Wamp/www/file.php

Then you must write the URL into this form:
http://localhost/file.php

Note: 404 error is an http error , means the resources you are trying to reach is not exist !


text:
Q: xauth list fails I have an issue with xauth list.
When i run the command xauth list from the account student I get this error xauth:  timeout in locking authority file /home/luigi/.Xauthority. As you can see the command uses the home directory of luigi and not the .Xauthority from /home student. One test that I did is to remove the .Xauthority and login via SSH the student account. however, i get always the same error
how can be possible? any suggestion


text:
Q: Tutorial information bubble control on iOS Is there a control on iOS or a well known library that offers info bubble functionality. (I am relatively new to iOS development so I am not sure if my search keywords are off or this is just not being used on iOS very much)
I would like to achieve something like this:

This comes from Android Tutorial Bubbles library.
I would like to avoid building this control by myself if there is already similar library or something that is being more widely used on iOS.
I found something similar called "ProductTour" but it seems to be quite limited.

A: Yes you can use PopOverPresentation style/segue to achieve this effect. But you have to customize.
I just customize just a little and here is the output.


text:
Q: Python BeatifulSoup scrape a dynamic container I am trying to scrape some flashcards from this website, but I am having a few problems. Below a snippet of my code:
# point to the right link and chapter
url_main = r'https://learninglink.oup.com/access/content/neuroscience-sixth-edition-student-resources/neuroscience-6e-chapter-1-flashcards?previousFilter=tag_chapter-'
chapter = '01'
url_main = url_main + chapter

# get source
html = requests.get(url_main).text
bs = BeautifulSoup(html, features="html.parser")

If I inspect the page on Chrome, I can see that the information I am looking for is in class="box1text". So I do:
# get class
text = bs.find(class_ = "box1text" )

However, when I print this 'text' variable I get:

And no mention of the text I am looking for. What am I doing wrong?
Also, I would like to know how to interact with this container and its buttons, but I don't even know where to start from. My ideal output would be a dictionary containing all the keywords and the associated answers (so, front and back of the card for each flashcard), but to do so I need to be able to interact with this container. Any suggestion on how to do this?
Thanks in advance!

A: I know this doesn't answer your question, but there is actually a better way to go about this.
If you go into devTools sidebar of your browser, and examine the network log,
you would see that there is a Http request being sent to get all the flashcard info:
As you can see, all you need to do is mimic this http request by copying the request header and sending it.
Since I don't use python, i would just use cUrl on the windows command prompt.
You could do this too right now by right clicking on that exact request when the browser is open and clicking on 'copy as Curl(cmd)' , and pasting whatever you get into the command prompt, and you should be getting the required text that you can easily read
Edit:
Also, the site in your post doesn't require any additional paramters to be sent in the request, so you should be able to get away with just:
curl "https://learninglink.oup.com/protected/files/content/flashcardCsv/1512079199667-Neuroscience6e-ch01_flashcards.csv"

you can copy and paste this in cmd to verify for yourself


text:
Q: Не получается подключить conn pool asyncpg через unix сокеты к базе PostgreSQL. Пишет при подключении, что файл не найден Есть клиент на python, который использует пул соединений через asyncpg. Клиент и PostgreSQL запущены на одном сервере Linux. При попытке подключения возникает ошибка, что такой файл не найден.
URI:
postgresql:///devdb?host=/var/run/postgresql&user=maxidev&password=j2v4j23324v242h34v2hj&port=5432

Ошибка:
File "uvloop/loop.pyx", line 2260, in create_unix_connection
  File "uvloop/loop.pyx", line 2255, in uvloop.loop.Loop.create_unix_connection
FileNotFoundError: [Errno 2] No such file or directory

pg_hba:
local    devdb     maxidev             all                 md5

A: Проблему исправил тем, что убрал all - поле ADDRESS у local и убрал ранее определённое разрешение:
local   all             postgres                                peer


text:
Q: Does the first season of The Expanse cover the entire first book? I've seen the first season of The Expanse. I haven't read any of the books (yet). I expect there to be differences between the book and the TV series, as will happen always.
But do the first season of the The Expanse TV series and Leviathan Wakes, the first book of the series, cover the same period and events?
Or are there events in the book not yet covered in the show?
Or perhaps events in the show taken from the second book, Caliban's War?

A: Some things from the series are heavily 'modified' from the books. For example, in the books Alex never kept it secret that he was in the Martian navy.

A: The first season covers about the first half of Leviathan Wakes.  There are definitely events in the first book that have not yet happened on the show.
However, there are also components of the show that did not occur in the first book.  For example:

 Chrisjen Avasarala is not in the first book. She makes her debut in Caliban's War, book 2 of the series.