text:
Q: Is there a difference between these two initialisation modes? Let's say I have this:
public class Whatever {
   private ArrayList<String> myList = new ArrayList<String>();
   // more code goes here
}

or let's say I have this:
public class Whatever {
   private ArrayList<String> myList = null;

   public Whatever() {
     myList = new ArrayList<String>();
   }
}

What's the difference between these two initialisations of myList? Would it be wrong to preffer the first variant?

A: The JVM first executes code such as this (outside the constructor):
public class Whatever {
   private ArrayList<String> myList = new ArrayList<String>();
   // more code goes here
}

And only then code such as this (inside the constructor):
public class Whatever {
   private ArrayList<String> myList = null;

   public Whatever() {
     myList = new ArrayList<String>();
   }
}

So unless the order of execution is somehow important to you i guess @Daff's answer is the right one.

A: In this particular example, there is no difference except that the first form is shorter.
However, if the attribute initialization expression (potentially) throws exceptions, the second form allows you to catch the exceptions, or declare them as thrown in the constructor signature.
And of course, if you have multiple constructors, the second form allows you to initialize the attribute differently in each constructor ... or use constructor chaining to initialize the attribute the same ... or mix the two styles of initialization.

A: The first variant will always instantiate the array list, the second one only when calling the default constructor. Meaning for the second solution you will have to call the default constructor for any additional constructor you add e.g.
public class Whatever {
   private final List<String> myList;

   public Whatever() {
     myList = new ArrayList<String>();
   }

   public Whatever(String name) {
     this();
     // Other stuff done
   }

   public Whatever(List<String> myList) {
     this.myList = myList;
   }
}

The (second) "lazy" initialization method might be better if you don't always use the list (e.g. if you set the list in another constructor directly like in my example) and want to avoid creating unnecessary objects. (EDIT: I changed the ArrayList to an interface and set it final. It wasn't part of the question but it is - as mentioned in the comments - the best way to use List collections).


text:
Q: VB.NET: How to find a word after a specific word in a line and store it I have a continuous string of words coming from a machine to hyper terminal of my system, for which I am using USB to serial cable. I want to find some of the values which comes after a specific word in that string and then store it.
I used threads and splitting concepts to do it but as per the requirement and operation of the machine  it will not work properly in the runtime.
The values which I want to capture comes from a specific word. I want to skip that words and just store the values. How to do it?
I have given the example of that string below:

MEAN 49  50
SD   500 10
MIN  100 5
MAX  50  45.56

In this I just want to store the values e.g. 49 and 50, then discard MEAN. Then discard SD and store 500 and 10 and so on.

A: You can use a StreamReader object to read the stream one line at a time.  Then, you can easily parse the line using the String.Split method.  I would recommend creating one or more classes that represent the data being read, like this:
Public Class LineData
    Public Property Label As String
    Public Property Value1 As Decimal
    Public Property Value2 As Decimal
End Class

Public Function ReadNextLine(stream As Stream) As LineData
    Dim reader As New StreamReader(stream)
    Dim line As String = reader.ReadLine()
    Dim data As LineData = Nothing
    If line IsNot Nothing Then
        Dim words() As String = line.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
        If words.Length = 3 Then
            data = New LineData()
            data.Label = words(0)
            data.Value1 = Decimal.Parse(words(1))
            data.Value2 = Decimal.Parse(words(2))
        End If
    End If
    Return Data
End Function

Note, this is a very simple example based on the example data you provided.  If different lines have different numbers of numeric parameters, that will further complicate the logic.  In my example, the method returns Nothing if no data can be read.  Also, the method will throw an exception if the last two words in the line are not numeric.  Therefore, you would need to wrap it in some additional exception handling.

A: This may be what you're looking for. Although personally I'd create a class which stores the type(mean, median etc), firstvalue and secondvalue.
By the sounds of it though, all you want it to do is dump the values into some sort of storage, therefore this will suffice.
Dim Values as New List(Of Decimal)

'Use a streamreader to read each line of text
Using reader As StreamReader = New StreamReader(*your text source*)
'Read the line
Dim linetext as string = reader.ReadLine
Dim myValue as decimal
'Split the line
Dim splitText() = linetext.Split(" ")
'Analyze each section of the line, if its possible to parse the value as a decimal then add it to the list of values to be stored.
For Each txt in splitText
If Decimal.TryParse(txt, myValue) then Values.Add(myValue)
Next
End Using

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inline form elements being pushed down by collapsible menu I have a bootstrap 5 form that is inline and which has a collapsible menu.
I am having difficulty stopping the collapsible advanced search menu pushing box 1 and 2 down (see code snippet).
I have set the .collapse with position absolute but this messes up the layout (the dropdown menu doesnt span 100% and box 1 and 2 kind of jump when the advanced search is clicked). You may need to view the snippet in full page mode to see the problem clearer.I have set the .collapse position to absolute but this does kind of disrupt the layout of the dropdown menu. Any help with getting this sorted would be much appreciated. Have been stuck on this form for ages!

.collapse{
  position: absolute;
  width: 1200px;
}

.search-form{

border:2px solid #000;

}
<Doctype html>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

      <form action="" class=" form-inline d-flex">

    Advance Search With Filters

            <input type="text" placeholder="Property ID" class="form-control">

            <input type="text" class="form-control" placeholder="Search by MAP">

            <input type="text" class="form-control" placeholder="Search by Country">

    <input type="password" id="inputPassword6" class="form-control" placeholder="box1" aria-describedby="passwordHelpInline">

    <input type="password" id="inputPassword6" class="form-control" placeholder="box2" aria-describedby="passwordHelpInline">

      Must be 8-20 characters long.

    </form>

A: Can you please try this code may be this can be helpful to your question.

.search-form{
  position: absolute;
  border:2px solid #000;

}

.collapse {

  width: 100%;

}
<Doctype html>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

      <form action="" class=" form-inline d-flex">

    Advance Search With Filters

            <input type="text" placeholder="Property ID" class="form-control">

            <input type="text" class="form-control" placeholder="Search by MAP">

            <input type="text" class="form-control" placeholder="Search by Country">

    <input type="password" id="inputPassword6" class="form-control" placeholder="box1" aria-describedby="passwordHelpInline">

    <input type="password" id="inputPassword6" class="form-control" placeholder="box2" aria-describedby="passwordHelpInline">

      Must be 8-20 characters long.

    </form>


text:
Q: Django Model Fields: Keeping track of list of possible items I'm creating a Django model, where (as a simplified example) a user group (Users are all assigned to a group) will be able to access files of a certain file type, and which types a group can access will change by group. The list of files can be any of ~10 common file types. This list might change, but that's probably not common.
Roughly speaking, I see two ways of doing this. Representing the file types as a list of strings for each user [".jpg", ".txt", ".zip"] or, as a M:M relationship with some sort of "FileExtension" Object.
These are cases in which I imagine the ORM route would be much preferred (Ex: If it's important to keep track of Each file extension's use case as for "image", "text", "audio", etc) But what if there's no other information we really need to consider here but the file extension itself? Is there a reason to create a whole model for just a few strings? In my actual project, I want to avoid the complications of creating and maintaining multiple models and storing those in the DB if I can.
Rough Possible Code Examples of each:
String/List approach:
class UserGroup(models.Model):

    group_name = models.CharField(max_length=128)

    file_access = models.JSONField(null=True) #JSON-serialized list of strings

Model approach:
class UserGroup(models.Model):

    group_name = models.CharField(max_length=128)

    file_access = models.ManyToManyField(FileExtension)

class FileExtension(models.Model):

    extension = models.CharField(max_length=8, null=True)

Quick Note: I've already looked into this answer which was helpful in showing me the ways I could do this, but does not leave me convinced as to what the best way is for me to do here. Also the question is a decade old so perhaps some things have changed in how Django handles this.


text:
Q: Finding if the values in one column are within the range of several other columns I am looking for an easy way to find whether the value in a column lies within the range of values in other columns.
My input looks like this:
ID  "Q1 Comm - 01 Scope Thesis" "Q1 Comm - 02 Scope Project" "Q1 Comm - 03 Learn Intern"    "Q1 Comm - 04 Biography"    "Q1 Comm - Overall Plan"
10   NA                          NA                           4                              NA      4
31   2                           NA                           NA                             NA      2
225  0                           NA                           NA                             NA      1
243  NA                          2                            NA                             1       0
310  NA                          2                            NA                             1       NA

For each unique ID, I am interested in identifying when the column Q1 Comm - Overall Plan is:
1 - Below the min() of all the other columns, or
2 - Above the max() of all the other columns, or
3 - Within the range of all the other columns
The complete list of columns (along with the overall column) is below:
"Q1 Comm - 01 Scope Thesis"
"Q1 Comm - 02 Scope Project"
"Q1 Comm - 03 Learn Intern"
"Q1 Comm - 04 Biography"
"Q1 Comm - 05 Exhibit"
"Q1 Comm - 06 Social Act"
"Q1 Comm - 07 Post Project"
"Q1 Comm - 08 Learn Plant"
"Q1 Comm - 09 Study Narrate"
"Q1 Comm - 10 Learn Participate"
"Q1 Comm - 11 Write 1"
"Q1 Comm - 12 Read 2"
"Q1 Comm - Overall Plan"

My required output is something like this:
ID  "Q1 Comm - 01 Scope Thesis" "Q1 Comm - 02 Scope Project" "Q1 Comm - 03 Learn Intern"    "Q1 Comm - 04 Biography"    "Q1 Comm - Overall Plan" "Q1_check"
10   NA                          NA                           4                              NA      4 "within"
31   2                           NA                           NA                             NA      2 "within"
225  0                           NA                           NA                             NA      1 "above"
243  NA                          2                            NA                             1       0 "below"
310  NA                          2                            NA                             1       NA NA

The dput() for my data frame df is below.
dput(df)

structure(list(ID = c(10L, 31L, 225L, 243L), Q1.Comm...01.Scope.Thesis = c(NA,
2L, 0L, NA), Q1.Comm...02.Scope.Project = c(NA, NA, NA, 2L),
    Q1.Comm...03.Learn.Intern = c(4L, NA, NA, NA), Q1.Comm...04.Biography = c(NA,
    NA, NA, 1L), Q1.Comm...Overall.Plan = c(4L, 1L, 2L,
    NA), X = c(NA, NA, NA, NA), X.1 = c(NA, NA, NA, NA), X.2 = c(NA,
    NA, NA, NA)), class = "data.frame", row.names = c(NA, -4L
))

Note:
I had asked this question here Finding if a value is within the range of other columns but the example was too simplified and none of the solutions worked for me.
The question was getting too lengthy, therefore, for the sake of clarity, I am posting this as a new question.
I thank you for your time and help on this post.

