text:
Q: Http status 404: Not found error on File Upload The file i'm uploading is 55MB. Max file size allowed is 49MB. My code is:
private void AddFilePartToVault(FileInfo fileInfo, long folderId,
                                WebServiceManager manager)
{
    Guid guid = Guid.Empty;

    using(FileStream stream = new FileStream(fileInfo.FullName,
                               FileMode.Open,FileAccess.Read))
    {

        ByteArray array = new ByteArray();
        array.Bytes= new byte[MaxFileSize];

        long unreadBytes;
        while ((unreadBytes = stream.Length-stream.Position)>0)
        {

           if (unreadBytes < MaxFileSize)
           array.Bytes=new byte[unreadBytes];

            stream.Read(array.Bytes,0,array.Bytes.Length);
            try
            {
                guid = manager.DocumentService.UploadFilePart(guid, array);
            }
            catch (System.Net.WebException we)
            {
                MessageBox.Show(we.Message);
            }
       }

Using this, the second part of 6MB is uploaded and the first 49MB is not uploaded. Throws wen exception Http status 404 Not found.


text:
Q: Does Meilisearch have a limit for how many results it can give when searching? I have a model, let's call it Entry.
In a view, I have a paginated table (35 per page) with a search bar that lists every entry.
When the view loads, meilisearch is called to retrieve the first page of results. This is done with a search query using the search bar's value (it starts out empty). The initial query to the search endpoint is q="", limit=35, offset=0.
When I click on the pagination buttons, meilisearch is called again, using the page number for the offset. For example, for page 2 the query should be q="", limit=35, offset=35.
This works up until page 30. Then no results are shown, even though I have more than 100 pages worth of entries in my database.

I didn't know why this happened and assumed it was something weird going on with the laravel/scout or meilisearch/meilisearch-php. After some debugging, I found nothing and decided to run the query myself using cURL.
curl \
    -H "Authorization: Bearer my-meilisearch-key" \
    -H "Content-type: application/json" \
    http://127.0.0.1:7700/indexes/my-index/search
    -d '{"q":"","limit":5,"offset":1000}'

The results are below.

Just to be clear, it I had used offset: 999, the search would have returned 1 hit. 1000 is a very peculiar number so I'm wondering if there's a configuration value somewhere that I could tweak to get as many results as I possibly can?

A: After asking around, I got the answer I needed on Discord by the user Rapand.

As I suspected, Meilisearch did have a default 1000 results per search limit. This is configured by the maxTotalHits pagination option. To quote from their documentation :

maxTotalHits takes priority over search parameters such as limit, offset, hitsPerPage, and page.
For example, if you set maxTotalHits to 100, you will not be able to access search results beyond 100 no matter the value configured for offset.

To update my pagination's limits, I just ran
curl \
    -X PATCH 'http://localhost:7700/indexes/my-index/settings/pagination' \
    -H 'Authorization: Bearer my-meilisearch-key' \
    -H 'Content-type: application/json' \
    -d '{"maxTotalHits": 20000}'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding legends to two variable line graph - ggplot2 R I have a dataframe named data with index, mean and median as variables. I have created the graph with this code.
ggplot(data, aes(x = index)) +
  geom_line(aes(y = median), size = 1, colour="firebrick") +
  geom_line(aes(y = mean), size = 1, colour = "dodgerblue4") + geom_point(size = 2, aes(y = median), colour = 'firebrick' ) +
  geom_point(size = 2, aes(y = mean), colour = 'dodgerblue4' )

I want to add legend to this graph for median and mean. I am able to find legends only for factor of single variable. But not able to do it for two variables.
I am trying this,
scale_colour_manual("", breaks = c("Median", "Mean"),values = c("firebrick", "dodgerblue4"))

But no effect in the graph.  Can anybody help me in doing this?
Thanks


text:
Q: Parse special character encoded (escaped) XML with lxml/ElementTree Is there a way to instruct lxml/ElementTree to parse an XML file that is still special character encoded?
It looks like this:
<?xml version="1.0" encoding="utf-8"?>
<RootElement>
    <DataElement>data</DataElement>
</RootElement>

It came as the text node of another XML file. It's huge, so I don't want to load it entirely into memory.


text:
Q: WEB API in .NET Core 2.0.6 is slower than .NET 4.5.2? I've made a simple test to compare performance of ASP.NET WEB API with .Net Framewrok 4.5.2 and with dotNet Core 2.0.6
Just runned locally, on my PC.
I've created a new project with framework 4.5.2, with the default "valuesController". There's nothing else in my project (no DBs, no other controllers)
(Screen capture of VS with .net 4.5.2)
Then I run a simple load test with WebSurge to GET the IEnumerable (30 seconds, 8 threads) (Screen capture of WebSurge results).
As you can see, I get 11.326 total requests and 377 reqs/second
So, I did the same but with dotNet Core....just the default "ValuesController" (Screen capture of VS with dotnet Core 2.0.6)
Then I run the same load test and I get this: (Screen capture of WebSurge results).
I get only 455 total requests and 15 reqs/second
Can someone explain me why this is happening? Am I missing something here?
Edit
I run in Release mode. For the .Net 4.5.2 project I get 72.763 requests and 2.425 reqs/second . For the dotNet Core project I get 47.195 requests and 1.537 reqs/second
Edit 2:
As @fknx said, the debugger in dotNet Core is significantly slower than the debugger of the full .NET Framework.
I published both solutions, definitely dotnet Core is much faster!


text:
Q: Different welcome screen language to system users? Found various articles which can be used to update the system users and login screen via the GUI, such as How to change default login/lock screen of Windows 8? but what i need to do is slightly different.
I need the system users to be in Dutch for application and number formatting reasons but i would like for the login screen to appear in English as the vast majority of admins are English.
I appreciate that beyond the login screen the admins will be English and that it is obvious its asking for a user name and password, but the client specifically wants English Login screens, English Language admin user accounts and Dutch language system accounts.
Steps for both WinServer2008r2 and WinServer2012 appreciated, if possible.
Thanks in Advance!
Dave


text:
Q: Updating column in MySql I am trying to update column for three rows in sql. However when I run following query, only one row is affected. Can someone help me to see where I am making a mistake? Thank you!
update some_table
set date_updated = case some_id
when '7791'   then '2021-10-08 06:59:05'
when '1555'   then '2021-08-26 05:30:54'
when '363201' then '2021-08-31 05:01:45'
end
where some_id = ('7791, 1555, 363201')
and date_updated between '2021-11-01' and '2021-11-03';

A: You missed IN Clause
       where some_id in ('7791' ,'1555' , '363201')
      and date_updated between '2021-11-01' and '2021-11-03';

A: update some_table
set date_updated =
    case when some_id = '7791'  then '2021-10-08 06:59:05'
         when some_id = '1555'   then '2021-08-26 05:30:54'
         when some_id = '363201' then '2021-08-31 05:01:45'
    end
where some_id IN ('7791', '1555', '363201')
and date_updated between '2021-11-01' and '2021-11-03';

A: you should put IN clause to work properly


text:
Q: Can I use regular expression in cucumber step where I validate string? Ex - Then the message should contain:
| {any string} Hello |
Is there some kind of syntax I have to follow so that it use it as regular expression instead of text ?
The step definition is in Ruby for"Then the message should contain"
Referred this - https://cucumber.io/docs/cucumber/cucumber-expressions/ , but didnt figured it out


text:
Q: Vectorizing a function that uses strsplit I am trying to make a function that converts time (in character form) to decimal format such that 1 corresponds to 1 am and 23 corresponds to 11 pm and 24 means the end of the day.
Here are the two function that does this. Here one function vectorizes while other do
time2dec <- function(time0)
{
time.dec <-as.numeric(substr(time0,1,2))+as.numeric(substr(time0,4,5))/60+(as.numeric(substr(time0,7,8)))/3600
return(time.dec)
}

time2dec1 <- function(time0)
{
time.dec <-as.numeric(strsplit(time0,':')[[1]][1])+as.numeric(strsplit(time0,':')[[1]][2])/60+as.numeric(strsplit(time0,':')[[1]][3])/3600
return(time.dec)
}

This is what I get...
times <- c('12:23:12','10:23:45','9:08:10')

#>time2dec(times)
[1] 12.38667 10.39583       NA
Warning messages:
1: In time2dec(times) : NAs introduced by coercion
2: In time2dec(times) : NAs introduced by coercion

#>time2dec1(times)
[1] 12.38667

I know time2dec which is vectorized, gives NA for the last element because it extracts 9: instead of 9 as hour. That is why I created time2dec1 but I do not know why it is not getting vectorized.
I will also be interested in getting a better function for doing what I am trying to do.
I saw this which explain a part of my question but does not provide a clue to do what I am trying.

A: Don't try to reinvent the wheel:
times1 <- difftime(as.POSIXct(times, "%H:%M:%S", tz="GMT"),
                   as.POSIXct("0:0:0", "%H:%M:%S", tz="GMT"),
                   units="hours")
#Time differences in hours
#[1] 12.386667 10.395833  9.136111

as.numeric(times1)
#[1] 12.386667 10.395833  9.136111

A:  as.numeric( strptime(times, "%H:%M:%S")-strptime(Sys.Date(), "%Y-%m-%d" ))
[1] 12.386667 10.395833  9.136111

Basically the same as Roland's but bypassing some steps, and I try to avoid using difftime if I can. Had too many bugs arise because I don't really understand the function or the class ... or something. And when I timed it versus Roland's his was faster. Oh, well.
Emulating @G.Grothendieck's efforts (and essentially working similarly to his elegant strapply solution:
num <- apply( matrix(scan(text=gsub(":", " ", ch), what=numeric(0)),nrow=3), 2,
                 function(x) x[1]+x[2]/60 +x[3]/3600 )
#Read 9 items
num
#[1] 12.386667 10.395833  9.136111

And this actually answers the original question:
 num <- sapply( strsplit(ch, ":"), function(x){ x2 <- as.numeric(x);
                                                x2[1]+x2[2]/60 +x2[3]/3600})
 num
#[1] 12.386667 10.395833  9.136111

A: In the following we shall use this test vector:
ch <- c('12:23:12','10:23:45','9:08:10')

1) To fix up the solution in the question we prepend a 0 and then replace any string of 3 digits with the last two:
num.substr <- function(...) as.numeric(substr(...))
time2dec <- function(time0) {
    t0 <- sub("\\d(\\d\\d)", "\\1", paste0(0, time0))
    num.substr(t0, 1, 2) + num.substr(t0, 4, 5) / 60 + num.substr(t0, 7, 8) / 3600
}

time2dec(ch)
## [1] 12.386667 10.395833  9.136111

2) Parsing the string is slightly easier with strapply in the gsubfn package:
strapply(ch, "^(.?.):(..):(..)",
   ~ as.numeric(h) + as.numeric(m)/60 + as.numeric(s)/36000,
   simplify = c)