A: You might try something like this with rowwise and c_across:
library(dplyr)
df %>%
  rowwise %>%
  summarise(ID = ID,
            Max = `Q1.Comm...Overall.Plan` > max(c_across(-c(ID,`Q1.Comm...Overall.Plan`)),na.rm = TRUE),
            Min = `Q1.Comm...Overall.Plan` < min(c_across(-c(ID,`Q1.Comm...Overall.Plan`)),na.rm = TRUE),
            Range = `Q1.Comm...Overall.Plan` >= range(c_across(-c(ID,`Q1.Comm...Overall.Plan`)),na.rm = TRUE)[1] &
                    `Q1.Comm...Overall.Plan` <= range(c_across(-c(ID,`Q1.Comm...Overall.Plan`)),na.rm = TRUE)[2]) %>%
  mutate(Result = case_when(Max ~ "above",
                            Min ~ "below",
                            Range ~ "within",
                            TRUE ~ NA_character_))
# A tibble: 4 x 5
     ID Max   Min   Range Result
  <int> <lgl> <lgl> <lgl> <chr>
1    10 FALSE FALSE TRUE  within
2    31 FALSE FALSE TRUE  within
3   225 TRUE  FALSE FALSE above
4   243 NA    NA    NA    NA

You can change summarise to mutate to keep the original columns and/or select to get rid of them.
See the dplyr rowwise tutorial for more information.

A: library(purrr)
library(data.table)

needed_cols <- setdiff(names(df), c("ID", "Q1.Comm...Overall.Plan"))

setDT(df)[, c("min", "max") := transpose(pmap(.SD, range, na.rm = TRUE)), .SDcols = needed_cols]
df[, Q1_check := fcase(
    is.na(`Q1.Comm...Overall.Plan`), NA_character_,
    `Q1.Comm...Overall.Plan` < min, "below",
    `Q1.Comm...Overall.Plan` > max, "above",
    default = "within"
  )
]
df[, c("max", "min") := NULL]

A: I have revised your dput to suit to your requirements as discussed in the linked question.  I think this will help you.  I used janitor::clean_names() which I suggest you to use before proceeding so that your column names are cleaned.
So the revised dput is
df <- structure(list(id = c(10L, 31L, 225L, 243L), q1_comm_01_scope_thesis = c(NA,
2L, 0L, NA), q1_comm_02_scope_project = c(NA, NA, NA, 2L), q1_comm_03_learn_intern = c(4L,
NA, NA, NA), q1_comm_04_biography = c(NA, NA, NA, 1L), q1_comm_overall_plan = c(4L,
1L, 2L, NA), q2_comm_01_scope_thesis = c(NA, 4, 0, NA), q2_comm_02_scope_project = c(NA,
NA, NA, 4), q2_comm_03_learn_intern = c(8, NA, NA, NA), q2_comm_04_biography = c(NA,
NA, NA, 2), q2_comm_overall_plan = c(8, 2, 4, NA)), row.names = c(NA,
-4L), class = "data.frame")

df
   id q1_comm_01_scope_thesis q1_comm_02_scope_project q1_comm_03_learn_intern q1_comm_04_biography q1_comm_overall_plan q2_comm_01_scope_thesis
1  10                      NA                       NA                       4                   NA                    4                      NA
2  31                       2                       NA                      NA                   NA                    1                       4
3 225                       0                       NA                      NA                   NA                    2                       0
4 243                      NA                        2                      NA                    1                   NA                      NA
  q2_comm_02_scope_project q2_comm_03_learn_intern q2_comm_04_biography q2_comm_overall_plan
1                       NA                       8                   NA                    8
2                       NA                      NA                   NA                    2
3                       NA                      NA                   NA                    4
4                        4                      NA                    2                   NA

Now proceed as suggested. You have to modify [-5] inside cur_data() to suit to your requirements (as per the relative location of overall_column I think 9 in your case)
library(tidyverse)

split.default(df[-1], gsub('(q\\d*)(.*)', '\\1', names(df[-1]), perl = T)) %>%
  map(., ~ .x %>% bind_cols('id' = df$id) %>%
        group_by(id) %>%
        mutate(across(ends_with('_overall_plan'), ~ case_when(. < min(cur_data()[-5], na.rm = T) ~ 'below',
                                                              . > max(cur_data()[-5], na.rm = T) ~ 'above',
                                                              is.na(.) ~ NA_character_,
                                                              TRUE ~ 'within'),
                      .names = '{str_remove(.col,"_comm_overall_plan")}_check'))
        ) %>%
  reduce(left_join, by = 'id')

# A tibble: 4 x 13
# Groups:   id [4]
  q1_comm_01_scop~ q1_comm_02_scop~ q1_comm_03_lear~ q1_comm_04_biog~ q1_comm_overall~    id q1_check q2_comm_01_scop~ q2_comm_02_scop~ q2_comm_03_lear~ q2_comm_04_biog~
             <int>            <int>            <int>            <int>            <int> <int> <chr>               <dbl>            <dbl>            <dbl>            <dbl>
1               NA               NA                4               NA                4    10 within                 NA               NA                8               NA
2                2               NA               NA               NA                1    31 below                   4               NA               NA               NA
3                0               NA               NA               NA                2   225 above                   0               NA               NA               NA
4               NA                2               NA                1               NA   243 NA                     NA                4               NA                2
# ... with 2 more variables: q2_comm_overall_plan <dbl>, q2_check <chr>


text:
Q: How To Include Header Information in ToJSON Output Hi there I have a requirement to provide a JSON array for delivery to one of our clients. The JSON is based on the following 'Model' components:
 Public Class PIValues
     Inherits List(Of PIValue)

     Public Sub New()
     End Sub
 End Class

 Public Class PIValue
     Private _PointName As String
     Private _value As Double
     Public Property PointName() As String
         Get
             PointName = _PointName
         End Get
         Set(value As String)
             _PointName = value
         End Set
     End Property
     Public Property Value() As Double
         Get
             Value = _value
         End Get
         Set(value As Double)
             _value = value
         End Set
     End Property
 End Class

Its a breeze to generate the required JSON output however I also need to provide some header information as part of the package in the form:
 TimeStamp: <yyyyMMdd hh:mm:ss>

Where the contents within the chevrons are a variable time stamp of the specified format.
How can I insert this information into the JSON package?
Kind Regards
Paul.


text:
Q: Loop back to question instead of printing out "Try again"? (C) this is my first day coding and I'm trying to see how the code work, how can I change Y/N to Yes/No and loop back questions if the answer is not Yes instead of printing out "Try again?" or make it better?
int main(void)
{

    char answer;
    int name;
    printf("Enter Username: \n");
    scanf("%s",&name);
    printf("Is your username \"%s\"? Enter Y or N\n", &name);

    while (scanf(" %c", &answer) == 1 && answer == 'Y')
    {
        char answer2;
        Sleep(1000);
        printf("Username confirmed\n");
        Sleep(2000);
        int pass;
        printf("Enter your password: \n");
        scanf("%s",&pass);
        printf("Is your password \"%s\"? Enter Y or N\n", &pass);
        while (scanf(" %c", &answer2) == 1 && answer2 == 'Y')
        {
            printf("Success!");
            Sleep(1000);
            exit;
        }
        printf("Try again..\n");
        Sleep(1000);
        exit;
    }
    Sleep(1000);
    printf("Try again..\n");
    Sleep(1000);
    exit;
    return 0;
}

A: My best advice, as Weather Vane told you in the comment section, is to try to compile your code, before making changes: you'll find out that it won't even compile, since there are some errors (https://godbolt.org/z/MdahM4sT8).
You should debug and try to figure out why it doesn't work, fix it, then move to the new "features".

You probably want to change the while() condition and read a sequence of characters (array of char) instead of a single char.
char answer[4];

while (scanf("%3s", answer) > 0 && strcmp(answer, "Yes") == 0)

char answer[4]; creates an array of characters (which can be called a string, even though C doesn't have that abstraction) of size 4.
You might want to know why we need a size of 4, since the longer answer we can get is "Yes". Well, a string in C is a sequence of characters (char), ending with a special character, called terminating character '\0'.
Therefore, when you read a string with scanf(), you need to reserve some space for the terminating character aswell, and scanf() will add it when reading a space or carriage return after your input string. So if you enter "Yes" and then press the Return key, your answer[4] buffer will look like: {'Y', 'e', 's', '\0'}.
%3s tells scanf() to read only the first 3 characters of the string (prevents security issues like buffer overflow).

int scanf(const char *format, ...)

Description
Reads formatted input from stdin.

Return Value
On success, the function returns the number of items of the argument list successfully read. If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror) and, if either happens before any data could be successfully read, EOF is returned.

Once you've read that string, you can use strcmp(), a function defined in `<string.h> header, that takes in 2 string parameters, and returns:

*

*a negative value if the first precedes alphabetically the second;

*0 if they're equal;

*a positive integer if the second precedes alphabetically the second;

Therefore you can check if strcmp(answer, "Yes") == 0 to know if you've read Yes, and


text:
Q: How can I use VBA in Excel to find a free slot in the other persons calendar and pull back in to my sheet? I have a excel spreadsheet with names, emails, Meeting date and meeting times, How can i get ans import a time slot from a recipients calendar to make/suggest an appointment time and get that info back in to the excel spreadsheet while making sure the dates and times fall within 9-5 Mon-Fri
Please bare in mind Im still quite new to VBA so code would be fantastic and instructions would be even better :)
Thanks
(Thanks for the "-1" on my question too :D )

So far i have managed to get excel -> outlook to get the information only when i specify a set date and a set user eg;
Public Sub GetFreeBusyInfo()

    'launch Outlook
    Dim olapp As Outlook.Application
    Set olapp = CreateObject("Outlook.Application")
    Dim myNameSpace As Outlook.Namespace
    Set myNameSpace = olapp.GetNamespace("MAPI")
    Dim myRecipient As Outlook.Recipient
    ' who's calendar
    Set myRecipient = myNameSpace.CreateRecipient("person@email.com")
    Dim myFBInfo As String
    On Error GoTo ErrorHandler
    'when and how long to look for
    myFBInfo = myRecipient.FreeBusy(#1/30/2014#, 60 * 24, True)
    MsgBox myFBInfo
    Exit Sub
ErrorHandler:
    MsgBox "Cannot access the information. "
End Sub

, but it is reporting back im the message box something like "001010101101101011100100" I understand that in my case its saying 0= free and 1= busy but how can i change that back to a manageable date and time that i can then drop the msgbox and insert it to a cell?
Also would it be best to screen the out of hours times before or after pulling the info back to excel as im only looking for one date and time?

A: In terms of what you are asking, it seems that you are wanting to get information from Outlook into Excel and manipulate it.
I would advise trying it yourself, with being new to VBA it's often best to try it first as at least then you get an understanding of where the code is coming from and how it works. I have not long learned Outlook automation in Excel VBA and glad I did it mostly off my own back as it helps you more in the long run.
I will help point you in the right direction though...
What you need to do is generate an Outlook "Object" and run your VBA from there. A link explaining the basics of what can be done can be found on MSDN here: http://msdn.microsoft.com/en-us/library/office/bb206737(v=office.12).aspx
As you will be working with Calendars, you will be using the AppointmentItem code. More on that can be found on MSDN here: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.appointmentitem.aspx
Hopefully this will at least point you in the right direction as to how to go about it.

A: Although it is a rather old question but I'll try to answer it ...
The FreeBusy method you are using returns a String of time slot information. If the 3rd parameter of the method (called "CompleteFormat") is true, then each character contains the value of a Outlook.OlBusyStatus member (which is olBusy=2, olFree=0, olOutOfOffice=3, olTentative=1, olWorkingElsewhere=4). If the CompleteFormat parameter is false, then "1" means busy and "0" indicates a free time slot.
The method always returns the free/busy information of one month starting with the given date (1st parameter). The length of the time slot is determined by the 2nd parameter of the method call. This parameter specifies the length of one time slot in minutes - you specified 24 * 60 which means that each character represents a full day. So in your example the first character shows the free/busy information for the entire day #1/30/2014#, the 2nd character is for #1/31/2014# and so on. I have no information how the status is calculated from a time span that has different states but I assume that the "worst" state is taken.
Please note that the method starts the time slots with the time 00:00:00  of the day you specified. So if you specify a start-date including time information as the 1st parameter, then the time information is ignored.
That being said, you might be looking for something like the following:
    resolution = 60 * 24
    startDate = #1/30/2014#
    myFBInfo = myRecipient.FreeBusy(startDate, resolution, True)
    For i = Len(slots) To 1 Step -1
        s = CInt(Mid(slots, i, 1))
        If s = olFree Or s = olTentative Then
           slotDate = DateAdd("n", (i - 1) * resolution, startDate)
           Debug.Print Format(slotDate, "dd.mm.yyyy HH:MM")
        End If
    Next

If you want to get more "sofisticated" results, then it is a good idea to fetch the free/busy information in smaller time slots (i.e. 15 minutes) than the overall time slot you are searching (i.e. 60 minutes) and then calculate all possible slots on your own.
This is how I implemented a search for a common free time slot for multiple recipients:

*

*For each recipient:

*

*Fetch free/busy information in 15 minute time slots

*Generate an array of all possible 1 hour slots (= 4 time slots in a row must be free) that are also part of the previous recipient's free 1 hour slots

*Return first element of resulting array


text:
Q: Dropdown menu hidden within navbar i'm doing a project in which I have to make a website from scratch using no frameworks. The problem i'm having is that I'd like to make a navigation bar that can collapse down on mobile devices aswell as have a dropdown menu on a desktop.
I've managed to get it properly working for mobile devices, but when on a desktop the dropdown menus just hide within the nav bar container. I believe this is a problem where the height isn't adjusting for the dropdown, but i'm not too sure how i'd fix it. The navigation bar has to be fixed to the top, collapse when below 900px and the dropdowns must be visible when hovering over them.
The Website in question is
http://www.ico.mmu.ac.uk/13143651/webdev/
CSS
nav {
background-color: #b8b8b8;
font-family: arial;
position: fixed;
top: 0;
z-index:999;
text-decoration: none;
width: 100%;
padding:0px;
overflow:auto;
margin:0px;
clear:both;
}

HTML

    Courses

Digital Media

Web Development

Journalism

Information Communications

    Facilities

Societies

Jobs and Placements

Library

    Manchester and Student Life

Travel

Attractions

Nightlife

    Student Help

Finance

Student Union

Assistance

Contact

Thanks in advance.

A: In your css, change your .nav overflow rule.
From
overflow: auto
to
overflow: visible

A: It's hard to know what the desired behaviour is, but you can try variations on this:
ul.slimmenu li > ul{
    position: fixed;
    top: 50px;
    left: none;
}


text:
Q: CSV read specific row I have a CSV file with 100 rows.
How do I read specific rows?
I want to read say the 9th line or the 23rd line etc?

A: You could read all of them and then use normal lists to find them.
with open('bigfile.csv','rb') as longishfile:
    reader=csv.reader(longishfile)
    rows=[r for r in reader]
print row[9]
print row[88]

If you have a massive file, this can kill your memory but if the file's got less than 10,000 lines you shouldn't run into any big slowdowns.

A: You could use a list comprehension to filter the file like so:
with open('file.csv') as fd:
    reader=csv.reader(fd)
    interestingrows=[row for idx, row in enumerate(reader) if idx in (28,62)]
# now interestingrows contains the 28th and the 62th row after the header

A: You can do something like this :
with open('raw_data.csv') as csvfile:
    readCSV = list(csv.reader(csvfile, delimiter=','))
    row_you_want = readCSV[index_of_row_you_want]

A: Use list to grab all the rows at once as a list. Then access your target rows by their index/offset in the list. For example:
#!/usr/bin/env python

import csv

with open('source.csv') as csv_file:
    csv_reader = csv.reader(csv_file)
    rows = list(csv_reader)

    print(rows[8])
    print(rows[22])

A: You simply skip the necessary number of rows:
with open("test.csv", "rb") as infile:
    r = csv.reader(infile)
    for i in range(8): # count from 0 to 7
        next(r)     # and discard the rows
    row = next(r)   # "row" contains row number 9 now

A: May be this could help you , using pandas you can easily do it with loc
'''
Reading 3rd record using pandas -> (loc)
Note : Index start from 0
If want to read second record then 3-1 -> 2
loc[2]` -> read second row and `:` -> entire row details
'''

import pandas as pd
df = pd.read_csv('employee_details.csv')
df.loc[[2],:]

Output :


text:
Q: Should I use an ssl terminator or just haproxy? I'm trying to figure out how to set up my architecture for a socket.io app that will require both https and wss connections. I've found many tutorials on the web suggesting that you use something like stud or stunnel in front of haproxy, which then routes your unencrypted traffic to your app. If I were to go this route, is it suggested that haproxy and the ssl terminator be on separate instances, or is it fine if they are on the same EC2 server instance?
If I do not want to use a separate ssl terminator, could I use haproxy to terminate the ssl? Or instead would it be possible to proxy these https and wss connections to my application and have the node app terminate the ssl itself?

A: Give a try to haproxy-1.5-dev12, it supports SSL offloading and will make your life easier :-)

A: The last I checked, haproxy still didn't have SSL termination as a feature. This is why you're seeing recommendations to put stunnel in front of it as a way to provide just that feature.
In my opinion, it's generally OK to host both stunnel and haproxy on the same system. Even EC2 micro instances can drive a good chunk of SSL traffic, and the larger instances are even better at it. You might run into some problems at high scale where the number of sockets that need to get opened to forward all this traffic around might run into limits, but that's kind of a nice problem to have.
I do know of one SSL-enabled load-balancer, and that's Pound. Not nearly as featured as HAproxy, but if all you need is SSL-termination and some back-end servers it's good enough. Chances are you'll have to build your own packages though, so that might rule it out.


text:
Q: How to make the display of a satellite image the same across users? I have a group of users counting objects in a satellite image. To keep viewing conditions the same I wish each user to have the same display (e.g., the same scale).
To do this, I have asked users to set the same scale when viewing the satellite image (e.g., 1:1,000) on their laptop. Despite this, the image display looks different between users. For some users, the image appears more "zoomed in" and for others more "zoomed out" compared to mine.
How can I ensure all users have the same scale when viewing a satellite image?
Technical Details:
Users have the same satellite image (0.5 m Worldview imagery) but different laptops and platforms (some users are using QGIS, others ArcGIS).

A: I would set the display scale of the worldview image at a very narrow window to display at 1:1000 (but do not allow it to draw any finer or coarser than that) using the scale range option in ArcGIS (Layer properties/General tab).
I think setting a common scale is your best option here - I don't see how you can match displays beyond that point.

A: You could downsample the image to a coarser resolution, then tell everyone to zoom in as much as they want.

A: It's worthwhile to note that what you see in QGIS on the screen map canvas depends on all of

*

*The specified scale

*The size, in pixels, of the map canvas window