## [1] 12.383667 10.384583  9.133611

3) We can reduce the string manipulation to just removing the colons and then convert the resulting character string to numeric so we can manipulate it numerically:
num <- as.numeric(gsub(":", "", ch))
num %/% 10000 + num %% 10000 %/% 100 / 60 + num %% 100 / 3600
## [1] 12.386667 10.395833  9.136111

4) The chron package has a "times" class that internally represents times as fractions of a day.  Converting that to hours gives an easy solution:
library(chron)

24 * as.numeric(times(ch))
## [1] 12.386667 10.395833  9.136111

ADDED Added more solutions.

A: The following does what you want
sapply(strsplit(times, ":"), function(d) {
  sum(as.numeric(d)*c(1,1/60,1/3600))
})

Step by step:
strsplit(times, ":")

returns a list with character vectors. Each character vector contains the three part of the time (hour, minutes, seconds). We now want to convert each of the elements in the list to a numeric values. For this we need to apply a function to each element and put the results of the back into a vector which is what sapply does.
sapply(strsplit(times, ":", function(d) {
})

As for the function. We first need to convert the character values to numeris values using as.numeric. The we multiply the first element with 1, the second with 1/60 and the third with 1/3600 and add the results (for which we use sum). Resulting in
sapply(strsplit(times, ":"), function(d) {
  sum(as.numeric(d)*c(1,1/60,1/3600))
})


text:
Q: Pass dictionary values a list in a function I have  list of list. I want to pass the inner list in a function as list
('HNSPS150', ['19.41', 19.72, 18.64, 18.53, 20.36, 21.88, 21.84, 22.85, 23.06, 23.42, 23.69, 23.74, 24.27, 24.79, 25.68, 25.95, 26.16, 26.68, 26.97, 26.84, 26.95, 26.88, 27.02, 27.06, 27.13, 27.48, 27.86, 27.77, 28.51, 28.33, 28.58, 28.88, 29.28, 21.38, 21.36, 22.22, 22.67, 22.95, 23.41, 23.71, 23.73, 24.18, 24.23, 24.21, 24.76, 20.58, 18.96, 19.32, 19.95, 20.68, 21.03, 21.19, 21.68, 22.0, 23.39, 24.05, 23.44, 23.47, 23.71, 24.28, 24.64, 25.05, 25.84, 25.61, 25.55, 25.86, 26.74, 26.78, 28.1, 28.41, 28.19, 27.79, 28.54, 28.94, 28.98, 29.41, 29.67, 29.14, 29.7, 30.18, 30.33, 30.77, 31.1, 30.81, 31.18, 31.33, 31.54, 32.19, 32.61])
('HNSPS406', ['64.04', 64.7, 65.65, 66.01, 67.97, 68.54, 68.84, 68.05, 68.48, 70.99, 72.66, 70.51, 70.78, 71.79, 71.1, 71.91, 73.6, 73.65, 74.17, 74.3, 74.97, 74.78, 75.27, 76.18, 77.13, 77.11, 77.47, 78.19, 77.87, 78.32, 79.25, 81.45, 15.9, 15.69, 16.69, 17.61, 17.87, 18.51, 19.2, 17.89, 17.36, 20.11, 19.81, 20.64, 21.16, 21.19, 24.86, 26.68, 27.82, 28.48, 30.08, 29.71, 30.31, 31.6, 32.4, 33.33, 34.31, 35.44, 35.85, 36.58, 38.59, 38.79, 39.97, 40.42, 40.42, 40.95, 41.73, 44.13, 45.07, 46.13, 46.7, 50.55, 51.84, 51.83, 53.29, 53.78, 55.2, 28.88, 16.97, 17.8, 18.54, 22.0, 24.09, 23.99])
('CLL28DSQL4', ['64.60', 68.69, 70.03, 69.39, 70.04, 64.88, 66.14, 65.77, 66.02, 59.45, 67.53, 65.92, 68.74, 69.95, 66.3, 71.81, 70.16, 67.33, 68.43, 73.38, 66.71, 71.5, 69.99, 70.9, 70.41, 69.18, 71])

How can i access the list as a function parameter.

A: try this
import itertools

list(itertools.chain.from_iterable(LISTS))


text:
Q: Find a centroid of a dataset If I have some random data set let's say
X       Y
1.2     16
5.7     0.256
128.54  6.879
0       2.87
6.78    0
2.98    3.7
...     ...
 x'      y'

How can I find the centroid coordinates of this data set?
p.s. Here what I tried but got wrong results
float Dim1[K];
float Dim2[K];
float centroidD1[K];
float centroidD2[K];

int K = 4;
int counter[K];
for(int i = 0; i < K ; i++)
{
    Dim1[i] = 0;
    Dim2[i] = 0;
    counter[i] = 0;
    for(int j = 0; j < hash["Cluster"].size(); j++)
    {
        if(hash["Cluster"].value(j) == i+1)
        {
            Dim1[i] += hash["Dim_1"].value(j);
            Dim2[i] += hash["Dim_2"].value(j);
            counter[i]++;
        }
    }
}

for(int l = 0; l < K; l++)
{
    centroidD1[l] = Dim1[l] / counter[l];
    centroidD2[l] = Dim2[l] / counter[l];
}

I guess I choose wrong algorithm for doing it, as I get wrong results.

A: Calculating a sum and dividing by N is not a good idea if you have a large data set. As your floating point accumulator grows adding a new point eventually stop working due to the magnitude difference. An incremental formula might work better, see: https://math.stackexchange.com/questions/106700/incremental-averageing
If the issue is too large a data set you can verify the basic functioning of your code by using a smaller data set with a hand verified result. For example, just 1 data point, or 10 data points.


text:
Q: Lines of Code VS Instructions while measuring code quality I have a projet composed of numerous modules. I am running both JaCoCo for unit tests coverage and Sonar for code quality.
For a technical reason, I can't use JaCoCo reports for one of my modules (GWT erases the target folder and I couldn't go past this issue yet).
Let's say I have 8 modules, from 1 to 8.
One of them is for domain objects only, so I don't want to cover it with my tests. Same goes for another one, dedicated for auto-generated classes.
JaCoCo runs on 5 modules, and Sonar on 6 modules.
The total instructions shown by JaCoCo is 145k.
Sonar shows a total of 75k LOC.

Aren't they quite the same ? Did I miss something ? Is JaCoCo taking in account the whole project whatever reports I feed him ? What can possibly explain this gap in measurement ?

A:
Aren't they quite the same ?

Not at all.
From http://www.jacoco.org/jacoco/trunk/doc/counters.html :

The smallest unit JaCoCo counts are single Java byte code instructions.

comparison of "instructions" with "lines of code" is like comparison of apples and oranges - they don't represent the same thing. Single line of code usually contains many bytecode instructions.
For example
System.out.println("Hello, World!");

is a single line, but 3 bytecode instructions as can be seen using javap (Java Class File Disassembler):
     0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
     3: ldc           #3                  // String Hello, World!
     5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V

BTW JaCoCo also counts lines. But while comparing this one with LoC in SonarQube, please take into account that algorithms of calculation are different - JaCoCo computes this number by analyzing information recorded by compiler in bytecode, while SonarQube computes this number by analyzing source code.


text:
Q: NotifyPropertyChanged not firing I am trying to capture the SelectedItem for a ListBox when then data template click event is triggered for the Button.  I put a breakpoint in the notifypropertychanged event handler, but it never triggers.  What am I doing wrong here?
xaml:
   <ListBox x:Name="lstbox_playerContainer"
       ItemsSource="{Binding ChildObjectOC}"
       SelectedItem="{Binding SelectedChildObject, Mode=TwoWay}">
       <ListBox.ItemTemplate>
           <DataTemplate>
               <Button Name="btn_childButton" Click="btn_childButton_Click"/>
           </DataTemplate>
        </ListBox.ItemTemplate>
   </ListBox>

c#:
public partial class PlayerCrowdPromptPage: INotifyPropertyChanged {

     public PlayerCrowdPromptPage() {
          InitializeComponent();
          DataContext = this;
     }

    private ObservableCollection<PlayerCrowdObjectBO> childObjectOC = new ObservableCollection<PlayerCrowdObjectBO>();
    public ObservableCollection<PlayerCrowdObjectBO> ChildObjectOC {
        get {
            return childObjectOC;
        }
        set {
            childObjectOC = value;
        }
    }

     private PlayerCrowdObjectBO selectedChildObject;
     public PlayerCrowdObjectBO SelectedChildObject {
         get { return selectedChildObject; }
         set {
               selectedChildObject = value;
               OnPropertyChanged("SelectedChildObject");
         }
    }