*The screen "logical DPI" (dots per inch)
In particular, QGIS uses this logical DPI (#3) to convert the size in #2 to a nominal assumed size of the canvas (in cm/whatever), and then the scale factor to determine how many map units make up one pixel.
If your users are seeing different images, and you have forced #1 (the scale) to be the same, one of #2 or #3 is different. The one which is most likely to be "surprising" is #3, especially since the "logical DPI" may not actually be the same as the actual "physical DPI" of each user's screen. In particular, on modern laptops, the actual physical DPI may well be 150 or more, but (in windows) the logical dpi will be 96, 120, 144, or rarely 168 or 192 depending on how the user has set the magnification factor for the UI in Windows' system settings. For more details, see Correcting canvas DPI in QGIS Windows
In your context, you will have to decide whether you want "same" to mean "same actual physical scale, as if the screen were a sheet of paper", "same number of map units per pixel", or "same width in map units of map canvas, irrespective of each user's actual screen size". Then you can correct what is being shown by using the following PyQGIS iface.mapCanvas().setMagnificationFactor(...) command.
To determine the factor you want, based on your choice above, you may query targetDpi/iface.mainWindow().logicalDpiX() and .physicalDpiX() for the respective values and use their ratio, or the ratio of a fixed target number to logicalDpiX for instance.


text:
Q: Directional derivative of of $H^1(\Omega) \ni u\mapsto \int_{\Omega} \sqrt{1+|\nabla u|^2}$
Show that the directional derivative of $F:H^1(\mathbb{R})\to \mathbb{R}, u\mapsto \int_{\Omega} \sqrt{1+|\nabla u|^2}$ is $$\partial_e F(u)=\int_{\Omega} \frac{\nabla{u} \cdot \nabla{e}}{\sqrt{1+|\nabla u|^2}}.$$

By definition of directional derivative I think we have $$\partial_e F(u)=\lim_{t\to0}\frac{F(u+te)-F(u)}{t}=\lim_{t\to0}\frac{F(u+te)-F(u)}{te}e=F'(u)e$$ or rather $F'(u)\cdot e$?
Differentiating naively I get $F'(u)=\int_\Omega\frac{\nabla{u}}{\sqrt{1+|\nabla u|^2}}$ and so I would have $\partial_e F(u)=\int_{\Omega} \frac{\nabla{u} \cdot e}{\sqrt{1+|\nabla u|^2}}$, missing a gradient.
I also tried to expand $F(u+te)$ but I am not sure how to simply $F(u+te)-F(u)= \sqrt{1+|\nabla{u}+t\nabla{e}|^2}-\sqrt{1+|\nabla{u}|^2}$.

A: As noted by @mattos, the first variation of a functional gives the Gateaux derivative (directional derivative): $$\partial F_e(u)=\lim_{t\to 0} \frac{F(u+te)-F(u)}{t}= \frac{d}{dt} F(u+te)\bigg\rvert_{t=0}=\frac{d}{dt}
\int_{\Omega}\sqrt{1+|\nabla{u}+t\nabla{e}|^2}dx\bigg\rvert_{t=0}$$
Taking the derivative inside the integral and using the chain rule we get $$ \partial F_e(u)=\int_{\Omega} \frac{(\nabla{u}+t\nabla{e})\cdot \nabla{e}}{\sqrt{1+|\nabla{u}+t\nabla{e}|^2}}dx\bigg\rvert_{t=0}=\int_{\Omega} \frac{(\nabla{u}+t\nabla{e})\cdot \nabla{e}}{\sqrt{1+|\nabla{u}+t\nabla{e}|^2}}dx\bigg\rvert_{t=0}=\int_{\Omega} \frac{\nabla{u}\cdot \nabla{e}}{\sqrt{1+|\nabla{u}|^2}}dx.$$

A: In your original attempt, your manipulation of
$$
\lim_{t \to 0} \frac{F(u+te) - F(u)}{t}
$$
does not make sense. Remember that $e$ is a function in $H^1$ and $F$ is a functional, it doesn't make sense to (for example) divide by $e$ here. You need to think of
$$
f(t) := F(u + te)
$$
as your scalar function. Find the derivative of this at $t=0$, i.e. we have
$$
f'(0) = \lim_{t \to 0} \frac{F(u+te) - F(u)}{t}
$$
So thinking more along the lines of your second attempt will get to the right answer.


text:
Q: Unable to Install Eclipse ADT Plugin on Eclipse Indigo I am trying to install Eclipse plugin for Android Development.
Steps :
"Help" -> "Install New Software" Added "http://dl.google.com/eclipse/plugin/3.7"
And then checked "Google Plugin for Eclipse" to install it.
The Installation moves upto 40% and I get this error everytime.
An error occurred while collecting items to be installed
session context was:(profile=PlatformProfile, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
Unable to read repository at http://dl.google.com/eclipse/plugin/core/3.7/plugins/com.google.appengine.eclipse.core_3.0.1.v201206290132-rel-r37.jar.
Connection reset
Needed Help to install ADT plugin for Eclipse for Android Developement.

A: If you are using Windows, try to install the ADT after execute Eclipse as administrator

A: Solved the Issue.
For anybody getting this type of errors.
Steps to Solve :
1 : Download the Eclipse ADT Plugin zip file from the website developer.android.com
2 : Extract the zip file.
3 :  Copy the contents of plugins folder into /usr/lib/eclipse/plugins (On Linux and /Applications/eclipse/plugins on Mac )
Contents are :
com.android.ide.eclipse.adt_20.0.0.v201206242043-391819.jar
com.android.ide.eclipse.base_20.0.0.v201206242043-391819.jar
com.android.ide.eclipse.ddms_20.0.0.v201206242043-391819.jar
com.android.ide.eclipse.gldebugger_20.0.0.v201206242043-391819.jar
com.android.ide.eclipse.hierarchyviewer_20.0.0.v201206242043-391819.jar
com.android.ide.eclipse.ndk_20.0.0.v201206242043-391819.jar
com.android.ide.eclipse.traceview_20.0.0.v201206242043-391819.jar
overlay.com.android.ide.eclipse.adt.overlay_20.0.0.v201206242043-391819.jar

4 : Now restart the eclipse , Go to "Install new Software" Add the link "http://dl-ssl.google.com/eclipse/plugins" Then install it as mentioned on the android developers site.


text:
Q: Select all if blah.. else select all where blah I have an enum like:
typedef NS_ENUM(int, name) {
    kAll,
    kFirstType,
    kSecondType
};

then I do:
if (type == kAll) {
        query = [NSString stringWithFormat:@"SELECT * FROM TABLE WHERE ID = %ld", itemID];
    }
    else {
        query = [NSString stringWithFormat:@"SELECT * FROM TABLE WHERE ID = %ld AND type = %ld", itemID, type];
    }

How can I combine this into ONE query like:
"SELECT CASE WHEN type = 0 THEN (SELECT ALL ITEMS) ELSE '* WHERE ID = blah AND type = meh' END;

How would I do that with a query? I don't want the if (blah) then query = meh.. else query = other..

A: You could do this:
select * from myTable where id = :id and (:type = 0 or :type = type)

Or this:
select * from myTable where id = ? and (? in (0, type))

But I wouldn't expect the second one in particular to perform well. I haven't tested either version.
There's no way to change the structure of the WHERE clause from within the statement. You'd need some kind of eval function, which isn't built-in to SQLite. You can find the source code for a loadable eval extension in the SQLite source tree if you want, but that seems like overkill.


text:
Q: Is it natural to say "feel embarrassed"? Guy 1: So how are you? It's been a long time.
Guy 2: I'm okay. Yeah, I just feel a little embarrassed about everything that happened last time. I hope you can forgive me.
Is the use of "feel" natural here? Or would it be much more natural if the sentence was "Yeah, I'm just a little embarrassed about everything that happened last time."?


text:
Q: Classpath and plug-in dependencies in Java Eclipse I have got a Java Maven project in Eclipse which imports some external plug-ins for which I do not have the source code.
One of those plug-ins should be able to access some of the public classes from my project. The package/class name can be defined dynamically.
After some research I found this thread which says, that exported packages should be visible to other plug-ins. But unfortunately this does not work in my case.
Does anybody have any idea how I could give the imported plugin access to my classes?
Thanks!


text: Q: Enumerate handles open by process using process id or name without NtQueryInformationProcess Is there any way to know handle/handles open by any process if we know process id and name without using any API from ntdll.dll e.g. NtQueryInformationProcess.


text:
Q: Overflow container stops access to slider touch/swipe Hope you can help. I'm a bit of a newb and despite research have not found a way of fixing my issue. I have a transparent navigation bar sitting over the top of a slider that has touch swipe functionality as well as arrow nav buttons to click next/previous. Directly under the transparent nav is a tab that shows/hides text content (using jquery). See the test link below.
The problem is that in order for the show/hide to disappear behind the nav, it needs to sit in a div container that has overflow:hidden. This is the container coloured red in my test below. Unfortunately on mobile, this container covers most of the page and prevents the touch swipe functionality over most of the page. If anyone can offer any suggestions on whether it's possible to collapse the red containing div when you close the show/hide, I'd be very grateful.
http://the3rdobject.com/test/index.html

A: What you need is a callback. On that callback you can show/hide the div that bothers you.
More details here: http://api.jquery.com/toggle/.
What interest you is this part:
 $( "#clickme" ).click(function() {
     $( "#book" ).toggle( "slow", function() {
        // Animation complete.
     });
 });

In your case you probably want to do something like this:
 $( "#clickme" ).click(function() {
     $( "#book" ).toggle( "slow", function() {
        $("#botheringDivId").hide();
     });
 });

You may need to adapt it a bit to fit your needs but that should be easy.


text:
Q: Get Month of the date in Hive and group by department i have three columns StartDate,Department,Tripduration(StartDate Column is in "MM/dd/yyyy" need to be converted "yyyy-MM-dd")

The requirement is to query the data for each month & grouped by the department

Any help would be appreciated?

A: you can convert "MM/dd/yyyy" to "yyyy-MM-dd" this way.
select TO_DATE(FROM_UNIXTIME(UNIX_TIMESTAMP(StartDate, 'dd/MM/yyyy'))) as month
from your_table;

and group by (month & department)
select
  MONTH(TO_DATE(FROM_UNIXTIME(UNIX_TIMESTAMP(StartDate, 'dd/MM/yyyy')))) as month,
  Department,
  sum(Tripduration) --or avg or whatever you want
from your_table
group by MONTH(TO_DATE(FROM_UNIXTIME(UNIX_TIMESTAMP(StartDate, 'dd/MM/yyyy')))), Department;


text:
Q: Fast Enumeration with NSMutableDictionary I found a weird issue with 64 bit platform, when i tried to enumerate NSMutableDictionary.I have a code as follows,
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSArray *expectedKeysArray = [NSArray arrayWithObjects:@"K1", @"K2", @"K3", @"K4", @"K5", nil];
NSArray *expectedValuesArray = [NSArray arrayWithObjects:@"V1", @"V2", @"V3", @"V4", @"V5", nil];
for (int i = 0; i < [expectedKeysArray count]; i++) {
    [dictionary setObject:[expectedValuesArray objectAtIndex:i]
                        forKey:[expectedKeysArray objectAtIndex:i]];
}
 for (NSString *key in dictionary) {
    NSLog(@"key %@",key);

}

When i ran the above code in 32 bit simulator,line within the for loop
 NSLog(@"key %@",key);

is getting executed and fast enumeration works fine.But when i run the above code in 64 bit simulator, it doesn't even enter the for loop and fast enumeration doesn't work.Did anyone face a similar issue?.I'm using Xcode 5.1,with iOS 7.1


text:
Q: Determinant of transition matrix problem. Consider continuous Markov chain with finite state space. Let's $P(t)$ demote it's transition matrix at moment $t$.
We want to prove that for all non-zeroes $$ we have : $det P(t) \ne 0$.
I think this isn't right. If we consider $P = \xi \xi^{т}$, where $\xi = \{1/\sqrt{2},1/\sqrt{2}\}$ then all powers of this matrix have zero determinant
Maybe I miss something?


text:
Q: How to get my current user logon in MS Access forms I have initial form logon to Validate user details to access my MS Access database.
Now I have a requirement in another form, If I choose same logon user from a combo box then command button should be enabled in the form so how I validate my initial logon user who logged in with another form Textbox in my access db.
So I researched about this but could not get the useful scenario - Can some please help me how I can acheive this details ..Thanks!

A: Whilst the API approach @Remou suggests works, I have moved to this technique
Public Function GetUserName() As String
    Dim wshNet As Object
    Set wshNet = CreateObject("WScript.Network")
    GetUserName = wshNet.UserName
    Set wshNet = Nothing
End Function

I believe it to be more robust than calling an API

A: After the user completes her login, hide rather than close the login form.  With the form hidden, code in your other form can still read values from the login form.
To hide a form named frmLogin:
DoCmd.OpenForm "frmLogin",acNormal,,,,acHidden

or
DoCmd.OpenForm "frmLogin",acNormal,WindowMode:=acHidden

If the hidden frmLogin includes a text box named txtUserName, you can inspect its value like this:
Debug.Print Forms!frmLogin!txtUserName

I based this answer on the assumption you created your own security framework in your Access database application.  But that point is unclear.  If you're using Access ULS (user level security), which requires the older MDB format database, the CurrentUser() function which Matt mentioned will give you the user's Access security name.  However, if that is the approach you're using, I don't understand why you would need a separate login form.
So your question is unclear.  If none of the answers is satisfactory, please edit your question to include an explanation of the security/login strategy you're using.

A: Record the logged on user in a public variable once validated and then you can test this against the "CurrentUser()" command to see if they match on next form.
NOTE: Only use this method if each user has their own copy of the front-end (do not use if everyone is sharing the same front-end, although with good practice they shouldn't be)


text:
Q: nautilus: no modification, access dates for folder when looking folder properties I dont see properties like Modification date or accessed date.
screenshot (folder properties on right)
I am on ubuntu 12.04

A: Okay, my bad.
The image on the right appears to refer to an inode type as opposed to an html type.
It appears that the basic properties cannot be resolved with an inode type.


text:
Q: Trigger popup on link click How can I trigger a popup on link/button click? I'm using the Sumome page builder and I would like to trigger it on link click. I saw it used on other websites like this: <button data-sumome-listbuilder-id="idnumber">Join</button>
But for some reason, when I insert my Sumome idnumber, it doesn't work (nothing pops up, it just displays a button that does nothing)

A: Maybe your button stop of working when you changed it's id because there was an event-listener attached on the previous id (when you change it you must update the event-listener script aswell). It's hard to be sure without a piece of code to check. Anyway, if you want to build a new pop-up instead of editing the current ones:
Pop-ups are blocked on browsers by default and take some seconds to load. The best option is use a modal div with position:fixed instead and hide/show it using display:none / display:inline-block

function show(){
  document.getElementById("zero").style.display = "inline-block";
  document.getElementById("aa").style.display = "inline-block";
}

function hide() {
  document.getElementById("zero").style.display = "none";
  document.getElementById("aa").style.display = "none";
}
body {
  height: 100%;
  background: honeydew;
}

#zero {
  top: 0;
  left: 0;
  position: fixed;
  background: black;
  opacity: 0.4;
  width: 100%;
  height: 100%;
  pointer-events: none;;
}

#aa {
  font-weight: bold;
  position:fixed;
  left:0;
  right:0;
  margin: auto;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
  width: 200px;
  height: auto;
  padding: 15px;
  background: #fff;
  box-sizing: content-box;
  border: 3px solid black;
}

a, a:visited, a:focus {
  margin-right: 10px;
  color: white;
  background: crimson;
  padding: 5px;
  border: 3px solid black;
  text-decoration: none;
}

a:active {
  background: darkred;
}

#text {
  text-align: justify;
    -webkit-column-count: 3; /* Chrome, Safari, Opera */
    -moz-column-count: 3; /* Firefox */
    column-count: 3;
}

.left {
  float: left;
}

.right {
  float: right;
}

click to openLorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam nibh. Nunc varius facilisis eros. Sed erat. In in velit quis arcu ornare laoreet. Curabitur adipiscing luctus massa. Integer ut purus ac augue commodo commodo. Nunc nec mi eu justo tempor consectetuer. Etiam vitae nisl. In dignissim lacus ut ante. Cras elit lectus, bibendum a, adipiscing vitae, commodo et, dui. Ut tincidunt tortor. Donec nonummy, enim in lacinia pulvinar, velit tellus scelerisque augue, ac posuere libero urna eget neque. Cras ipsum. Vestibulum pretium, lectus nec venenatis volutpat, purus lectus ultrices risus, a condimentum risus mi et quam. Pellentesque auctor fringilla neque. Duis eu massa ut lorem iaculis vestibulum. Maecenas facilisis elit sed justo. Quisque volutpat malesuada velit.

x

content A

content B

content C

content D

Anyway, if you want a real pop-up window, you can do it like this:
HTML
click to open

JAVASCRIPT
function pop() { window.open('http://www.example.com','pop',"height=590,width=450,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=auto,resizable=yes,copyhistory=no"); }

codepen DEMO
As you see on the Javascript line, there's several attributes like 'width' and 'height' to customize your pop-up window.

A: you can try javascript. Or for fast checking use this line of code,
test

or this one,
<button onclick="alert('fine')">Click me</button>


text:
Q: I want to get the related client name through a hasManyThrough relationship I need to print on the view the name of the client that refers to the tasks of its projects through the interim relationship called projects.
I used a hasManyThrough relationship because I needed to get more information. Now I need to get the client name as described above.
Relationship defined in the Client model:
public function projects()
    {
        return $this->hasMany(Project::class);
    }

public function tasks()
    {
        return $this->hasManyThrough(Task::class, Project::class);
    }

Relationship defined in the Project model:
public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function tasks()
    {
        return $this->hasMany(Task::class);
    }

Relationship defined in the Task model:
public function project()
    {
        return $this->belongsTo(Project::class);
    }

I've tried this but can't get the client name
TaskController:
public function index($id = NULL)
    {
        $tasks = Task::all();
        $project = Project::find($id)->load(['tasks']);
        return view('task.index', compact('tasks','project'));
    }

In the task view of that task I want to see the following line:
"List of tasks related projects to (client name)"
Anyone who can kindly help me?

clients
id - integer
name - string
projects
id - integer
client_id - integer
name - string
tasks
id - integer
project_id - integer
title - string

A: If I understood correctly, you need first to add a relationship on Task model:
    public function client()
    {
        return $this->hasOneThrough(Client::class, Project::class);
    }

this relationship will allow you to get the client to whom the project containing this task belongs to.
Then on your TaskController :
    public function index($id = NULL)
    {
        $tasks = Task::with(['project', 'client'])->get();
        $project = Project::find($id)->load(['tasks']);
        return view('task.index', compact('tasks','project'));
    }

Now the $tasks will have within them the project info + client info


text:
Q: 'Use Layer Extent' not available in v.voronoi I want to follow the accepted answer to the question, "Voronoi Diagram on a given polygon using QGIS".
However, in my QGIS (3.16.14-Hannover), in v.voronoi I don't have the option 'Use Layer Extent'. The closest I have is 'Calculate From Layer', but this just produces a bounding box based on the contents of the layer, rather than using the polygon contained in the layer as a hull.
Do I have to upgrade something?

A: Set GRASS GIS 7 region extent to the extent of your polygon layer to get voronoi polygons covering the whole extent of your layer - see the red lines in the screenshot. Then use Menu Vector / Geoprocessing Tools / Intersection to clip part of the voronoi polygons outside the initial (blue) polygon.
If you need this more often, create a model for it, then you can do it in one step.

Voronoi polygons after intersection processing:


text: Q: Calling itunes web api to fetch the data I am very much new to the web API concept. I want to populate a div in my web page with the logo images of all the games of particular developer in itunes using the itunes web API. Can anyone please help me out. Thanks in advance.


text:
Q: How can I be sure I have downloaded all data from a WFS service? I need to download all data from a WFS service as CSV files and be sure I've downloaded all data.
I'm using Python to download chunks of 20 000 rows at a time:
import urllib.request
import os

download_folder = r'C:\Arenden\arter_test'

for start in range(0, 1000000, 20000): #I'm using 1000000 as stop since I dont know the row count of the service
    #For each 20 000 chunk create the url string
    req = "https://slwgeo.artdata.slu.se/geoserver/SLW/wms?service=WFS&version=1.1.0&request=GetFeature&typeName=SLW:AllSwedishOccurrences&maxFeatures=20000&startIndex={0}&outputFormat=csv".format(start)
    print(req)

    #And save the csv file
    file = os.path.join(download_folder, "allswedishoccurrences_{0}.csv".format(start))
    urllib.request.urlretrieve(req, file)

Is there a way of knowing when to stop? It just keeps going
https://slwgeo.artdata.slu.se/geoserver/SLW/wms?service=WFS&version=1.1.0&request=GetFeature&typeName=SLW:AllSwedishOccurrences&count=20000&startIndex=0&outputFormat=csv
https://slwgeo.artdata.slu.se/geoserver/SLW/wms?service=WFS&version=1.1.0&request=GetFeature&typeName=SLW:AllSwedishOccurrences&count=20000&startIndex=20000&outputFormat=csv
...

There are no duplicates in the csv files:
import pandas as pd

df1 = pd.read_csv(r'/home/bera/GIS/wrk/Species/csvfiles/allswedishoccurrences_20000-40000.csv')
#df1.shape
#(20000, 78)

df2 = pd.read_csv(r'/home/bera/GIS/wrk/Species/csvfiles/allswedishoccurrences_40000-60000.csv')
#df2.shape
#(20000, 78)

#df1.equals(df2)
#False

df3 = pd.concat([df1, df2])
#df3.shape
#(40000, 78)

df3 = df3.drop_duplicates()
#df3.shape
#(40000, 78)

A: Using https://slwgeo.artdata.slu.se/geoserver/SLW/wms?service=WFS&version=1.1.0&request=GetFeature&typeName=SLW:AllSwedishOccurrences&resultType=hits gives me:
<wfs:FeatureCollection numberOfFeatures="25000" timeStamp="2022-05-03T12:00:14.842Z" xsi:schemaLocation="http://www.opengis.net/wfs http://slwgeo.artdata.slu.se:8080/geoserver/schemas/wfs/1.1.0/wfs.xsd http://www.svenskalifewatch.se/ http://slwgeo.artdata.slu.se:8080/geoserver/SLW/wfs?service=WFS&version=1.1.0&request=DescribeFeatureType&typeName=SLW%3AAllSwedishOccurrences">
<gml:featureMembers>

so there are 25000 features in that collection.


text:
Q: How to add inner border radius of shadow div in react native How do i apply inner border radius to my element like below, border radius applies it to outside shadow

What mine looks like:
Code:
        const getCheckListData = (): React.ReactNode => {
    return checkListJSON.map(
        (checklist: CheckListInterface, index: number): React.ReactNode => {
            return (
                <View style={[styles.checkListTile, styles.checkListTileGreen]} key={index}>
                    <Text style={styles.checkListTileText}>{checklist.value}</Text>
                </View>
            );
        },
    );
};

    checkListTileGreen: {
            shadowColor: ThemeConfigs.defaultColors.primaryLightColor,
            shadowOpacity: ThemeConfigs.defaultCard.shadowOpacity,
        },
            checkListTile: {
            flexDirection: 'row',
            justifyContent: 'center',
            alignItems: 'center',
            flexShrink: 1,
            width: wp('28%'),
            height: hp('15%'),
            marginTop: hp('1.5%'),
            marginRight: wp('1.5%'),
            color: ThemeConfigs.defaultColors.textSecondaryColor,
            shadowOffset: {
                width: 1,
                height: 0,
            },
            elevation: 10,
            borderRadius: hp('2%'),
        },