    public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged(string propertyName) {
            if (PropertyChanged != null){
               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

A: Clicking on the Button won't automatically select the corresponding item. You may select it programmatically in the event handler though:
private void btn_childButton_Click(object sender, RoutedEventArgs e)
{
    Button btn = (Button)sender;
    ListBoxItem lbi = lstbox_playerContainer.ItemContainerGenerator.ContainerFromItem(btn.DataContext) as ListBoxItem;
    lbi.IsSelected = true;
}

This should set the SelectedChildObject property and raise the PropertyChanged event.


text:
Q: Getting started with libpurple I'm writing a Cocoa Touch program that will (hopefully) use Libpurple as it's background. The only problem is that I have no clue where to get started. I've been looking through some source code of applications that do use it, but so far haven't gotten anywhere.
Does anyone know anything that will help me familiarize myself with libpurple?

A: First of all, you may encounter some trouble, since libpurple is licensed under GPLv2. It may be incompatible with what you are trying to do. (I am not totally sure you can have a GPLv2 app on the App Store.)
Second, you can read purple-client-example.c in the libpurple source, for a super-short example.
Also, Adium might be more useful to study than Pidgin since it is a Mac OS X app, closer to what you might do on the iPhone.

A: The best way to understand libpurple is to work with Pidgin, the OSS client that uses it.  Study the Pidgin implementation, then start to design your own client.

A: If you plan to sell this, you cannot use libpurple because it is under the GNU license.  Please check out my alternative AIM API for Objective-C, with a bit of tweaking, it will probably work moderately well on iPhone: LibOrange


text:
Q: JAVA use apache poi creates xlsx, all the rows after 9th will be inserted back to 2nd row I'm following the Apache POI – Spreadsheets tutorial from this site:
https://www.tutorialspoint.com/apache_poi/apache_poi_spreadsheets.htm
Everything works fine, but when I try to add more than 10 rows, all rows after 9th will be inserted back from the 2nd row. I am new in JAVA, is there anything wrong with the loop to iterate the data or something else? Please help!
I used the entire code from the tutorial but added some more lines to create more rows:
package testing;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Testing {

    /**
     * @param args the command line arguments
     * @throws java.lang.Exception
     */

   public static void main(String[] args) throws Exception
   {
      //Create blank workbook
      XSSFWorkbook workbook = new XSSFWorkbook();
      //Create a blank sheet
      XSSFSheet spreadsheet = workbook.createSheet(
      " Employee Info ");
      //Create row object
      XSSFRow row;
      //This data needs to be written (Object[])
      Map < String, Object[] > empinfo =
      new TreeMap < String, Object[] >();
      empinfo.put( "1", new Object[] {
      "EMP ID", "EMP NAME", "DESIGNATION" });
      empinfo.put( "2", new Object[] {
      "tp01", "Gopal", "Technical Manager" });
      empinfo.put( "3", new Object[] {
      "tp02", "Manisha", "Proof Reader" });
      empinfo.put( "4", new Object[] {
      "tp03", "Masthan", "Technical Writer" });
      empinfo.put( "5", new Object[] {
      "tp04", "Satish", "Technical Writer" });
      empinfo.put( "6", new Object[] {
      "tp05", "Krishna", "Technical Writer" });
      empinfo.put( "7", new Object[] {
      "tp06", "Krishna", "Technical Writer" });
      empinfo.put( "8", new Object[] {
      "tp07", "Krishna", "Technical Writer" });
      empinfo.put( "9", new Object[] {
      "tp08", "Krishna", "Technical Writer" });
      empinfo.put( "10", new Object[] {
      "tp09", "Krishna", "Technical Writer" });
      empinfo.put( "11", new Object[] {
      "tp10", "Krishna", "Technical Writer" });

      //Iterate over data and write to sheet
      Set < String > keyid = empinfo.keySet();
      int rowid = 0;
      for (String key : keyid)
      {
         row = spreadsheet.createRow(rowid++);
         Object [] objectArr = empinfo.get(key);
         int cellid = 0;
         for (Object obj : objectArr)
         {
            Cell cell = row.createCell(cellid++);
            cell.setCellValue((String)obj);
         }
      }
      //Write the workbook in file system
      FileOutputStream out = new FileOutputStream(
      new File("Writesheet.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println(
      "Writesheet.xlsx written successfully" );
   }
}

If I run the code, the generated *.xlsx file will be:
example.xlsx
Anyway to make it works normally?

A: Treemap sorts the keys that's why the final result is different than expected. Try using linkedhashmap which saves the insertion order.


text:
Q: Identityserver4 Access levels Practices We're looking for 3 types of different access levels but don't know how to implement them using current identityserver4 features.
Have these scenarios:

*

*We have an upper management system which some clients have access to specific pages or not, like admin or client(seems like Roles)

*We have column type access level, for example, some users in the manager role can see a specific column/field or not, or in same roles shouldn't see some column/row data in reports.

*We have a record level, access level, for example, some manager shouldn't see other branch client list. (like policies)

The whole process should be dynamic without any hardcode. and for doing these structures we should do some code on the back-end(middleware, etc) and some on frontend side(with a razor or etc).
any Idea how to implement these using identityserver4 authorization types?

A: The main feature of IdentityServer is to handle the authentication of the user and global authorization: which client has access to what resource.
Everything else could be considered out-of-scope of IdentityServer. Please read this article for some background information.
As an answer they've created the PolicyServer.
In the OSS version authorization has become a seperate (local) mechanism, while the paid version outsources authorization to a seperate server.
Extended with resource-based authorization you can implement authorization that covers all access levels.


text:
Q: SQL Query multiple where clause prioritize I have following SQL query
SELECT * FROM train_stop where code='ABC' OR code='XYZ' OR code='DEF' group by number order by departs

Now since i am using Group By so as to take only one row with specific number. But i want to prioritize the result. It means if my table has code='ABC' and code='XYZ' , then the result must select ABC row and not 'XYZ' because ABC has come first in where clause.  Similarly if table has XYZ and DEF for same number, XYZ must come up in result and not DEF. Till now my experiments led me that its hows on random basis. I would be helpful if you could guide me to achieve this and proper indexing strategy for this case. Thanks.
The create statement is as follows-
Create Statement is `CREATE TABLE `train_stop` (
  `number` varchar(1000) NOT NULL,
  `stop_number` int(11) NOT NULL,
  `code` varchar(1000) NOT NULL,
  `station name` varchar(1000) NOT NULL,
  `arrives` time NOT NULL,
  `departs` time NOT NULL,
  `halt` varchar(1000) NOT NULL,
  `pf` varchar(1000) NOT NULL,
  `day` int(11) NOT NULL,
  `km` varchar(1000) NOT NULL,
  `speed` varchar(1000) NOT NULL,
  `elev` varchar(1000) NOT NULL,
  `zone` varchar(1000) NOT NULL,
  `address` varchar(1000) NOT NULL,
  `active` int(11) DEFAULT '1',
  KEY `index_1` (`number`(767),`code`(767)),
  KEY `PIndex` (`number`(767),`stop_number`),
  KEY `three_columns_idx` (`code`(767),`active`,`departs`),
  KEY `two_columns_idx` (`code`(767),`active`),
  KEY `two_columns_group_idx` (`number`(767),`departs`),
  KEY `one_columns_group_idx` (`departs`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1`

A: Group by is the wrong way to do this. This will do it.  You would need to change the order by portion to match your where clause ordering whenever you change the codes to check against.
select * from (
  select if(@prev = number, @rank := @rank + 1, @rank := 1 and @prev := number) rank,
         train_stop.*
    from train_stop, (select @prev := 0, @rank := 1) q
  where code = 'abc'
    or code = 'xyz'
    or code = 'def'
  order by number asc, code='abc' desc, code='xyz' desc, code='abc' desc
) q where rank = 1;

Demo here: http://sqlfiddle.com/#!9/ccc4d/7
This query assigns a rank per ordered group, and then selects just the top ranked value out of each group. Would probably break if you have a station number 0

A: Try this.
SELECT *
FROM train_stop
where code='ABC'
 OR ( code != 'ABC'
  and code = 'XYZ' )
 OR ( code != 'ABC'
  and code != 'XYZ'
  and code='DEF' )
group by number
order by departs

A: SELECT * FROM (SELECT * FROM train_stop where code='ABC' OR code='XYZ' OR
code='DEF' order by departs ASC) as t group by t.number


text:
Q: Whats the equivalent of Makefile's include for SConstruct? I'm trying find the best way to replicate Makefile's include in SConstruct. I have come up with a solution, but its messy, relies of the user passing in specific command-line parameters and surely can't be the best option.
My file structure is as so:
Working_Dir/
   |-> includes/
   |    |-> filename.mk
   |    |-> filename.py
   |-> Makefile
   |-> main.c
   |-> SConstruct

These are my file's contents
Makefile
all: main.o
    echo "Version is: $(VERSION)"
    gcc $^ -o main

include includes/filename.mk

filename.mk
VERSION := "1.6.2"

%.o: %.c
    gcc -c -o $@ $<

SConstruct
import filename

env=Environment()
filename.Init(env)

#Create new builder
prog = Builder(action=["gcc $SOURCE -o $TARGET"])

#Add the builder
builder = { "Prog": prog}
env.Append(BUILDERS=builder)

print "Version is: " + env['VERSION']
env.Prog(target = "main", source = "main.o")

filename.py
from SCons.Script import *  # Needed so we can use scons stuff like builders

def Init(env):
    #Make builder
    obj = Builder(action="gcc -c -o $TARGET $SOURCE")

    #Add stuff
    env.Append(BUILDERS= {'Obj': obj})
    env.Append(VERSION= "1.6.2")

(Ignore the fact that SCons has its own Object builder, this is just a simplified example that I made to learn from for a bigger project)
To compile with the makefile I run make and for SCons its scons --site-dir="includes" since my included file isn't in the standard path. As far as I'm aware the site_dir option is the only way to include your own code/builders in scons as seen here. Also note that SConscript files aren't what I want, since when you call them they execute their instructions in their own directory rather than just loading variables and builders into the caller.
I want it to the user can just run scons and it works. I have read I can set these settings globally to my bash profile as seen here in section 10.1.1, but I don't want to do this because I don't want every SCons project on my system defaulting to use this directory. I also had a look at the SetOption() function, but its limited and doesn't actually allow you to set this particular parameter at all.
The only solution I can think of is to start off using GetOption('site_dir') and if its not the directory I'm expecting, I invoke a new SCons call with all of the same parameters, but now with the correct site_dir option.
However this feels very ghetto and I feel I'm missing a much better solution. Is there a better solution?
EDIT:
The reason I'm using this "includes" directory instead of the "site_scons" directory is because in my larger project the "includes" directory isn't in the same directory as the project, its in a completely different directory (The path to that directory is known). filename.py will be used for multiple of my SCons projects that depend on it, but not every SCons project on my machine should use it (ie. It shouldn't be global).

A: I figured it out on my own. I just loaded the file as a normal python module as seen in the top answer here. I specifically used the Python 2 answer since it seems SCons is configured on my system to use python 2.
Thanks to this I have the ability to load any python file including scons related code from anywhere on my computer, this is exactly what I wanted.
For those curious, here's the code I needed to add
file_path = "/path/to/my/file/filename.py"

import imp
extra_stuff = imp.load_source('filename', file_path)

env=Environment()
extra_stuff.Init(env)


text:
Q: I get a keyerror when I try to get data from a json in python I have this json, from an api, i need to get the data, but I don't understand why some of them I get and others I get "keyerror".
{
    "images": [
        {
            "OS-EXT-IMG-SIZE:size": 13167616,
            "created": "2021-07-13T09:35:56Z",
            "id": "15f490a5-9b64-4315-a592-3933e91356a5",
            "links": [
                {
                    "href": "http://192.168.1.82:8774/v2.1/7d8fed2119e04ee79e15b5a2fac2f5da/images/15f490a5-9b64-4315-a592-3933e91356a5",
                    "rel": "self"
                },
                {
                    "href": "http://192.168.1.82:8774/7d8fed2119e04ee79e15b5a2fac2f5da/images/15f490a5-9b64-4315-a592-3933e91356a5",
                    "rel": "bookmark"
                },
                {
                    "href": "http://192.168.1.82:9292/images/15f490a5-9b64-4315-a592-3933e91356a5",
                    "rel": "alternate",
                    "type": "application/vnd.openstack.image"
                }
            ],
            "metadata": {},
            "minDisk": 0,
            "minRam": 0,
            "name": "cirrios",
            "progress": 100,
            "status": "ACTIVE",
            "updated": "2021-07-13T09:35:57Z"
        },
        {
            "OS-EXT-IMG-SIZE:size": 1020264448,
            "created": "2021-07-11T15:14:03Z",
            "id": "ba417b6f-edde-4862-8425-6d3b1d545dcc",
            "links": [
                {
                    "href": "http://192.168.1.82:8774/v2.1/7d8fed2119e04ee79e15b5a2fac2f5da/images/ba417b6f-edde-4862-8425-6d3b1d545dcc",
                    "rel": "self"
                },
                {
                    "href": "http://192.168.1.82:8774/7d8fed2119e04ee79e15b5a2fac2f5da/images/ba417b6f-edde-4862-8425-6d3b1d545dcc",
                    "rel": "bookmark"
                },
                {
                    "href": "http://192.168.1.82:9292/images/ba417b6f-edde-4862-8425-6d3b1d545dcc",
                    "rel": "alternate",
                    "type": "application/vnd.openstack.image"
                }
            ],
            "metadata": {},
            "minDisk": 0,
            "minRam": 0,
            "name": "centos",
            "progress": 100,
            "status": "ACTIVE",
            "updated": "2021-07-11T15:14:22Z"
        }
    ]
}

I search for the data I am interested in with a for, but with "progress", "minDisk", "minRam", "status" I get keyerror, but not with "name" or "id".
try:
    result = requests.get(req["images"], headers=headers)
    result_data = json.loads(result.content)
except Exception as e :
    print('0')
    sys.exit("\nError requesting %s, please check conectivity" %(req["images"],))

for dato in result_data["images"] :
    print(f'Name={dato["name"]}')
    print(f'Id={dato["id"]}')
    print(f'Progress={dato["progress"]}')
    print(f'minDisk={dato["minDisk"]}')
    print(f'minRam={dato["minRam"]}')

I've been stuck for a long time and I can't figure it out, what could I be doing wrong?
Traceback (most recent call last):
  File "openstack3.py", line 263, in <module>
    print(f'Progress={dato["progress"]}')
KeyError: 'progress'

this its full error traceback


text: Q: The probability of getting a prime number from a Poisson random draw I know the probability of getting an odd number from a Poisson random draw of rate $\lambda$ is $\frac{1+e^{-2\lambda}}{2}$, what I'm interested in is the probability of getting a prime number from a Poisson random draw. Is there a way to find the closed-form solution to this problem or there's no hope? thanks


text:
Q: Extracting Files from Sharepoint 2013 WSS_Content Database Sharepoint 2013 stores documents in the WSS_Content database in a table called DocStreams.
Up until Sharepoint 2010, files where stored in a single row in a VarBinary column. Since Sharepoint 2013, files are stored in multiple rows using Shredded Blob storage.
Does anyone know how I can piece together the files from the shredded storage in c#?
I have found many exampled online to extract files from SharePoint 2010 and earlier but they only support a files content being stored in 1 row.


text:
Q: How to decipher this string from sql table? I have this string in a table.
[0-9]+(\*+)? ?([0-9]+)?(\*+)? ?([0-9]+)?

I understand that 0-9 means any number from 0 to 9, but the rest... what is the difference between [] and (), what does ? or + or / or *  mean? What is the space between?
? ?

How do I decipher it? What is this called? Are all these wild cards?

A: It is called regrex (see regular expression)

Regular expressions are patterns used to match character combinations
  in strings. These
  patterns are used with the exec and test methods of RegExp, and with
  the match, replace, search, and split methods of String.
  here

A: [RANGE] is like [a-z] or [SINGLE CHARACTERS] like [abc]
(MATCH_SET) in your result
Example Text "My lazy dog sleeps"
with regex /(lazy) (dog)/ matches
Resultset 0 = lazy dog
Resultset 1 = lazy
Resultset 2 = dog

With
    ?/+///*
I think you posted something wrong.


text:
Q: Rails devise sign_out is giving No route matches [GET] Seems like this is a very common question, and I have followed many of the fixes from google, yet my sign-out problem persists.
Here's what I have: Rails 4.1.1, Devise 3.2.4. Oh, btw, instead of User, I am calling my model AppUser
On view
As AppUser:

<% if app_user_signed_in? %>
    Signed in as: <%= current_app_user.email %>

    <%= link_to "Sign Out", destroy_app_user_session_path, method: :delete %>
<% else %>
    <%= link_to "Sign Up", new_app_user_registration_path %>

    <%= link_to "Sign In", new_app_user_session_path %>
<% end %>

/config/routes.rb
Rails.application.routes.draw do
  devise_for :app_users
  root 'home#index'
end

these are the partial routes from rake routes
                  Prefix Verb   URI Pattern                        Controller#Action
    new_app_user_session GET    /app_users/sign_in(.:format)       devise/sessions#new
        app_user_session POST   /app_users/sign_in(.:format)       devise/sessions#create
destroy_app_user_session DELETE /app_users/sign_out(.:format)      devise/sessions#destroy

on application.js
//= require jquery
//= require jquery_ujs
//= require_tree .

on application.html.erb, i included this as well
 <%= javascript_include_tag 'application' %>

and yet, i am still getting the get route error:
No route matches [GET] "/app_users/sign_out"

Why????
Ok.
So, changing :delete to :get on /config/initializer/devise.rb fixes the problem, with method: :delete removed of course.
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :get

But I still don't get it? Why? If I were to keep :delete on devise.rb, what was I missing?
========================
[SOLVED]
I probably should edit the status update here:
I have finally figured out why. Even though i have set up my javascript, etc, correctly, but it didn't load because I stupidly inherit my controller class from "ActionController::Base" instead of "ApplicationController".
As I was working through my project, I noticed link_tos on other pages weren't able to send :delete method either.
Once I fixed the inheritance, they all work.
Gah.

A: routes.rb
devise_scope :app_user do
  get "/app_users/sign_out" => "devise/sessions#destroy"
end

A: JQuery?

If I were to keep :delete on devise.rb, what was I missing?

From the looks of it, the issue is likely to do with your system not rendering / processing :delete HTTP verbs correctly. The issue will be a Javascript one, as this http verb is created by the rails UJS on a standard get link
I would suggest you either have some problems with other javascript files on your system (check the browser console), or you are not loading the jquery_ujs file properly
The best way to test this will be to firstly look at the browser console, then see if you can bind an action to event inside your JS:
#app/assets/javascripts/application.js
$(document).on("click", "#test_link", function(){
    alert("test");
});

A: I have finally figured out why.
Even though i have set up my javascript, etc, correctly, but it didn't load because I stupidly inherit my controller class from "ActionController::Base" instead of "ApplicationController".
As I was working through my project, I noticed link_tos on other pages weren't able to send :delete method either.
Once I fixed the inheritance, they all work.
Gah.


text:
Q: Where can I define the default i18n language in JHipster? I am new to JHipster and I would like to where can I define the default i18n language in JHipster? Is it in a Java Configuration class, in Spring-Boot yaml file, or in Javascript file?

A: You can set the language you like in the weapp/scripts/app.js file by changing the preferred language line, for instance $translateProvider.preferredLanguage('fr');changes the language to french.

A: And for JHipster 5.7.2 it's in src/main/webapp/app/app.module.ts under defaultI18nLang.

A: In the newer version of Jhipster (v 3.0.0 - the one I've been using), you will need to change two places:

*

*src/main/webapp/app/blocks/config/translation.config.js: change the line $translateProvider.preferredLanguage('en'); with your preferred language key (e.g. 'en' -> 'fr');

*src/main/webapp/app/blocks/config/translation-storage.provider.js: change the line $cookies.putObject(name, 'en'); with your preferred language key as well.

A: For jhipster: 4.12.0
Angular: 5
It's in this file: src/main/webapp/app/shared/shared-libs.module.ts under the property "defaultI18nLang"

A: For jhipster 6.5.1 you should edit defaultI18nLang in /src/main/webapp/app/core/core.module.ts, for example defaultI18nLang: 'ar-ly'

A: And for JHipster 7.2.0 it's in src/main/webapp/app/app.module.ts under:
translateService.setDefaultLang('en');
// if user have changed language and navigates away from the application and back to the application then use previously choosed language;
const langKey = sessionStorageService.retrieve('locale') ?? 'en';


text:
Q: How to type only random letters in input field with cypress Pls say, How I can past only letters in my tests.
Like this
    const uuid = () => Cypress._.random('^[A-Za-z]+$')
    const id = uuid()
    const firstname = `${id}`

    cy.get('.firstname').type(firstname)

A: ⚠ If you want to generate UUIDs be aware that not all characters in a UUID are random: Read here on Wikipedia.

UUID
I personally use this small package to generate UUIDs

Chance.js
If you need more generated data for your tests I'd recommend chance.js. You can read more about generating UUIDs here chance.js/uuid

On your own
Generating UUIDs on your own was already answered in this mega thread here: How to create GUID / UUID?
If you don't care if some of the strings are duplicates of each other (e.g. for first names), you could just

const generate = () => {
  document.body.innerHTML = `${document.body.innerHTML} ${Math.random().toString(36).substring(2)}`;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button type="button" id="btn" onclick="generate()">
    Generate string
  </button>
</body>

</html>


text:
Q: Stream normalization for online clustering in evolving environments TL;DR: how to normalize stream data, given that the whole data set is not available and you are dealing with clustering for evolving environments
Hi! I'm currently studying dynamic clustering for non-stationary data streams. I need to normalize the data  because all features should have the same impact in the final clustering, but I don't know how to do it .....
I need to apply a standard normalization. My initial approach was to:

*

*Fill a buffer with initial data points

*Use those data points to get mean and standard deviation

*Use those measures to normalize the current data points

*Send those points normalized to the algorithm one by one

*Use the previous measures to keep normalizing incoming data points for a while

*Every some time calculate again mean and standard deviation

*Represent the current micro clusters centroids with the new measures (having the older ones it shouldn't be a problem to go back and normalize again)

*Use the new measures to keep normalizing incoming data points for a while

*And so on ....

The thing is that normalizing the data should not get involved with what the clustering algorithm does ... I mean, you are not able to tell the clustering algorithm 'ok, the micro clusters you have till now need to be normalized with this new mean and stdev' ... I mean, I developed an algorithm and I could do this, but I am also using existing algorithms (clustream and denstream) and it does not feel right to me to modify them to be able to do this ....
Any ideas?
TIA

A: As more data streams in, the estimated standardization parameters (e.g, mean and std) are updated and converge further to the true values [1, 2, 3]. In evolving environments, it is even more pronounced as the data distributions are now time-varying too [4]. Therefore, the more recent streamed samples that have been standardized using the more recent estimated standardization parameters are more accurate and representative.
A solution is to merge the present with a partial reflection of the past by embedding a new decay parameter in the update rule of your clustering algorithm. It boosts the contribution of the more recent samples that have been standardized using the more recent distribution estimates. You can see an implementation of this idea in Apache Sparks MLib [5, 6, 7]:

where the α is the new decay parameter; lower α makes the algorithm favor the more recent samples more.

A: Data normalization affects clustering for algorithms that depend on the L2 distance. Therefore you can't really have a global solution to your question.
If your clustering algorithm supports it, one option would be to use clustering with a warm-start in the following way:

*

*at each step, find the "evolved" clusters from scratch, using the samples re-normalized according to the new mean and std dev

*do not initialize clusters randomly, but instead, use the clusters found in the previous step as represented in the new space.


text:
Q: A variable that has been assigned in a SELECT statement cannot be included in a expression or assignment when used in conjunction with a from clause This doesn't seem to work in Synapse,
--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(COLUMN_NAME)
FROM (  SELECT DISTINCT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tbl_TMY_2_041622_FullFields' And DATA_TYPE ='float'
) AS Rawcode
Does anyone has a work around ?, Thanks


text:
Q: Email Server Configuration I don't use Linux regularly, but do occasionally and I'm struggling with the email configuration that I'd like to get. I've run through a lot of information and tutorials on configuring Postfix and Courier but haven't found if it's possible to do a few things.
I'd like to store all received emails in a format which would be easy for me to 'post-process' the emails - my preferred choice would be MySQL. I should mention at this point that the server is not to be used in the regular sense of email, but rather for data collection.
The only machine that will need to access the mails is the server itself, to parse the headers and the body and harvest the necessary data.
Is it possible to configure Postfix (or an alternative?) like this, or possibly to execute a script upon receipt of an email, in which I would parse the email and add it to the database myself.
The basic purpose of the server is to receive emails which will then be stored and action taken depending on the contents of the body or the headers of the email.
I'd appreciate any help or nudges in the right direction here, I feel a bit like I'm chasing my tail as it seems that the docs I find assume I'm more au fait with Linux and mail server configuration.

A: you can try following link
http://www.howtoforge.com/virtual-users-domains-postfix-courier-mysql-squirrelmail-centos-5.3-x86_64

A: you can configure procmail [ with postfix ], mails - instead of being delivered to user's folder will be delivered on standard input to script defined by you. this script in turn can parse messages and take action [or just store entire mails in database for processing later].
in regular postfix setup you add:
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases

in /etc/aliases you add:
userName: "|/some/script"

and you run
postalias aliases


text:
Q: How to change a normal column to "computed" column I have a table in MSSQL server 2008. I would like to change one of the column in that table to computed column. Could somebody tell me how do I do that ?

A: Preserve the old data:
EXEC sp_rename 'MyTable.OldCol', 'RenamedOldCol', 'COLUMN';

Add computed column
ALTER TABLE MyTable ADD ComputedCol AS (some expression);

Then, when you're happy
ALTER TABLE MyTable DROP COLUMN RenamedOldCol;


text:
Q: How to save object according to a key which is hash created from tuple or list which numpy.ndarray My work takes a lot of computational time.
So I want to save each calculated result according to key, for example, a hashed key which generated by parameter which consist of a tuple include numeric, numpy.ndarray, etc.
To solve this assignment, I try to save result(for example, model of machine learning) according to a key, for example, it is hashed key generated from tuple or list which numpy.ndarray below code.
But I could not get hashed key from the tuple object include numpy.ndarray.
# Load dataset
iris = datasets.load_iris()

# generating model of SVM
from sklearn import svm
clf = svm.LinearSVC()
key_m=(iris.data, iris.target)
clf.fit(*key_m) # learn form the data according to parameter.

d = shelve.open("testDB")
# save object according to key(key_m)
d[hash(key_m)]=clf ## xx <- Error occurred.
# load object according to key(key_m)
clf_cron=d[hash(key_m)]

# Compare with base and retrieve
if clf==clf_cron:
    print("Equal\n")
else:
    print("Not Equal\n")

A: Numpy's ndarray object doesn't have a hash method, but you can use md5 or something similar:
import md5
m = md5.new()
m.update(iris.data)
m.update(iris.target)
key_m = m.hexdigest()


text:
Q: PHP4 - Parse ini I'm doing this on an old NAS drive which has php embeded and is running PHP4.
parse_ini_file is supported, but I can't create an array of values within the returned results.
The following works :
[first_section]
one = 1
five = 5
animal = BIRD

[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"

[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"

// Parse with sections
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);

but the third section just returns :
[third_section] => Array
        (
            [phpversion[]] => 5.3
        )

Not all of the values.
Am I doing this wrong or is it due to PHP 4 ?
Any alternative methods ?

A: Yes, this is due to PHP4. See http://3v4l.org/DMEud
The output starting from PHP 5 will give the third section as shown in the manual, while previous version will show the behavior you encounter.


text:
Q: Function for adding annotation (text + line) to an svg using d3.js? // legend description for fire colors
legendContText = wrapLabel("Color indicates time to containment (darker = longer) ranging from 8 to 114 days.  This one took 113 days.", 160);
const legendCont = legendOverlay.append("g")
  .attr("class","legend cont");
const legendContSpans = legendCont.append("text")
  .attr("y", yScale(70));
legendContText.forEach(function(string) {
  legendContSpans.append('svg:tspan')
  .text(string)
  .attr("font-size",yScale(0.28).toString()+"rem")
  .attr('x', yScale(-150))
  .attr('dy', yScale(5))
});
legendCont.append("line")
  .attr("class","legend cont")
  .attr("x1", yScale(-150))
  .attr("y1", yScale(57))
  .attr("x2", yScale(-140))
  .attr("y2", yScale(70));

So I created a visualization in d3 and I add several annotations to a large svg - each one consisting of several lines of text (one text object with several tspans) and one line.  Shown above is the code for one such annotation.
My code works fine (check out the result at http://heidistockton.com/fireandice/) - my issue is that it is WAY too repetitive and definitely not best practice (I have like 10-15 of them and they comprise nearly 40% of my code by row count).  Can someone help me determine a way to create a function for adding one such annotation?
I would expect the inputs of such a function to be:

*

*a string

*a width for the text wrapping

*a class name for the annotation (for cleaner html)

*x/y coordinates for the text box, and

*two sets of x/y coordinates for the line

The "wrapLabel" function just takes a string and breaks it into smaller chunks based on length (code from Carys Mills).   I would expect to either nest the wrapLabel function inside an annotation function or just include the output of the wrapLabel function as an input for the annotation function.
Full code for my project can be found here: https://github.com/heidi8297/heidi8297.github.io/blob/main/fireandice/main.js


text:
Q: Can I eliminate variables in systems of diophantine equations? Consider the system of diophantine equations bellow.
$\cases{a_1x+b_1y+c_1z=d_1 \\ a_2x+b_2y+c_2z=d_2}$
Am I allowed to eliminate variables like one would in linear algebra? I was doing an exercise the other day where I assumed this was allowed and the result I acquired did not seem to agree with the answer the authors gave. Perhaps I just expressed it differently but more than likely I messed up.


text:
Q: Notation for applying a function recursively. Consider a function $f: \mathbb{R} \to \mathbb{R}$ that is monotonically increasing in $x$ such that $x_t = f(x_{t-1})$ where $t$ represents time.
Let $x_t \leq x'_t$, so
$$ f(x_t) \leq f(f(x'_{t-1})) \leq f(f(f(x'_{t-2}))) \leq \cdots$$
Is there a more elegant way to write the expression with inequalities?
Note: I am unsure what tags to add.

A: $$f^n(x_{t-n+1}) \le f^{n+1}(x_{t-n}),$$
where the superscript indicates $n$-fold composition.


text:
Q: Will satisfying the OLS Assumptions matter if the only thing i care about is the value of y that is predicted from the output? If i dont care about the individual effects of each variable onto y, and building confidence intervals and stuff, but only that i get accurate predictions of my y values. Will satisfying them matter? If they do matter, then why are they not taken into consideration when we do linear regression in machine learning? The coeffs of the input variables that are produced remain the same, and if we get bad results when we do not satisfy them, we should surely take them into consideration, right?

A: Yes, but the strength of my Yes varies by the assumption. For instance, one of the assumptions of OLS is that the model is linear: $y=X\beta+\varepsilon$, You should agree with me that if this assumption is broken, then predicting becomes problematic. Also think about autocorrelation: if $E[X\varepsilon]>0$ then larger $X$ would tend to underestimate and predict with bias. etc.
Machine learning is almost entirely an interpolation exercise. You make the network weights remember a lot of combinations of inputs then interpolate between them when you get a new input. Although the formulae can be exactly the same, there is a difference in application. In a typical OLS setup you get some data X, then try to come up with a few coefficients $\beta$, typically much smaller set of them compared to the umber of observations. In ML you often devise much larger set of weights, even larger than the number of observations often. In this case the weights effectively "memorize" the mapping of $y$ to combinations of $X$. The OLS machinery is simple used as a way to memorize this mapping. The trouble comes when new $X'$ comes that is completely out of the field of previous $X$ that the algorithm has seen so far. In this case it's easy to get a nonsensical result.

A: It depends. You can measure prediction quality by cross-validation and the like, and this doesn't require some assumptions such as normality and linearity. If the assumptions are fulfilled, you are in a better position for achieving a good prediction result, however this is not a theorem and applies sometimes but not always (for example a truly linear system with large variance will yield worse OLS predictions than a slightly nonlinear one with a small variance, at least if the nonlinearity is suitable for linear approximation).
However, you may be interested in future prediction in regions in which you currently don't have test data, and then "slight nonlinearity" may play out much worse than you can assess from the data you have.
Furthermore, standard estimation of the prediction error with test and training sets still requires independence and identical distribution (given explanatory variables $x$) of test and training set, and of both regarding any future observations that you actually want to predict. If this is violated and you don't know how exactly, you cannot assess the prediction error in any reliable way.
PS: "If they do matter, then why are they not taken into consideration when we do linear regression in machine learning?" Well, everybody who ignores these things does so at their own peril...


text:
Q: CSS dot leaders at first line over complex background I need to implement dot leaders after first line of text using CSS to use it over texture/image background.
Expected behaviour:

I saw a few implementation of dot leaders over the internet. They all use one of the techniques below:

*

*::after dots + overflow

    Text

    $100

.item1 {
  display: flex;
}
.text1 {
  flex-grow: 1;
  position: relative;
  overflow: hidden;
}
.text1::after {
  content: '';
  position: absolute;
  bottom: 0;
  border-bottom: 1px dotted grey;
  width: 100%;
}
.price1 {
  align-self: flex-end;
}

*absolute dots + white background

      Text

      $100

.item2 {
  display: flex;
  justify-content: space-between;
  position: relative;
  mix-blend-mode: darken;
}
.item2::before {
  content: '';
  position: absolute;
  top: 1em;
  left: 0;
  right: 0;
  border-bottom: 1px grey dotted;
}
.bg2 {
  background: white;
  position: relative;
  z-index: 1;
}

*dumb flexbox

    Text

    $100

.item3 {
  display: flex;
  align-items: flex-start;
}
.dots3 {
  flex-grow: 1;
  border-bottom: 1px dotted grey;
  min-width: 10px;
  height: 1em;
}

They are all shown here: https://jsfiddle.net/rzmLg4yu/62/
Each of these techniques has its own pitfalls in my case.

*

*Has dot leaders at last line.

*Does not work over complex background, even with mix-blend-mode (uncomment bg line to see).

*Has large white gaps due to line breaks (resize to see). Switching to grid is no use.

Is there more solutions to this case?

A: Technic 3 can be improved to get rid of the wrapping gaps:

body {
  color: grey;
}

.width {
  width: 300px;
  padding: 5px;
  resize: horizontal;
  overflow: hidden;
  abackground: linear-gradient(45deg, yellow, black);
  background-repeat: repeat-x;
  background-size: 200px 100%;
}

.item3 {
  display: flex;
  align-items: flex-start;
}

.dots3 {
  flex-grow: 1;
  border-bottom: 1px dotted grey;
  min-width: 10px;
  height: 1em;
}

.text3 {
  padding-right: 0px;
  text-align: justify; /* <--- */
}

        3 Text text

        $100

    3 Text text text text text text text text text text text text text text text text

        $100

Here text-align: justify; will space the words evenly.

I think your issue with the second technic is because of white background color right? because of .bg2 {background: white;...}?
Otherwise, you should've used mix-blend-mode: lighten; to demonstrate the issue:

body {
  color: grey;
  padding: 20px;
}

.width {
  width: 230px;
  padding: 5px;
  resize: horizontal;
  overflow: auto;
  background: linear-gradient(90deg, yellow, black);
  background-repeat: repeat-x;
  background-size: 200px 100%;
}

div>div {
  background-color: white;
  border: 2px solid green;
}

.simpleDiv1 {
  mix-blend-mode: darken;
}

.simpleDiv2 {
  margin-top: 20px;
  mix-blend-mode: lighten;
}

darken blend. Simple text without any styles and stuff.

lighten blend. Simple text without any styles and stuff.

If you use darken blend then any normal text will disappear with that background, let alone dot leaders.

Technic two without background white:

body {
  color: grey;
  padding: 20px;
}

.width {
  width: 230px;
  padding: 5px;
  resize: horizontal;
  overflow: hidden;
  abackground: linear-gradient(90deg, yellow, black);
  background-repeat: repeat-x;
  background-size: 200px 100%;
}

.item2 {
  display: flex;
  justify-content: space-between;
  position: relative;
  mix-blend-mode: darken;
  text-decoration-line: underline;
  text-decoration-style: solid;
  text-decoration-color: white;
  text-decoration-thickness: 2px;
}

.item2::before {
  content: '\00a0';
  height: calc(1em - 0.5px);
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  border-bottom: 1px dotted gray;
  z-index: -1;
}

        2 Text text

        $100

        2 Text text text text text text text text text text text text text text text text

        $100

Here I'm using white underline, instead of whole white background, to hide dotleader. But you'll get white underline while using some blend modes.

Technic three can be improved if we are willing to break words while wrapping:

body {
  color: grey;
}

.width {
  width: 300px;
  padding: 5px;
  resize: horizontal;
  overflow: hidden;
  abackground: linear-gradient(45deg, yellow, black);
  background-repeat: repeat-x;
  background-size: 200px 100%;
}

.item3 {
  display: flex;
  align-items: flex-start;
}

.dots3 {
  flex-grow: 1;
  border-bottom: 1px dotted grey;
  min-width: 10px;
  height: 1em;
}

.text3 {
  padding-right: 0px;
  word-break: break-all;
}

        3 Text text

        $100

    3 Text text text text text text text text text text text text text text text text

        $100

Here instead of wrapping on word boundaries, I'm wrapping on letter boundaries using word-break: break-all. If your font-size is 1em, then this way the maximum gap will be less than 1em, because browser won't be able to fit a letter less than 1em space.

A: Three improvements for the second technique

*

*I suggest using the value multiply for the  mix-blend-mode property. In the case of dark text, it gives a sharper result even on a gradient background. Look the first demo.

*We can simplify layout of the second technique with a help of the ::first-line pseudo-element. It can be used with "only a small subset of CSS properties", but this subset contains all background-related properties.
I think this also gives a better result against mix-blend-mode: darken. Compare the second and third demo.

*And the gap property helps to set the minimum gap between the text and the price.
There are three demos in the snippet below:

*

*First one shows mix-blend-mode: multiply in action.

*The other two compare the effect of mix-blend-mode: darken on two layouts - with an extra bg block and with the ::first-line pseudo-element.

https://codepen.io/glebkema/pen/NWapXPQ?editors=1100

body {
  color: grey;
}

.width {
  width: 300px;
  padding: 5px;
  resize: horizontal;
  overflow: hidden;
  background: linear-gradient(45deg, yellow, black);
  background-repeat: repeat-x;
  background-size: 200px 100%;
}

.item2 {
  display: flex;
  justify-content: space-between;
  position: relative;
  mix-blend-mode: darken;
  gap: 10px;                 /* 3) */
}

.multiply .item2 {
  mix-blend-mode: multiply;  /* 1) */
}

.item2::before {
  content: '';
  position: absolute;
  top: 1em;
  left: 0;
  right: 0;
  border-bottom: 1px grey dotted;
}

.bg2 {
  background: white;
  position: relative;
  z-index: 1;
}

.price4,
.text4 {
  z-index: 1;
}

.price4,
.text4::first-line {         /* 2) */
  background: white;
}

mix-blend-mode: multiply;

                2 Text text

                $100

                2 Text text text text text text text text text text text text text text text text text

                $100

            4 Text text

            $100

            4 Text text text text text text text text text text text text text text text text text

            $100

mix-blend-mode: darken; (2nd method before 4th)

                2 Text text

                $100

                2 Text text text text text text text text text text text text text text text text text

                $100

            4 Text text

            $100

            4 Text text text text text text text text text text text text text text text text text

            $100

mix-blend-mode: darken; (4th method before 2nd)

            4 Text text

            $100

            4 Text text text text text text text text text text text text text text text text text

            $100

                2 Text text

                $100

                2 Text text text text text text text text text text text text text text text text text

                $100

A: Even the W3C official source has some disparity. You may see inconsistent rendering or poor support for invented features (such as non-monospace/preformatted, lead zero padding, varied currency widths).
Using a shim or Web Component such as Leader-Line would be advisable. I would recommend you experiment with dash-animation to increase visibility on busy backgrounds (at the expense of annoying someone with a busy leader).

A: You can modify technique 1 to move the dot functionality from the text to another span:

    Text

    $100

    Text text text text text text text text text text text text

    $100

    Text text text text text text text text text text text text

.item1 {
  display: flex;
}
.line1 {
  flex-grow: 1;
  position: relative;
  overflow: hidden;
}
.line1::after {
  content: '';
  position: absolute;
  bottom: 0;
  border-bottom: 1px dotted grey;
  width: 100%;
}
.price1 {
  align-self: flex-end;
}

This works as intended:

And a JSFiddle

A:

.item1 {
  display: flex;
  font-size:32px;
  color:#808080;
}
.line1 {
  flex-grow: 1;
  position: relative;
  overflow: hidden;
}
.line1::after {
  content: '';
  position: absolute;
  bottom: 0;
  border-bottom: 1px dotted #808080;
  width: 100%;
}
.price1 {
  align-self: flex-end;
}

  Text text

  $100

  Text text text text text text text text text

  $100

  Text text text text text text text


text:
Q: How to insert data into a PL/SQL table type rather than PL/SQL table? I have a table TDATAMAP which has around 10 million records, I want to fetch all the records into a PL/SQL table type variable, match it with some criteria and finally insert all the required records in a staging table. Please tell me if its possible to do it using PL/SQL table typle variable and BULK INSERT/COLLECT . I am also concerned about the performance of the code.

A:
" I want to fetch all the records into a PL/SQL table type variable,
  match it with some criteria and finally insert all the required
  records in a staging table."

This may well not be the right approach to take.  SQL is a set-based programming language.  It has features which allow us to identify and work with just the set of records we want.
So, instead of a three stage process - extract, filter, insert - celebrate the joy of sets:
insert into your_staging_table
select whatver
from your_10m_table
where something = your_matching_criteria;

There will be scenarios when this is not good enough.  But this is the approach to start with.

A: You can, but you probably should not, load 10 million records into memory at once - as long as there is sufficient memory to hold that much.  Normally BULK COLLECT is used with the LIMIT clause to process a finite number of rows at a time e.g. 1000.
From the documentation:

The BULK COLLECT clause lets you fetch entire columns from the result
  set, or the entire result set at once. The following example,
  retrieves columns from a cursor into a collection:

DECLARE
   TYPE NameList IS TABLE OF emp.ename%TYPE;
   names NameList;
   CURSOR c1 IS SELECT ename FROM emp WHERE job = 'CLERK';
BEGIN
   OPEN c1;
   FETCH c1 BULK COLLECT INTO names;
   ...
   CLOSE c1;
END;

The following example uses the LIMIT clause. With each iteration of
  the loop, the FETCH statement fetches 100 rows (or less) into index-by
  table acct_ids. The previous values are overwritten.

DECLARE
   TYPE NumList IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
   CURSOR c1 IS SELECT acct_id FROM accounts;
   acct_ids NumList;
   rows NATURAL := 100;  -- set limit
BEGIN
   OPEN c1;
   LOOP
      /* The following statement fetches 100 rows (or less). */
      FETCH c1 BULK COLLECT INTO acct_ids LIMIT rows;
      EXIT WHEN c1%NOTFOUND;
      ...
   END LOOP;
   CLOSE c1;
END;


text:
Q: ImportError: No module named expected_conditions I am using Linux Mint 17 and python 2.7 and selenium.
When I try to selenium webdriver its working fine
but python not detecting expected_conditions
    >>import selenium
    >>import expected_conditions as EC
     Trackback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named expected_conditions

any solution to fix this?

A: I am assuming you want to import Selenium's expected conditions
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC


text:
Q: LLamar desde un botón Swift 2 Xcode 7 Hola tengo el siguiente código que es para llamar desde un botón o abrir el dial para llamar en iOS el tema es que en mi proyecto tengo muchas pantallas y en cada una un botón que tiene que llamar a un número distinto. Mi consulta hay alguna forma de conectar todas las pantallas a un controller y colocar el codigo para llamar enlazado a cada botón o alguna otra forma mejor de aplicar el código a cada botón.
Swift
@IBAction func marcar(sender: AnyObject) {
        if let url = NSURL(string: "tel://0180032323") {
            UIApplication.sharedApplication().openURL(url)
        }

    }

A: Para manejar todo este tipo de situación, crear una clase Utils así:
class Utils: NSObject {
    class func call() {
        if let url = NSURL(string: "tel://0180032323") {
            UIApplication.sharedApplication().openURL(url)
        }
    }
}

Y llamarlo así desde cualquier parte de tu app:
Utils.call()

A: el problema que veo es que es un ibaction, ese ibaction debe de mandar llamar a una funcion  y que esa funcion sea la que tenga el codigo
una ves en una funcion desde otro archivo de swift prueba con esto:
let llamar = PrimeraPantalla()
llamar.FuncionLlamada()


text:
Q: How to add items in Firebase using react native I'm still a newbie in react native and it's also my first time using Firebase database. So, using the official documentation i've managed to add items (composed only by title ) in the database but only using an alertIos.
Now I need to navigate to other screen, add items and I need  the items themselves composed by title and genre for example. Thank you
PS: here is the tutorial that i used : https://firebase.googleblog.com/2016/01/the-beginners-guide-to-react-native-and_84.html
Also, I used a workaround when accessing to the Firebase database : i changed the rules to read and write for everybody (thing I'm sure is wrong), so can you help me access in a secure way.


text:
Q: Не создается окно в eclipse Когда пытаюсь создать окно просто через некоторое время в консоли появляется надпись terminated и все. Мне сказали нужно использовать SwingUtilities, но это не помогло. На других компьютерах когда делал все получалось. Пример окна:
import java.awt.*;
import javax.swing.*;

public class Main extends JFrame{

public static void main(String[] args) {
    SwingUtilities.invokeLater(
            () -> new Main()
        );
}
Main(){
    this.setDefaultCloseOperation(
            JFrame.EXIT_ON_CLOSE
        );
        this.setPreferredSize(
            new Dimension(1280, 1024)
        );
        this.pack();
        this.setVisible(true);
}

}

A: значит какая-то локальная ошибка.всё работает.может что-то в  Установке и настройке Eclipse.Переставлять Eclipse.попробуйте Debug.


text:
Q: PHP Docker Vendor Autoload.php not found I am trying to setup the Dockerfile for PHP services. PHP scripts are served using Nginx server in docker container but its giving me vendor/autoload.php not found error.
I have tried changing Dockerfile several times but the vendor/autoload.php error still persists.
Here is the Dockerfile
FROM composer as builder

RUN mkdir -p /usr/app/php-services
WORKDIR /usr/app/php-services
#copy composer file
COPY composer.json .

RUN composer install

#copy php-scripts to /usr/app/php-services
COPY . .

FROM nginx:alpine

COPY --from=builder /usr/app/php-services /usr/app/php-services
COPY ./phpdocker/nginx/nginx.conf /etc/nginx/conf.d/default.conf

#check if vendor has autoload file and it exists!!!
RUN ls /usr/app/php-services/vendor

EXPOSE 8000

The scripts should work fine but whenever I run docker logs it says.

Here is the nginx.conf file
server {
listen 8000;

access_log /var/log/nginx/application.access.log;

root /usr/app/php-services;

location / {
    try_files $uri /index.php$is_args$args;
}

location ~ \.php$ {
    fastcgi_pass php-fpm:9000;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PHP_VALUE "error_log=/var/log/nginx/application_php_errors.log";
    fastcgi_buffers 16 16k;
    fastcgi_buffer_size 32k;
    include fastcgi_params;
}
}

I have tried almost everything and have literally no idea why this is happening. What am I doing wrong here? Is there any issue in my nginx.conf file?

A: Sorry about the last response, I misunderstood the problem.
However I was able to build a similar container but wasn't able to reproduce the error. It might be something with the php-scripts you are adding that aren't in this post. I was able to get a similar container build though using modified copies of your Dockerfile + nginx.conf. I also added some debugging for troubleshooting in the Docker file and created a launch/build script.
I edited the Dockerfile to have the following. This will add setting 755 permissions if you need, listing out a few directories in question and your log. If needed post that output to comments.
FROM composer as builder
RUN mkdir -p /usr/app/php-services
WORKDIR /usr/app/php-services
COPY composer.json .
RUN composer install
#copy php-scripts to /usr/app/php-services
COPY . .
COPY php.ini /usr/app/php-services
FROM nginx:alpine
COPY --from=builder /usr/app/php-services /usr/app/php-services
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY php.ini .
#check if vendor has autoload file and it exists!!!
RUN chmod 755 -R /usr/app/php-services;ls -lrt /etc/nginx/ /var/log /usr/app/php-services/  /usr/app/php-services/vendor /usr/app/php-services/vendor/twitter.php;/var/log/nginx/application_php_errors.log | tee -a shellcheck.log
    #CMD ["ls -la /usr/app/php-services/vendor"]
EXPOSE 8000

Then edited nginx.conf to have the following. Added resolver information (unsure if this will apply to you or not) including upstream property, try_files, including snippets for fastcgi.
    server {
listen 8000;
resolver 127.0.0.11;
set $upstream php-fpm:9000;
access_log /var/log/nginx/application.access.log;
root /usr/app/php-services;
location / {
try_files $uri /index.php$is_args$args;
}
location ~ \.php$ {
try_files $uri =404;
include snippets/fastcgi-php.conf;
fastcgi_pass  $upstream;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PHP_VALUE "error_log=/var/log/nginx/application_php_errors.log";
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
include fastcgi_params;
}
}

Then created a shell script to launch build and report back some debug info. Add this next to the Dockerfile on docker host, make it executable with chmod +x run-container.sh then run it with ./run-container.sh $PORTNUM. ie ./run-container.sh 8000
    #!/bin/bash
docker build . -t php-services:v3
docker run -d -p $1:8000 php-services:v3
CONTAINER=`docker ps -a | head -2 | tail -1| awk '{print $1}'`
echo "Your container is: $CONTAINER"
docker ps -a | head -2 | tail -1| awk '{print $1}'
docker cp $CONTAINER:/var/log/nginx/ .
docker cp $CONTAINER:/shellcheck.log .
docker cp $CONTAINER:/etc/nginx/fastcgi.conf .
docker ps -a  | grep $CONTAINER
docker logs  $CONTAINER

Let me know if any of this works for you, for some reason yours is expecting a twitter.php which I do not have and wasn't an issue. Is that something you are copying into container from that folder?


text:
Q: Class Serialization To XML Given the following class design:
 public class AllUserCollections
    {
        public List<UserCollection> UserCollections { get; set; }

        public AllUserCollections()
        {
            this.UserCollections = new List<UserCollection> ();
        }
    }

    public class UserCollection
    {
        public string UserGroup { get; set; }
        public Dictionary<int,User> Users { get; set; }

        public UserCollection(string userGroup)
        {
            this.UserGroup = userGroup;
            this.Users = new Dictionary<int, User> ();
        }
    }

    public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
        public AgeGroup UserAgeGroup { get; set; }
    }

    public enum AgeGroup
    {
        Twenties,
        Thirties,
        Fourties,
    }

How can I serialize this to XML using my existing serialization class?
public static class HardDriveService
    {
        private static string docsFolderPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
        private const string fileName = "AllUserCollections.xml";
        private static string filePath = Path.Combine(docsFolderPath, fileName);

        private static bool FileExists(string fullFilePath)
        {
            if (File.Exists (fullFilePath))
                return true;

            return false;
        }

        public static void Save(AllUserCollections allUserCollections)
        {
            if (FileExists(filePath))
            {
                File.Delete (filePath);
            }

            XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType());
            using(StreamWriter writer = new StreamWriter(filePath))
            {
                serializer.Serialize(writer.BaseStream, allUserCollections);
            }
        }

        public static AllUserCollections Read()
        {
            AllUserCollections allUserCollections = new AllUserCollections();
            XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType());

            if (FileExists(filePath))
            {
                StreamReader reader = new StreamReader(filePath);
                object deserialized = serializer.Deserialize(reader.BaseStream);
                allUserCollections = (AllUserCollections)deserialized;
            }

            return allUserCollections;
        }

    }//End of class.

ISSUES
My code seems to fail on this line -
XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType());

I wonder if it's to do with the class needing to be explicitly marked as "serializable"? How would I do this?
Usage
This code will run on an iphone and save/read directly from an app to XML on the iPhone hard drive.

A: XMLSerializer doesn't support Dictionary out of the box. Your UserCollection class has a Dictionary. See this link for a workaround.
Why doesn't XmlSerializer support Dictionary?
Other than that the XMLSerializer requires that your classes have default constructors (UserCollection and User don't) and each of them must have the [Serializable] attribute.

A: You could use XElement to build up an XML format. You could use them along the following lines:
public static XElement ToXml(this User user)
{
    if (user == null)
    {
        throw new ArgumentException("User can not be null.");
    }

    XElement userElement = new XElement("User");
    userElement.Add(new XElement("ID", user.ID));
    userElement.Add(new XElement("Name", user.Name));
    userElement.Add(new XElement("Location", user.Location));
    userElement.Add(new XElement("UserAgeGroup", user.UserAgeGroup));

    return userElement;
}

public static string ToXml(this UserCollection userCollection)
{
    if (userCollection == null)
    {
        throw new ArgumentException("UserCollection can not be null.");
    }

    XElement userCollectionElement = new XElement("UserCollection");
    userCollectionElement.Add(new XElement("UserGroup", userCollection.UserGroup));
    userCollectionElement.Add(new XElement("Users",
                                           userCollection.Users.Select(x => new XElement("User", x.ToXml()));

    return userCollectionElement;
}

Calling .ToString() on an XElement should give you an xml-formatted string.

A: Here you have 2 choices  XmlSerializer(which  will not work with Dictionary or List type deserialization  )  or you can use DataContractSerializer which added in .net 3.0 and has a lot advantages here are few: form  this  post

*

*optimized for speed (about 10% faster than XmlSerializer, typically)

*in "opt-in" - only stuff you specifically mark as [DataMember] will be serialized

*doesn't support XML attributes (for speed reasons)
Note : you should add reference to the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\System.Runtime.Serialization.dll
//to serialize
        SerializeHelper.Serialize("your filename" ,new AllUserCollections());
// deserialize
        var usertCollections = SerializeHelper.Deserialize<AllUserCollections>("yourfile name");

//code
 [DataContract]
    public class AllUserCollections
    {
        public List<UserCollection> UserCollections { get; set; }

        public AllUserCollections()
        {
            this.UserCollections = new List<UserCollection>();
        }
    }
    [DataContract()]
    public class UserCollection
    {
         [DataMember]
        public string UserGroup { get; set; }

         [DataMember]
        public Dictionary<int, User> Users { get; set; }

        public UserCollection(string userGroup)
        {
            this.UserGroup = userGroup;
            this.Users = new Dictionary<int, User>();
        }
    }
    [DataContract()]
    public class User
    {   [DataMember]
        public int ID { get; set; }
         [DataMember]
        public string Name { get; set; }
         [DataMember]
        public string Location { get; set; }
         [DataMember]
        public AgeGroup UserAgeGroup { get; set; }
    }
     [DataContract]
    public enum AgeGroup
    {
        Twenties,
        Thirties,
        Fourties,
    }
    public  static class  SerializeHelper
    {
         public static void Serialize<T>(string fileName, T obj)
    {
        using (FileStream writer = new FileStream(fileName, FileMode.Create))
        {
         DataContractSerializer ser =
            new DataContractSerializer(typeof(T));
        ser.WriteObject(writer, obj);
        writer.Close();
        }

    }

    public static T Deserialize<T>(string fileName)
    {
        T des;
        using (FileStream fs = new FileStream(fileName,FileMode.Open))
        {
        XmlDictionaryReader reader =
            XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
        DataContractSerializer ser = new DataContractSerializer(typeof(T));
        des =
            (T)ser.ReadObject(reader, true);
        reader.Close();
        fs.Close();

        }

        return des;
    }
    }

A: FULL WORKING SOLUTION
Data Model
using System;
using System.Collections.Generic;

namespace iPhoneHardDriveCRUDPrototype
{
    [Serializable]
    public class AllUserCollections
    {
        public List<UserCollection> UserCollections { get; set; }

        public AllUserCollections()
        {
            this.UserCollections = new List<UserCollection> ();
        }
    }

    [Serializable]
    public class UserCollection
    {
        public string UserGroup { get; set; }
        public SerializableDictionary<int,User> Users { get; set; }

        public UserCollection()
        {
            this.Users = new SerializableDictionary<int, User> ();
        }

        public UserCollection(string userGroup)
        {
            this.UserGroup = userGroup;
            this.Users = new SerializableDictionary<int, User> ();
        }
    }

    [Serializable]
    public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
        public AgeGroup UserAgeGroup { get; set; }

        public User()
        {

        }
    }

    [Serializable]
    public enum AgeGroup
    {
        Twenties,
        Thirties,
        Fourties,
    }
}

Serializable Dictionary
using System;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace iPhoneHardDriveCRUDPrototype
{
    [XmlRoot("dictionary")]
    public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
    {
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

            bool wasEmpty = reader.IsEmptyElement;
            reader.Read();

            if (wasEmpty)
                return;

            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                reader.ReadStartElement("item");
                reader.ReadStartElement("key");
                TKey key = (TKey)keySerializer.Deserialize(reader);
                reader.ReadEndElement();
                reader.ReadStartElement("value");
                TValue value = (TValue)valueSerializer.Deserialize(reader);
                reader.ReadEndElement();
                this.Add(key, value);
                reader.ReadEndElement();
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

            foreach (TKey key in this.Keys)
            {
                writer.WriteStartElement("item");
                writer.WriteStartElement("key");
                keySerializer.Serialize(writer, key);
                writer.WriteEndElement();
                writer.WriteStartElement("value");
                TValue value = this[key];
                valueSerializer.Serialize(writer, value);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }

    }//End of Class....
}

Serializer
using System;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;
using System.Collections.Generic;

namespace iPhoneHardDriveCRUDPrototype
{
    public static class HardDriveService
    {
        private static string docsFolderPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
        private const string fileName = "AllUserCollections.xml";
        private static string filePath = Path.Combine(docsFolderPath, fileName);

        private static bool FileExists(string fullFilePath)
        {
            if (File.Exists (fullFilePath))
                return true;

            return false;
        }

        public static void Save(AllUserCollections allUserCollections)
        {
            if (FileExists(filePath))
            {
                File.Delete (filePath);
            }

            XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType());
            using(StreamWriter writer = new StreamWriter(filePath))
            {
                serializer.Serialize(writer.BaseStream, allUserCollections);
            }
        }

        public static AllUserCollections Read()
        {
            AllUserCollections allUserCollections = new AllUserCollections();
            XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType());

            if (FileExists(filePath))
            {
                StreamReader reader = new StreamReader(filePath);
                object deserialized = serializer.Deserialize(reader.BaseStream);
                allUserCollections = (AllUserCollections)deserialized;
            }

            return allUserCollections;
        }

    }//End of class.
}


text:
Q: JAX-RS CXF cross-parameters validation in case of sub-resources I'm building REST services based on JAX-RS CXF and looking for a way how to validate pair of cross-parameters which depend from each other. The trickiest part is that I'm dealing with sub-resources and my method does not take all parameters to be validated at method level.
Let's take some simple entities as an example.
The top level API is CustomerResource:
POST /customer    -- add a new customer
GET  /customer/{customerId} -- get the customer by id

Sub-resource API is OrderResource:
POST /customer/{customerId}/order -- put a new order for the customer with {customerId}

where body is
{
    "itemId" : "123",
    "discountId" : "456"
}

I need to validate that Customer with {customerId} has the discount {discountId} which belongs to him.
@Path("/customer")
public interface CustomerResource {
    ...
    @Path("/{customerId}/order")
    OrderResource ordersOf(@PathParam("customerId") String customerId);
    ...
}

public interface OrderResource {
    ...
    @POST
    @Path("/")
    @Consumes(MediaType.APPLICATION_JSON)
    Order apply(@Valid OrderRequest orderRequest);
    ...
}

public class OrderRequest {
    private String itemId;
    private String discountId;
    ...
}

It's easy to validate each isolated parameter for @NotNull or for existence.
But my special discount validator should has and customerId and discountId at the time of validation to read right objects from DB and perform the check.
Of course I can do the validation later on service layer, but at the moment I am trying to keep service code nice and simple as possible.
Please also note, that it's too expensive to change API or update DB relations.


text:
Q: How to solve a system of equations which includes vectors? I'm starting to wonder if this is something that mathematica just can't do? I thought something like this might work:
Reduce[(p0 | pt | v0 | vt | a1 | a2) \[Element] Vectors[3, Reals]
  && (t1 | t2 | k) \[Element] Reals
  && v0 + a1*t1 == vt - a2*t2
  && p0 + v0*t1 + 1/2*a1*t1^2 == pt - (v0 + a1*t1)*t2 - 1/2*a2*t2^2
  && Norm[a1] == k
  && Norm[a2] == k
  && t1 >= 0
  && t2 >= 0,
 {a1, a2, t1, t2}]

But I get this:

Reduce::elemc: Unable to resolve the domain or region membership
  condition (p0|pt|v0|vt|a1|a2)[Element]Vectors[3,Reals]. >>

I'm interpreting this to mean that Reduce can't handle vectors? I read a suggestion about specifying the components for all the vectors but this is already complex enough, if I did that it would be enormous.


text:
Q: how to have multiple arguments to multiple variables for a function I'm trying to have multiple arguments through argparse to be used in a function
I want the arguments to be put in the function below
def toto(var1,var2,var3):
    print(var1,var2,var3)

This is my argparse
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--names', type=str,nargs=1, help='<Required> Set flag')
args = parser.parse_args()

Issue is I need three arguments.
I put the function in a file like hello.py
if __name__ == "__main__":
    print(args)
    if args.names:
        toto(var1,var2,var3)

I then run the command
python hello.py --names 'bobo'

I have this error
Traceback (most recent call last):
  File "hello.py", line 15, in <module>
    toto(var1,var2,var3)
NameError: names 'var1' is not defined

What is it happening and how can I add three arguments instead of one?
Thanks

A: First, you need to specify the number of arguments argparse should accept on the command line, in this case three so nargs=3.
parser.add_argument('--names', type=str,nargs=3, help='<Required> Set flag')

The variables will be stored in args.names which is a list in this case, so you can unpack that list into three variables:
if __name__ == "__main__":
    if args.names:
        var1, var2, var3 = args.names
        toto(var1, var2, var3)

Finally, run it like below and it will give you the correct results:
~$ python hello.py --names 'babi' 'bibo' 'bobu'
babi bibo bobu


text:
Q: No se coloca la casilla de CheckBox MVC ASP.NET Estoy trabajando con CheckBox y tengo problemas para hacer que se vea la casilla como se muestra en la imagen:

El problema es que me sale de la siguiente manera:

Estoy siguiendo el ejemplo de esta pagina con el video que proporciona y aun así no logro hacer que se vea como en la imagen:
https://www.infinetsoft.com/Post/How-to-add-checkbox-in-dropdownlist-using-jQuery/2501#.X8zAImUzbIU
Anexo código de mi View:
@{
   ViewBag.Title = "About";
 }

<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css"
      rel="stylesheet" type="text/css" />

<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css"
      rel="stylesheet" type="text/css" />

        Multiselect checkbox dropdown using jquery

Select Employee's Name

                @Html.DropDownList("EmpList", ViewBag.Employees as SelectList, new { style = "width:100%", multiple = "multiple" })

                <input type="button" id="btnSelected" value="Get Selected" />

Estoy utilizando MVC 4 Con VS2015 y la BD es una diferente a la que proporciona la pagina
Agredezco sus comentarios ya que tengo poco tiempo trabajando con esto

A: En tu vista (view) en lugar de
@Html.DropDownList("EmpList"..

intenta con
@Html.ListBoxFor("EmpList"..

El primer helper hace un render de un elemento html del tipo select simple, mientras que el segundo genera un select con la opción de multiselect