A: Try the following:

*

*Increase your border-radius: 2% to a higher value. Lets say border-radius: 50%

*Add overflow: hidden; to your checkListTileGreen class


text:
Q: Each of segments intersects with at least half of the others, prove that there is a segment that intersects with all segments There are a finite number of segments in $R^1$, and each of them intersects with at least half of the others, prove that there is a segment that intersects with all of segments
My ideas: 1)There is a similar problem where any two segments intersect, which is solved using the Helly theorem, but I don't know how to use Helly in this situation. 2) Use some olympiad ideas

A: Idea: Let $I_l$ be the interval with the smallest right endpoint, and $I_r$ be the interval with the largest left endpoint. By pigeonhole, there exists an interval $I$ that intersects with both $I_l$ and $I_r$. Now show $I$ intersects with all the segments.


text:
Q: Image size issue in Liferay 6.2 document and media portlet I'm facing an issue in document and media portlet liferay 6.2 since a long time. There are two scenarios -
1) I upload an image of 2MB and when I download it's size increases to 3.2MB.
2) I upload an image of 5MB and when I download it's size decreases to 500KB.
For some images, it works fine but for some images it doesn't. Any help will be highly appreciated.


text:
Q: Should I give a healing item to my follower? I've been dumping marginally useful loot onto my templar friend with my current monk.  In the latest development, I handed him my sword that was sucking a few life points from its target to heal its wielder.  Does that do any good for the follower?  If not (or if so), what items should I give to my follower?

A: It's possible that it could be of some small use, but there are a few relevant things to remember about followers and lifesteal items:

*

*They gain a 2.5x multiplier to any stat items on them (including Vitality),

*unless a concerted effort is made to boost them, deal significantly less damage than a player would,

*most lifesteal items operate on a percent of the damage done,

*Followers suffer no penalties for dying save for a brief delay before getting back up.

Even with strong weapons on the Scoundrel, from what I've seen it's not a great benefit, due to the low damage potential of even the most kitted out followers.
The best things to stick on followers for general use are still weapons with decent DPS that you don't think you could sell for much, as a small amount of damage is still extra damage; and items with large amounts of statistics - the Scoundrel can turn a +50 Dexterity weapon into a +125 Dexterity weapon, the Templar can turn a +50 Vitality shield into a +125 Vitality shield, so on and so forth.

A: Well, the first question is, how often is your Templar actually dying on you?
I don't know about you, but for me, the Templar only really dies when the shit is hitting the fan, or if he gets burst down by standing between me and some Fallen Maniacs or other similar one-shot gimmicks. In either of those cases, a little bit of extra life on hit just isn't going to save him.
I find that your best bet in gearing your companions is to prioritize, more or less in order: Weapon DPS, Primary Stat, Vitality, and Magic Find/Gold Find/+XP. If your follower has 'enough' defense to not be dying regularly, stacking MF/GF/XP is probably the most useful thing you can do, simply because it's the only one that directly benefits you. They get the vast majority of their damage output from having an up-to-date weapon, and even then, their DPS is generally pretty pathetic -  the main advantage of a follower is the CC, Healing, or Buffs they provide for the player. In my experience, your best bet is to play to that strength, and gear accordingly.

A: The way you "build" and equip your companion entirely depends on what you need him for.
I don't know for a monk, but as a wizard, I chose the templar as a tank, so he must stay alive as long as possible.  Therefore I gave him all the defensive skills I could find in his selection and equiped him with items providing vitality and armor.  It seems that the templar doesn't deal any damages anyway, so why bother equiping him in this direction ?

A: I find it can be useful to gear up your Follower with life boosting equipment, especially if they're a few levels behind or have otherwise underpowered gear.  I always keep an eye on my Follower's health bar during battle, just in case.
According to the Diablo 3 Wiki, Followers don't die and require resurrection.  If they run out of life, they just take off for a while and come back on their own.


text:
Q: Why am I getting an "Items Collection Must Be Empty" exception with nested DataGrids? I'm using nested DataGrids to manage classes with nested class collections.
Each nested class is represented by a cell template.
This is a minimal mockup which reproduces the issue :
using System.ComponentModel;
using System.Linq;

namespace ICMBE{
    public class Outer : INotifyPropertyChanged {
        public event PropertyChangedEventHandler PropertyChanged;

        private Nested1[ ] _categories = Enumerable.Range( 1, 1
                    ).Select( n => new Nested1( ) ).ToArray( );

        public Nested1[ ] Categories {
            get { return this._categories; }
        }
    }

    public class Nested1 : INotifyPropertyChanged {
        public event PropertyChangedEventHandler PropertyChanged;

        private Nested2[ ] _questions = Enumerable.Range( 1, 5
                    ).Select( n => new Nested2( ) ).ToArray( );

        public Nested2[ ] Questions {
            get { return this._questions; }
        }
    }

    public class Nested2 : INotifyPropertyChanged {
        public event PropertyChangedEventHandler PropertyChanged;

        private Nested3[] _answers = Enumerable.Range( 1, 5
                ).Select( n => new Nested3( ) ).ToArray( );

        public Nested3[ ] Answers {
            get { return this._answers; }
        }
    }

    public class Nested3 : INotifyPropertyChanged {
        public event PropertyChangedEventHandler PropertyChanged;

        private string _foo = "Bar";

        public string Foo { get { return this._foo; } }
    }
}

Create a field value and expose it in the application :
using System.ComponentModel;

namespace IMCBE{
    public partial class App : INotifyPropertyChanged {
        public event PropertyChangedEventHandler PropertyChanged;
        private Outer _outer = new Outer( );
    }
}

namespace IMCBE{
public partial class Program {
        /// <summary>
        /// Bla bla bla
        /// </summary>
        public Outer Outer{
            get { return this._outer; }
        }
    }
}

Using this window -
<Window
    x:Class="ICMBE.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Controls="clr-namespace:WPFTools.Controls;assembly=WPFTools"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WhyAreMyRowNumbersChanging"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <!-- Answers -->
        <DataTemplate x:Key="dtAnswerTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100" />
                    <ColumnDefinition Width="5" />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <ToggleButton>
                    <Viewbox>
                        <TextBlock Text="Correct" />
                    </Viewbox>
                </ToggleButton>
                <TextBox Text="Bar" />
            </Grid>
        </DataTemplate>

        <!-- Questions -->
        <DataTemplate x:Key="dtQuestionTemplate">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="25" />
                    <RowDefinition Height="5" />
                    <RowDefinition Height="25" />
                    <RowDefinition Height="5" />
                    <RowDefinition Height="50" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="128" />
                    <ColumnDefinition Width="5" />
                    <ColumnDefinition Width="128" />
                    <ColumnDefinition Width="5" />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <Viewbox Grid.ColumnSpan="3">
                    <TextBlock Text="Question" />
                </Viewbox>
                <TextBox Grid.Row="2" Grid.ColumnSpan="3" Text="Foo" />
                <ToggleButton Grid.Row="4">
                    <Viewbox>
                        <TextBlock Text="Bonus" />
                    </Viewbox>
                </ToggleButton>
                <Button Grid.Row="4" Grid.Column="2" />
                <Viewbox Grid.Column="4">
                    <TextBlock Text="Answers" />
                </Viewbox>
                <DataGrid
                    AutoGenerateColumns="False" CanUserAddRows="False"
                    CanUserDeleteRows="False" Grid.Column="4"
                    Grid.RowSpan="4" ItemsSource="{Binding Nested}">
                    <DataGridTemplateColumn
                        Width="*"
                        CellTemplate="{StaticResource dtAnswerTemplate}" />
                </DataGrid>
            </Grid>
        </DataTemplate>

        <!-- Categories -->
        <DataTemplate x:Key="dtCategoryTemplate">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="25" />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="256" />
                    <ColumnDefinition Width="5" />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <Viewbox>
                    <TextBlock Text="Outer"/>
                </Viewbox>
                <DataGrid
                    AutoGenerateColumns="False" CanUserAddRows="False"
                    CanUserDeleteRows="False" Grid.Row="2"
                    Grid.ColumnSpan="3" HeadersVisibility="None"
                    ItemsSource="{Binding Nested}">
                    <DataGrid.Columns>
                        <DataGridTemplateColumn
                            Width="*"
                            CellTemplate="{StaticResource dtQuestionTemplate}" />
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </DataTemplate>
    </Window.Resources>
    <DataGrid
        Grid.Row="1"
        ItemsSource="{Binding Outer.Nested, Source={x:Static Application.Current}}"
        MaxHeight="Infinity" ScrollViewer.CanContentScroll="True">
        <DataGrid.Columns>
            <DataGridTemplateColumn
                Width="*" CellTemplate="{StaticResource dtCategoryTemplate}" />
        </DataGrid.Columns>
    </DataGrid>
</Window>

Running this causes the program to just crash. The exception is "Items collection must be empty".
From what I've read, this happens if you set the Items and ItemsSource are both set, but this isn't happening here.
Why is this crash occurring?

A:
From what I've read, this happens if you set the Items and ItemsSource
  are both set.

This is actually the cause of the error, because you forgot to put a <DataGrid.Columns> tag  around the DataGridTemplateColumn in the DataGrid in the dtQuestionTemplate DataTemplate.
It should look like this:
<DataGrid ... ItemsSource="{Binding Nested}">
    <DataGrid.Columns>
        <DataGridTemplateColumn
            Width="*" CellTemplate="{StaticResource dtAnswerTemplate}" />
    </DataGrid.Columns>
</DataGrid>


text:
Q: How to integrate get_post_time with date_i18n function? I have date format and would like to translate to another language with date_i18n function how can I integrate with get_post_time here is my code :
$time = get_post_time('F j, Y', true,$newspost['ID']);

A: Use the fourth parameter for get_post_time():
$time = get_post_time(
    'F j, Y',      // format
    TRUE,          // GMT
    get_the_ID(),  // Post ID
    TRUE           // translate, use date_i18n()
);

get_post_time() calls mysql2date() internally, and it passes the $translate argument through. In mysql2date() we find this:
if ( $translate )
    return date_i18n( $format, $i );

So, all you need is a single TRUE.
For a test, try this:
add_filter( 'the_content', 'wpse_100266_i18n_time' );

/**
 * Prepend the post content with translated post time.
 *
 * @wp-hook the_content
 * @param   string $content
 * @return  string
 */
function wpse_100266_i18n_time( $content )
{
    $time = get_post_time(
        'F j, Y',      // format
        TRUE,          // GMT
        get_the_ID(),  // Post ID
        TRUE           // translate, use date_i18n()
    );

    return "<p>$time</p>$content";
}

Then install at least one other language and the plugin WCM User Language Switcher. Viewing the front end, we get different month names when we switch the language now.
get_post_modified_time() works with the same arguments.


text:
Q: Python Jupyter Notebook pygame Image: FileNotFoundError: No such file or directory I just started programming. I watched a you tube tutorial on how to create a hangman game with pygame.
When it comes to loading images I get this:
***FileNotFoundError**
Traceback (most recent call last)
<ipython-input-1-03373876a9dc> in <module>
     29 images = []
     30 for i in range(7):
---> 31     image = pygame.image.load("hangman" + str(i) + ".png")
     32     images.append(image)
     33
FileNotFoundError: No such file or directory.*

The images (hangman 1...7)are located in the same folder as the ipynb
for example the first one
(C:\Users\basti\Documents\hangman\hangman1.png)
Can somebody help me with this?
Thanks in advance :)

A: range(7) gives you an iterator from 0 to 6. If your images start at 1 and end at 7, you should use range(1,8)


text:
Q: Unity RegisterInstance recreating singleton every request I'm trying to set up an object to be a singleton using Unity, but the object is being created every time I make a request.
public class ShareTubeRoomRepository : IShareTubeRoomRepository
{
    public ShareTubeRoomRepository()
    {
        //load my base data
    }

Unity Configuration
    public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterInstance<IShareTubeRoomRepository>(new ShareTubeRoomRepository(), new ContainerControlledLifetimeManager());
    }

I have also tried the following:
container.RegisterType<IShareTubeRoomRepository, ShareTubeRoomRepository>(new ContainerControlledLifetimeManager());

I put a breakpoint at the constructor for the repository and it's being called every time a page loads in my MVC application. Every resource I've found has said that these methods of registering the type should create it as a singleton, so why is it recreating this instance every request?
I tried making the data that I want to store static so it won't get refreshed, and instantiating it in the static constructor, but even the static constructor is getting called multiple times. According to this answer: https://stackoverflow.com/a/5119154/526704 that shouldn't be happening, right?

A:
I tried making the data that I want to store static so it won't get
  refreshed, and instantiating it in the static constructor, but even
  the static constructor is getting called multiple times.

That means you've got multiple AppDomains in your application. I suppose you're running it on IIS with multiple workers. In that case it will create a singleton per AppDomain. Make sure you use a single AppDomain.

A: I solved this by creating a property that relied on using the HttpContext.Current.Application dictionary (https://stackoverflow.com/a/3733549/526704)
System.Web.HttpContext.Current.Application.Lock();
System.Web.HttpContext.Current.Application["Name"] = "Value";
System.Web.HttpContext.Current.Application.UnLock();


text:
Q: Disable button focus border I have a Jquery Mobile page with buttons
When set the focus to a button with Tab, there is a blue border... (Only with IE when browsing in a WPF WebBrowser control)

I would like  to disable this border in the css, because when I click in the page, it automatically focus my first button...
It seems simple but I can't manage to do it...
For some reasons, I can't inspect the page to know the css property to disable.
What is the equivalent of "-moz-focus-inner" for Internet Explorer ?


text:
Q: Add log4j maven dependency to war without having it in compile time Our application uses slf4j, but has dependency to

*

*slf4j api

*slf4j over log4j

*log4j

The problem is that very often IDE imports classes from log4j and not from slf4j.
Ideally, i want to have only slf4j api as a maven dependency for my application and pack slf4j binding with log4j only at the time i building a war.
I found several solutions so far:

*

*Add libs to WEB-INF/lib folder. This is bad, because i have no maven dependency control and have to store binary in my repo which is not the best thing to do.

*Use maven-war plugin with overlays. But as i understand adding dependency to overlay will require to declare dependency (at least as compile)

Is it ok to have only dependency for slf4j api? How to package other dependencies to war without declaring them as project dependencies?
Thanks!

A: Please simply specify dependency to slf4j-log4j in  runtime scope.
So during compile and test time class from runtime scope  will not be available.
Also in IDE it shouldn't be visible - I checked it in IntelliJ.
Of course all artifacts with runtime scope will be put in WEB-INF/lib directory.
Example:
    ...
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
        <scope>runtime</scope>
    </dependency>
    ...


text:
Q: How to form a row complete Latin squares of order odd? Hello dear mathematicians
How to form a row complete latin square of order odd.
I found some answers for Latin squares of order even.
Regards

A: Perhaps the best known way of constructing row complete latin squares is via sequencable groups. A group is sequencable if its elements can be ordered, say as $g_0,g_1,\ldots,g_{n-1}$, so that the map $g_i \mapsto g_i^{-1}g_{i+1}$ (for $0 \leq i \leq n-1$) is injective. We call such an ordering of the elements of a group a directed terrace.
Given a directed terrace $g_0,g_1,\ldots,g_{n-1}$ the latin square $L$ defined by $L_{i,j} = g_i^{-1}g_{i+1}$ is row complete (for a proof of this fact see the introduction to M.A. Ollis' dynamic survey on sequencable groups).
But now we need to ask what we know about sequencable groups. Keedwell conjectured that every nonabelian group of order at least 10 is sequencable. The conjecture has been confirmed for all nonabelian groups of odd order at most 555.
Which leaves us with our final question: for which odd orders do we know there exists a nonabelian group? The answer to this question is nontrivial, and is given in this Mathoverflow question/answer.


text:
Q: What is a good LaTeX editor for brainstorming? Short Background: I enjoy using MS word when drafting and doing research. The ability to manipulate objects like matrices and series is extremely fast as I see them as I would write them, and yet I can tweak terms with ease, use copy and paste on pieces of an object, disect at the object level and move components around, etc....
Additionally, I can seemlessly write in MathML in the same frame as I'm manipulation objects. (So instead of editing a TeX file or ML File and then looking at the compiled output, I can in the output file itself, write MathML and have it autocompile there itself (no time wasted switching frames or coordinating place in code with location of object)
Whats a LaTeX editor that supports this?
BakomaTeX, gets an honorable mention as it supports object level manipulation, but the production of these objects needs to happen in the separate code (or via their drop down menus) and can't be done inline.
Is there a LaTeX editor that combines real time inLine equation compilation and  object level manipulation in one frame?

I guess technically nothing stops me from secretly using MS Word to think, and then quietly (but a little painfully) switching to LaTeX when another human will be involved.
But It would be nice if the language I present and publish in, was the same that I worked in.


text:
Q: Process.Start() does not work unless stepping over using F10 I would like to start a process using:
ProcessStartInfo createProject = new ProcessStartInfo();
createProject.FileName = exePath;
createProject.UseShellExecute = false;
createProject.WorkingDirectory = projectDirectory;
createProject.Arguments = exeArguments;

try
{
    // Start the process with the info specified.
    System.Diagnostics.Process.Start(createProject);
}
catch (IOException eX)
{
    // Log error.
    MessageBox.Show("Unable to create project", "Error Creating Project");

}

When I put a breakpoint at the line of Process.Start() and continue with step over by pressing F10, then the process runs without any problem.
However when I press F5 at the breakpoint or just run my application without any breakpoints, I get a "Your application has stopped working" dialog, without my application throwing any exception.
I tried also using Thread.Sleep() before the Process.Start() which has no result.
I really wonder what causes this problem.
EDIT: After I check the event viewer, I see that the faulting module is MSVCR90.dll. I have the version 9.0.30729.6161 installed.

A: This answer is for the one who is interested in the solution of the problem not the pragmatic discussion on the question itself:
Actually the answer was in the question itself and I got it after @rene raised one question.
Process runs when I step over because then program has time to finish its job. But when I press F5 it crashes because the process itself is not completed. I used following code:
ProcessStartInfo createProject = new ProcessStartInfo();
createProject.FileName = exePath;
createProject.UseShellExecute = false;
createProject.WorkingDirectory = projectDirectory;
createProject.Arguments = exeArguments;

try
{
    using (System.Diagnostics.Process exeProcess = System.Diagnostics.Process.Start(createProject ))
          {
             exeProcess.WaitForExit();
          }
}
catch (IOException eX)
{
    // Log error.
    MessageBox.Show("Unable to create project", "Error Creating Project");

}

This is the reason also why it doesn't throw any exception.
Thanks to @rene again!

A: Check your event log (with eventvwr.exe) to see if the process you're starting is hitting anything critical.
If the started process is also yours, you can add logging to it, or use System.Diagnostics.Debugger.Launch() to have it launch a debugger at startup -- or use gflags to break into it with WinDbg or similar on startup.


text:
Q: Calculate frequency of values spread across multiple columns in R I have a data set similar to this tibble:
  ~PatientID, ~A1, ~A2, ~B1, ~B2,
  #--|---|---|---|---
 101, "01:01", "02:01", "07:01", "51:01",
 102, "02:01", "03:01", "08:01", "51:01",
 103, "01:01", "03:01", "07:01", "08:01",
 104, "03:01", "68:01", "14:01", "08:01"
 )

They are gene types for patients. Since people have two copies of each gene, there are two columns for each gene per patient (e.g. A1 & A2). I am trying to calculate the frequency of each gene. Since the genes are spread between two columns, I am having a hard time figuring this out. Is there a way to calculate frequencies across multiple columns? My desired output would look something like this for the A gene:

A_value
A_count

01:01
2

02:01
2

03:01
3

68:01
1

Would appreciate code using dplyr, since that is what I'm trying to learn!

A: We could select the columns that starts_with 'A', then reshape to 'long' format with pivot_longer and get the count
library(dplyr)
library(tidyr)
df1 %>%
     select(starts_with("A")) %>%
     pivot_longer(cols = everything(), values_to = "A_value") %>%
     count(A_value, name = "A_count")

-output
# A tibble: 4 x 2
  A_value A_count
  <chr>     <int>
1 01:01         2
2 02:01         2
3 03:01         3
4 68:01         1

Or use table after unlisting the subset of dataset in base R
table(unlist(df1[startsWith(names(df1), "A")]))

data
df1 <- structure(list(PatientID = c(101, 102, 103, 104), A1 = c("01:01",
"02:01", "01:01", "03:01"), A2 = c("02:01", "03:01", "03:01",
"68:01"), B1 = c("07:01", "08:01", "07:01", "14:01"), B2 = c("51:01",
"51:01", "08:01", "08:01")), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"))


text:
Q: methods to handle cache data in memory through multi servers I'd like to get rid of a cron working every 20 seconds to load data from database in order to cache data in memory on servers. I know it looks pretty bad so I would like to redesign for that.
I have two ideas.
Firstly, I might be able to use message queue like kafka, rabbitMQ and etc. I used to use rabbitMQ to sort out this problem with different projects. That would work.
By the way, the second method was come up with, which is redis pub/sub. It might actually work. Then I will be able to either convert all in-memory-cache into redis-cache or just update
in-memory-cache when subscribing.
Are both good approaches? Is there any better way to achieve my goal? I have to consider multi server updates at once.

A: For in memory cache, the most important point is to make data update to date between multiple servers. And there are advantages and disadvantages for MQ and Redis solution.
For MQ solution, the advantage is you cache will distributed to your application servers, which can reduce the load pressure for cache(with load balancer in front).
Disadvantage is you need to make sure you cache for each servers are synchronized. As MQ listeners are asynchronous, there may have delays for different servers. And if you server lost connection to MQ, you data will also be out of date. Also if you cached to much data, your application memory can be booming since each of your server maintains a whole cache replica.
For Redis, it will always use single data source so synchronization will not be a problem. And you don't need to use pub/sub, just load the data into Redis.
But Redis will have a huge load pressure since all servers will query cache from same Redis.
So you can compare the advantages and disadvantages for each solution based on your case.


text:
Q: Example for Berge's theorem on matching I'm reading about Berge's theorem on matching, but I think I misunderstood the theorem and definitions somehow, because I cannot make sense of the example below. In this example I've marked the matching in pink, and the alternating path in green. This is the only alternating path involving the matching that I could find, and it's clearly not an augmenting path.

I've realized that there is a bigger matching that could be obtained by taking out edge 3 and adding in edges 1 and 2. But since 1325679 is not an alternating path, shouldn't that possibility not be considered by the theorem?
=============================================
Here are the relevant theorem and definitions:

A: 132 is an augmenting path.
It is not required that an augmenting path must contain all the edges that are in your matching so far.
(In fact it doesn't have to contain any edge that is in your matching so far -- say, if you have path graph with four vertices $a-b-c-d$ and start by matching $a$ to $b$, the augmenting path you need to match the other two nodes will consist of the edge $cd$ only).


text:
Q: Android - Unable to create new Android Project I have downloaded Eclipse-Kepler for android programming. For creating an android project when I choose file->new option,I don't find any android application project in the option to choose.
how I could find it?

A: Visit Android SDK's
 and Eclipse Plugin for Android

A: Download the Eclipse ADT bundle. This way it would not be necessary to separately add the Android SDK.


text:
Q: HTTP File Download: Monitoring Download Progress I am in a situation, when I have to implement downloading of large files(up to 4GB) from a Web server: Apache 2.4.4 via HTTP protocol. I have tried several approaches, but the best solution looks to be the usage of X-SendFile module.
As I offer progress bar for file uploads, I would need to have the same feature for file downloads. So here are my questions:

*

*Is there any way, including workaround, to achieve file downloads progress monitoring?

*Is there any way, including workaround, to calculate file download transfer speed?

*Is there better way to provide efficient file downloads from a web server than usage of X-Sendfile module?

Is there better file download option in general, that would allow me to monitor file download progress? It can be a client (JavaScript) or server solution(PHP). Is there any particular web server that allows this?
Currently I use:

*

*Apache 2.4.4

*Ubuntu

Many times thanks.

A: 2 ideas (not verified):
First:
Instead of placing regular links to files (that you want to download) on your page place links like .../dowanload.php which may look sth like this:
<?php

    // download.php file
    session_start(); // if needed

    $filename = $_GET['filename']);

    header( 'Content-type: text/plain' ); // use any MIME you want here
    header( 'Content-Disposition: attachment; filename="' . htmlspecialchars($filename) . '"' );
    header( 'Pragma: no-cache' );

    // of course add some error handling

    $filename = 'c:/php/php.ini';

    $handle = fopen($filename, 'rb');

    // do not use file_get_contents as you've said files are up to 4GB - so read in chunks
    while($chunk = fread($handle, 1000)) // chunk size may depend on your filesize
    {
        echo $chunk;
        flush();
        // write progress info to the DB, or session variable in order to update progress bar
    }

    fclose($handle);
?>

This way you may keep eye on your download process. In the meantime you may write progress info to the DB/session var and update progress bar reading status from DB/session var using AJAX of course polling a script that reads progress info.
That is very simplified but I think it might work as you want.
Second:
Apache 2.4 has Lua language built in:

*

*mod_lua

*Creating hooks and scripts with mod_lua
I bet you can try to write LUA Apache handler that will monitor your download - send progress to the DB and update progress bar using PHP/AJAX taking progress info from the DB.
Similarly - there are modules for perl and even python (but not for win)

A: I see main problem in that:
In a php+apache solution output buffering may be placed in several places:

Browser <= 1 => Apache <= 2 => PHP handler <= 3 => PHP Interpreter
  process

You need to control first buffer. But directly from PHP it is impossible.
Possible solutions:
1) You can write own mini daemon which primary function will be only send files and run it on another than 80 port 8880 for example. And process downloading files and monitor output buffer from there.
Your output buffer will be only one and you can control it:

Browser <= 1 => PHP Interpreter process

2) Also you can take mod_lua and control output buffers directly from apache.
3) Also you can take nginx and control nginx output buffers using built-in perl (it is stable)
4) Try to use PHP Built-in web server and control php output buffer directly. I can't say anything about how it is stable, sorry. But you can try. ;)
I think that nginx+php+built-in perl is more stable and powerful solution.
But you can choose and maybe use other solution non in that list. I will follow this topic and waiting your final solution with interest.

A: Read and write to the database at short intervals is killing performance.
I would suggest to use sessions (incrementing the value of sent data in the loop) with which you can safely off by quite another php file, you can return data as JSON which can be used by the javascript function/plugin.


text:
Q: How to develop http proxy server with username and password authentication I want to write a http proxy with authentication in golang but I couldn't find any example.
Here is what I trid but didn't work: (I get Error parsing basic auth)
server := &http.Server{
        Addr:         "0.0.0.0:8080",
        ReadTimeout:  15 * time.Second,
        WriteTimeout: 15 * time.Second,
        Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

            b, err := httputil.DumpRequest(r, true)
            if err == nil {
                fmt.Println("dump", string(b))
            } else {
                fmt.Println("dump error", err)
            }

            u, p, ok := r.BasicAuth()
            if !ok {
                fmt.Println("Error parsing basic auth")
                w.WriteHeader(401)
                return
            }
            if u != "USERNAME"{
                fmt.Printf("Username provided is correct: %s\n", u)
                w.WriteHeader(401)
                return
            }
            if p != "PASSWORD" {
                fmt.Printf("Password provided is correct: %s\n", u)
                w.WriteHeader(401)
                return
            }
            if r.Method == http.MethodConnect {
                handleTunneling(w, r)
            } else {
                handleHTTP(w, r)
            }
        }),
        // Disable HTTP/2.
        TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
}

log.Fatal(server.ListenAndServe())

I tested the application with firefox and foxyproxy
enter image description here

A: HTTP Authentication has two headers for providing authentication information: Authorization and Proxy-Authorization.
Authorization header:
The "Authorization" header field allows a user agent to authenticate
itself with an origin server -- usually, but not necessarily, after
receiving a 401 (Unauthorized) response.  Its value consists of
credentials containing the authentication information of the user
agent for the realm of the resource being requested.

Proxy-Authorization:
The "Proxy-Authorization" header field allows the client to identify
itself (or its user) to a proxy that requires authentication.  Its
value consists of credentials containing the authentication
information of the client for the proxy and/or realm of the resource
being requested.

Request.BasicAuth() is for "Authorization" header, not for "Proxy-Authorization" header.
BasicAuth returns the username and password provided in the request's Authorization header, if the request uses HTTP Basic Authentication. See RFC 2617, Section 2.

For parsing "Proxy-Authorization" header you can copy parseBasicAuth() function from request.go.
func ProxyBasicAuth(header http.Header) (username, password string, ok bool) {
    auth := header.Get("Proxy-Authorization")
    if auth == "" {
        return "", "", false
    }
    return parseBasicAuth(auth)
}

// parseBasicAuth parses an HTTP Basic Authentication string.
// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
func parseBasicAuth(auth string) (username, password string, ok bool) {
    const prefix = "Basic "
    // Case insensitive prefix match. See Issue 22736.
    if len(auth) < len(prefix) || !asciiEqualFold(auth[:len(prefix)], prefix) {
        return "", "", false
    }
    c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
    if err != nil {
        return "", "", false
    }
    cs := string(c)
    username, password, ok = strings.Cut(cs, ":")
    if !ok {
        return "", "", false
    }
    return username, password, true
}

// EqualFold is strings.EqualFold, ASCII only. It reports whether s and t
// are equal, ASCII-case-insensitively.
func asciiEqualFold(s, t string) bool {
    if len(s) != len(t) {
        return false
    }
    for i := 0; i < len(s); i++ {
        if asciiLower(s[i]) != asciiLower(t[i]) {
            return false
        }
    }
    return true
}

// lower returns the ASCII lowercase version of b.
func asciiLower(b byte) byte {
    if 'A' <= b && b <= 'Z' {
        return b + ('a' - 'A')
    }
    return b
}

Here is the source code with minor changes. You can also check out packages like elazarl/goproxy and  snail007/goproxy.


text:
Q: is there any replacement for creating 100 labels and putting informations on it I am having a sql like shown below which will retrieve around 100's of information's and push in to datatable .Here in this question i am showing a minimal sql and display the data.Next What i did is i took all these information's and assigned to the labels and displayed like shown below

Is there any better way i can display the data as shown.In these scenario if some body wants to display again 50 information's, again i have to create 50 labels and display those information's.If i transpose the data from data table and assign those information to a gridview where i set autogenerate= true,i will not get these look and feel.DO i have a better way to display these readonly informations.Is there any way i can design a gridview and show all these informations in to it

A: Repeater controls did the magic,thanks Webruster


text:
Q: Terraform module structure I had a flat structure of all my .tf files and want to migrate to a folder (i.e. module) based set up so that my code is clearer.
For example I have moved my instance and elastic IP (eip) definitions in separate folders
/terraform
 ../instance
   ../instance.tf
 ../eip
    ../eip.tf

In my instance.tf:
resource "aws_instance" "rancher-node-production" {}

In my eip.tf:
module "instance" {
  source = "../instance"
}

resource "aws_eip" "rancher-node-production-eip" {
  instance = "${module.instance.rancher-node-production.id}"

However when running terraform plan:

Error: resource 'aws_eip.rancher-node-production-eip' config: "rancher-node-production.id" is not a valid output for module "instance"

A: Think of modules as black boxes that you can't "reach" into. To get data out of a module, that module needs to export that data with an output. So in your case, you need to declare the rancher-node-production id as an output of the instance module.
If you look at the error you're getting, that's exactly what it's saying: rancher-node-production.id is not a valid output of the module (because you never defined it as an output).
Anyway here's what it would look like.
# instance.tf
resource "aws_instance" "rancher-node-production" {}

output "rancher-node-production" {
    value = {
        id = "${aws_instance.rancher-node-production.id}"
    }
}

Hope that fixes it for you.