问:
Website Image preload for faster loading
I`m trying to build a cool gallery for my photography website:

I thought i`m already done. On my computer i looks pretty cool, so i uploaded it to my Webspace on Webgo.

The problem is the loading time of the images, when loading the website the first time.

I build the masonry look with pure css. And the images are hard coded. Later i will fix this and load them via php.

Is there any possibility to get a faster image load? I already rendered the images down to max-width: 800px via photoshop.

答:
make thumbnails - make the images smaller, these are high resolution images and smaller ones will load much faster.

set up some sub-domains for images, this will let most modern browsers make multiple image requests simultaneously
so right now you website is portfolio.marcelmerz.de
so set up some sub domains for pictures e.g.
img1.marcelmerz.de, img2.marcelmerz.de, img3.marcelmerz.de, and img4.marcelmerz.de

point all 4 sub domains to where your images are, then alternate the image urls to use the different sub-domains.


来源: stackexchange

问:
Microsoft Access - Creating a form which looks up data between 2 dates
For my College assignment, I have to create a database in Access, I have done 99% of my database, apart from this section which I'm stuck on.

In my DB, I have a tickets table, which contains records on order information and a field containing a date. For my assignment, I have to create a Form which reads from a Query.

For example, in my Form i have already created i have 2 Combo boxes with the dates already pulled from the Query. I need to be able to drop down one of the boxes and input 1 date, and then drop down the other box and select a different date, press a button and it generate me a Report.

The part I am asking for help on is the expression which is used to look up the data inside the Query. I tried using this expression, which Access said was too complicated.

```<code>[Forms]![frmOrdersBetweenTwoDates]![Combo33] And [Forms]![frmOrdersBetweenTwoDates]![Combo36]
</code>```

My full SQL query is:

```<code>SELECT tblTickets.CustomerID, tblCustomers.FullName, tblCustomers.AddressLine1, tblTickets.OrderNumber, tblTickets.OrderDate
FROM tblCustomers INNER JOIN tblTickets ON tblCustomers.[CustomerID] = tblTickets.[CustomerID]
WHERE ((("WHERE [OrderDate]") Between [Forms]![frmOrdersBetweenTwoDates]![Combo52] And [Forms]![frmOrdersBetweenTwoDates]![Combo54]));
</code>```

My expression/query now returns the report, but there is no data inside the report. How could i fix this?

Cheers.

答:
Should post the complete query statement. Expect the filter clause should be like:

WHERE [date fieldname] BETWEEN [Forms]![frmOrdersBetweenTwoDates]![Combo33] AND [Forms]![frmOrdersBetweenTwoDates]![Combo36]

However, I don't use dynamic parameterized queries. I prefer to use the WHERE argument of OpenReport (same for OpenForm), in VBA:

DoCmd.OpenReport "report name", , , "[date fieldname] BETWEEN #" & Me.Combo33 & "# AND #" & Me.Combo36 & "#"

ContentLicense: CC BY-SA 3.0

Body:
For my College assignment, I have to create a database in Access, I have done 99% of my database, apart from this section which I'm stuck on.

In my DB, I have a tickets table, which contains records on order information and a field containing a date. For my assignment, I have to create a Form which reads from a Query.

For example, in my Form i have already created i have 2 Combo boxes with the dates already pulled from the Query. I need to be able to drop down one of the boxes and input 1 date, and then drop down the other box and select a different date, press a button and it generate me a Report.

The part I am asking for help on is the expression which is used to look up the data inside the Query. I tried using this expression, which Access said was too complicated.

[Forms]![frmOrdersBetweenTwoDates]![Combo33] And [Forms]![frmOrdersBetweenTwoDates]![Combo36]

My full SQL query is:

SELECT tblTickets.CustomerID, tblCustomers.FullName, tblCustomers.AddressLine1, tblTickets.OrderNumber, tblTickets.OrderDate
FROM tblCustomers INNER JOIN tblTickets ON tblCustomers.[CustomerID] = tblTickets.[CustomerID]
WHERE ((("WHERE [OrderDate]") Between [Forms]![frmOrdersBetweenTwoDates]![Combo52] And [Forms]![frmOrdersBetweenTwoDates]![Combo54]));

My expression/query now returns the report, but there is no data inside the report. How could i fix this?

Cheers.


问:
PHP If Both Variables are 0
Why is it echoing 'both variables 0'

https://3v4l.org/E530h

```<code><?php

  $QuantityOrdered = '1';
  $QuantityShipped = '0';
  echo '<br />' . $QuantityOrdered . ' & ' . $QuantityShipped . '<br />';

  if ($QuantityOrdered != '0' && $QuantityShipped != '0') {
    echo 'at least one variable is not 0';
  }

  else {
    echo 'both variables 0';
  }
</code>```

Trying to get it so that if BOTH $QuantityOrdered and $QuantityShipped are 0, it goes to the else statement.

If $QuantityOrdered and $QuantityShipped are anything other than BOTH 0... for example, 0 and 1 (as in my example).. or 1 and 1, 2 and 2 etc...

anything other than both being 0, it goes to the if statement.

答:
you need to use OR condition like this, if you use && (and) condition then both condition need to true so if $QuantityOrdered != '0' true and $QuantityShipped != '0' true then execute this code so your both condition need to true
so this condition not work

```<code> if ($QuantityOrdered != '0' && $QuantityShipped != '0') {
  echo 'at least one variable is not 0';
}
</code>```

if you want to check one value true then execute this code then use or (||) condition

```<code>if ($QuantityOrdered != '0'|| $QuantityShipped != '0') {
  echo 'at least one variable is not 0';
}
else {
 echo 'both variables 0';
 }
</code>```

for more information

http://www.w3resource.com/php/operators/logical-operators.php

Title: PHP If Both Variables are 0

Body:
Why is it echoing 'both variables 0'

https://3v4l.org/E530h

<?php

  $QuantityOrdered = '1';
  $QuantityShipped = '0';
  echo '
' . $QuantityOrdered . ' & ' . $QuantityShipped . '
';

  if ($QuantityOrdered != '0' && $QuantityShipped != '0') {
    echo 'at least one variable is not 0';
  }

  else {
    echo 'both variables 0';
  }

Trying to get it so that if BOTH $QuantityOrdered and $QuantityShipped are 0, it goes to the else statement.

If $QuantityOrdered and $QuantityShipped are anything other than BOTH 0... for example, 0 and 1 (as in my example).. or 1 and 1, 2 and 2 etc...

anything other than both being 0, it goes to the if statement.

Body:
you need to use OR condition like this, if you use && (and) condition then both condition need to true so if $QuantityOrdered != '0' true and $QuantityShipped != '0' true then execute this code so your both condition need to true
so this condition not work

 if ($QuantityOrdered != '0' && $QuantityShipped != '0') {
  echo 'at least one variable is not 0';
}

if you want to check one value true then execute this code then use or (||) condition

if ($QuantityOrdered != '0'|| $QuantityShipped != '0') {
  echo 'at least one variable is not 0';
}
else {
 echo 'both variables 0';
 }

for more information

http://www.w3resource.com/php/operators/logical-operators.php


问:
Add 12 months to a Date in PHP
We have a "start date" echoed out in a WooCoomerce email like so:

```<code><?php echo esc_html( date_i18n( wc_date_format(), $subscription->get_time( 'start', 'site' ) ) ); ?>
</code>```

The output looks like this: March 29, 2017

How would I go about adding 12 months to this date and echoing it out in the email as an "end date"?

Thanks

答:
The first line just sets up a variable for clarity's sake. The second line adds one year to the time and assigns it to $endDate. Simply add $endDate to your echo.

```<code>$startDate = $subscription->get_time( 'start', 'site' );
$endDate = date("F-d-Y", strtotime(date("F-d-Y", strtotime($startgDate)) . " + 1 year"));
</code>```

Title: Add 12 months to a Date in PHP

Body:
We have a "start date" echoed out in a WooCoomerce email like so:

<?php echo esc_html( date_i18n( wc_date_format(), $subscription->get_time( 'start', 'site' ) ) ); ?>

The output looks like this: March 29, 2017

How would I go about adding 12 months to this date and echoing it out in the email as an "end date"?

Thanks

Body:
The first line just sets up a variable for clarity's sake. The second line adds one year to the time and assigns it to $endDate. Simply add $endDate to your echo.

$startDate = $subscription->get_time( 'start', 'site' );
$endDate = date("F-d-Y", strtotime(date("F-d-Y", strtotime($startgDate)) . " + 1 year"));


问:
Django. Adding objects that have two foreign keys to the same class
my problem is that when you want to add objects to a class that contains two foreign keys to other (equal) classes. First add an object of the class to which the foreign key refers. And when you want to select the same object but in another field, it does not appear.

models.py

```<code>class Team(models.Model):
     name = models.CharField(max_length=255)

class Match(models.Model):
     home = models.ForeignKey(Team)
     away = models.ForeignKey(Team)
</code>```

So .. How do I do if I want local and away to be the same teams without having to update the admin page when I create the local team?

Thanks!

Agu

答:
Short of refreshing the page, the only other way I can think of doing this is by adding raw_id_fields to the admin.py. This will allow a popup to show up when selecting a ForeignKey, so it should let you create a Team and select it without refreshing the page.

Source

https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields

Body:
my problem is that when you want to add objects to a class that contains two foreign keys to other (equal) classes. First add an object of the class to which the foreign key refers. And when you want to select the same object but in another field, it does not appear.

models.py

class Team(models.Model):
     name = models.CharField(max_length=255)

class Match(models.Model):
     home = models.ForeignKey(Team)
     away = models.ForeignKey(Team)

So .. How do I do if I want local and away to be the same teams without having to update the admin page when I create the local team?

Thanks!

Agu


问:
f-strings vs str.format()
I'm using the .format() a lot in my Python 3.5 projects, but I'm afraid that it will be deprecated during the next Python versions because of f-strings, the new kind of string literal.

```<code>>>> name = "Test"
>>> f"My app name is {name}."
'My app name is Test.'
</code>```

Does the formatted string feature come to fully replace the old .format()? And from now on, would it be better to use the new style in all cases?

I understand that it's based on the idea that "Simple is better than complex." However, what about performance issues; is there any difference between them? Or is it just a simple look of the same feature?

答:
To build on Jim's answer and address your performance concern, I used python's dis module to compare the bytecode instructions for two syntactically different, but functionally equivalent functions.

```<code>import dis

def f1():
    a = "test"
    return f"{a}"

def f2():
    return "{a}".format(a='test')

print(dis.dis(f1))
print(dis.dis(f2))
</code>```

The result of which is:

``` 11           0 LOAD_CONST               1 ('test')
              2 STORE_FAST               0 (a)

 12           4 LOAD_FAST                0 (a)
              6 FORMAT_VALUE             0
              8 RETURN_VALUE
None
 15           0 LOAD_CONST               1 ('{a}')
              2 LOAD_ATTR                0 (format)
              4 LOAD_CONST               2 ('test')
              6 LOAD_CONST               3 (('a',))
              8 CALL_FUNCTION_KW         1
             10 RETURN_VALUE
None```

One can see that the f-string handles the formatting without attribute or function calls, which can impose type checking and memory overhead. According to timeit this results in a roughly 3x performance gain (for my specific functions)

```>>> timeit.timeit('f1()', 'from __main__ import f1', number=100000)
0.012325852433775708
>>> timeit.timeit('f2()', 'from __main__ import f2', number=100000)
0.036395029920726074```

ContentLicense: CC BY-SA 4.0

Title: f-strings vs str.format()

Body:
I'm using the .format() a lot in my Python 3.5 projects, but I'm afraid that it will be deprecated during the next Python versions because of f-strings, the new kind of string literal.

>>> name = "Test"
>>> f"My app name is {name}."
'My app name is Test.'

Does the formatted string feature come to fully replace the old .format()? And from now on, would it be better to use the new style in all cases?

I understand that it's based on the idea that "Simple is better than complex." However, what about performance issues; is there any difference between them? Or is it just a simple look of the same feature?

Body:
To build on Jim's answer and address your performance concern, I used python's dis module to compare the bytecode instructions for two syntactically different, but functionally equivalent functions.

import dis

def f1():
    a = "test"
    return f"{a}"

def f2():
    return "{a}".format(a='test')

print(dis.dis(f1))
print(dis.dis(f2))

The result of which is:

 11           0 LOAD_CONST               1 ('test')
              2 STORE_FAST               0 (a)

 12           4 LOAD_FAST                0 (a)
              6 FORMAT_VALUE             0
              8 RETURN_VALUE
None
 15           0 LOAD_CONST               1 ('{a}')
              2 LOAD_ATTR                0 (format)
              4 LOAD_CONST               2 ('test')
              6 LOAD_CONST               3 (('a',))
              8 CALL_FUNCTION_KW         1
             10 RETURN_VALUE
None

One can see that the f-string handles the formatting without attribute or function calls, which can impose type checking and memory overhead. According to timeit this results in a roughly 3x performance gain (for my specific functions)

>>> timeit.timeit('f1()', 'from __main__ import f1', number=100000)
0.012325852433775708
>>> timeit.timeit('f2()', 'from __main__ import f2', number=100000)
0.036395029920726074


问:
lines in a file with comma
I would like to know how to create a sub file with a number of commas, for example.

123,abc,qwe,ert

123,456,abc,qwe,fgh

I want to create a file .txt with the line that has 4 commas. (123,456,abc,qwe,fgh).

I tried with this.

awk -F\, '{print NF-1}'

But only gives me the number of commas that each line has.

答:
Replace all commas with commas and count the occurrences and compare:</p>

```<code>$ awk 'gsub(/,/,",")==4' file
123,456,abc,qwe,fgh
</code>```

Title: lines in a file with comma

Body:
Replace all commas with commas and count the occurrences and compare:

$ awk 'gsub(/,/,",")==4' file
123,456,abc,qwe,fgh


问:
Calling .NET lib function from VC++

I am developing a application which requires to invoke a class function which is present within the .NET dll.

Is it possible to invoke this function from VC++

Consider following snippet of code.

```<code>Class A
{
  public string DoSomeTask()
  {
     Some code
     return "return Value"
  }
}
</code>```

The above class is present in a .NET dll

I want to invoke a method DoSomeTask() from VC++

Thanks in advance,

Amit Shah

答: This blog post gives a good overview how this can be achieved (Reverse P/Invoke, COM, C++/CLI wrapper) and explains a pretty straightforward HowTo for C++/CLI wrapper (which I used).</p>

ContentLicense: CC BY-SA 2.5

Title: Calling .NET lib function from VC++

Body:
I am developing a application which requires to invoke a class function which is present within the .NET dll.

Is it possible to invoke this function from VC++

Consider following snippet of code.

Class A
{
  public string DoSomeTask()
  {
     Some code
     return "return Value"
  }
}

The above class is present in a .NET dll

I want to invoke a method DoSomeTask() from VC++

Thanks in advance,

Amit Shah


问:
Laravel 5.0 Undefined variable result
I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:

Routes

```<code>Route::get('/shopsales', 'shopsalescontroller@index');
</code>```

Controller

```<code>class shopsalescontroller extends Controller
</code>```

{

```<code> public function index()
{
    $storeNum = request('storeNum');

   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}
</code>```

}

shopsales view

```<code><section>
  <center><h1><STRONG>Query Data</STRONG></h1></center>
    <ul>
      @foreach ($result as $results)
        <li>Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
            Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}
        </li>
        <br>
      @endforeach
    </ul>

</section>
</code>```

I have used the exact code for the query that is working, struggling to understand why this is not.

答: Solved, though sorry for wasting your time, some of my views should of had a capital letter in them, fixed that cleared the view cache and now i have the queries. </p>

Title: Laravel 5.0 Undefined variable result

Body:
I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:

Routes

Route::get('/shopsales', 'shopsalescontroller@index');

Controller

class shopsalescontroller extends Controller

{

 public function index()
{
    $storeNum = request('storeNum');

   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}

}

shopsales view

Query Data

      @foreach ($result as $results)

Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
            Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}

      @endforeach

I have used the exact code for the query that is working, struggling to understand why this is not.


问:
Design a System to monitor web services
I want to know how to design a system that would monitor my web services status like CPU usage, whether the service is up or not. I searched it on internet but it shows me different tools. I want to design my own system. A very basic guidance will help me a lot.

答:
It depends how deep you want to go. In principle you need to store timeseries data, for example rrdtool can be used, then you need to collect a data based on some time interval and last but not least you should be able to present data, graphs for example.

Does it make sense to reinvent the wheel it is up to you, but for such problem there are open source systems based on rrdtool, like Cacti or Nagios.

Also influxdb with Graphana is powerfull in this respect, just to name a few.

Title: Design a System to monitor web services


问:
string to char conversion in ASP.net
I am getting extLogonName string for database, and depend upon the last char (number or alphabet) i need to change my logic.
 i am using length -1 to get last char

```<code>char last = extLogonName[extLogonName.Length-1];
</code>```

extLogonName is "moni.yewriwe2", but somehow last is returning me 50'2', i am only expecting 2.But now sure from where 50 is coming ?

After that i try to convert  char last = System.Convert.ToChar(last1);
it still showing me 50'2'.Actually i want to create login name, if same login name add number after it  Please find my complete logic.

```<code>  if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        extLogonName = (string)reader["logonname"];
                    }

                }
                   // char last = extLogonName[extLogonName.Length-1];
               // String NewString = Substring(oldString.Length - 1, 1);
                //String last = Substring(extLogonName.Length - 1, 1);
              string last1=  extLogonName.Substring(extLogonName.Length-1,1);

              char last = System.Convert.ToChar(last1);

              if ((last >= 'a' && last <= 'z'))
              {
                  int i = 2;
                  logonname = extLogonName + i.ToString();
              }

              if (last >= '2' && last <= '9')
              {

                 // char last2 = extLogonName[extLogonName.Length - 2];
                  string last3 = extLogonName.Substring(extLogonName.Length - 2, 1);
                  char last2 = System.Convert.ToChar(last3);
                  if (last2 >= '0' && last2 <= '9')
                  {
                      int number2 = (int)last2;

                      number2 = number2 + 1;
                      logonname = logonname + number2.ToString();
                  }

                int number = (int)last;
                 //Char number =System.Convert.ToInt32(last);

                  number = number + 1;
                  logonname = logonname + number.ToString();
              }
</code>```

so it create 'moni.yewriwe2' then 'moni.yewriwe51' and i want 'moni.yewriwe3'.

答: In the ASCII table, decimal 50 (hex 32) represents the character '2'.</p>

Title: string to char conversion in ASP.net

Body:
I am getting extLogonName string for database, and depend upon the last char (number or alphabet) i need to change my logic.
 i am using length -1 to get last char

char last = extLogonName[extLogonName.Length-1];

extLogonName is "moni.yewriwe2", but somehow last is returning me 50'2', i am only expecting 2.But now sure from where 50 is coming ?

After that i try to convert  char last = System.Convert.ToChar(last1);
it still showing me 50'2'.Actually i want to create login name, if same login name add number after it  Please find my complete logic.

  if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        extLogonName = (string)reader["logonname"];
                    }

                }
                   // char last = extLogonName[extLogonName.Length-1];
               // String NewString = Substring(oldString.Length - 1, 1);
                //String last = Substring(extLogonName.Length - 1, 1);
              string last1=  extLogonName.Substring(extLogonName.Length-1,1);

              char last = System.Convert.ToChar(last1);

              if ((last >= 'a' && last <= 'z'))
              {
                  int i = 2;
                  logonname = extLogonName + i.ToString();
              }

              if (last >= '2' && last <= '9')
              {

                 // char last2 = extLogonName[extLogonName.Length - 2];
                  string last3 = extLogonName.Substring(extLogonName.Length - 2, 1);
                  char last2 = System.Convert.ToChar(last3);
                  if (last2 >= '0' && last2 <= '9')
                  {
                      int number2 = (int)last2;

                      number2 = number2 + 1;
                      logonname = logonname + number2.ToString();
                  }

                int number = (int)last;
                 //Char number =System.Convert.ToInt32(last);

                  number = number + 1;
                  logonname = logonname + number.ToString();
              }

so it create 'moni.yewriwe2' then 'moni.yewriwe51' and i want 'moni.yewriwe3'.


问:
alert doesn't appear in localhost
The below code works fine in jsfiddle but when i run in the locahost, alert box doesn't appear while there is no error in the console too. What could be the reason. Can anyone help?

index.html

```<code><title>App</title>

<script type="text/javascript" src="movieList.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</code>```

movieList.js

```<code>$(document).ready(function(){
    alert('something');
});
</code>```

答: After a lot of tries, alert box appears as expected after i deleted all the browsing history. But i dont know what was the reason.</p>

Title: alert doesn't appear in localhost

Body:
The below code works fine in jsfiddle but when i run in the locahost, alert box doesn't appear while there is no error in the console too. What could be the reason. Can anyone help?

index.html

<title>App</title>

movieList.js

$(document).ready(function(){
    alert('something');
});


问:
Pause and resume downloads using Retrofit
I used this tutorial to implement downloading files in my app: https://www.learn2crack.com/2016/05/downloading-file-using-retrofit.html

The problem is that if internet speed is slow or if network fluctuates even for a second, the download is stopped permanently. Is there some way the app can detect that internet isn't active (connected but actually net isn't working), then pauses the download and resume when internet is fine.

Or some alternative so user doesn't get frustrated?

答:
I also faced this problem today and didn't find any good solutions which implemented at once download resumes, progress notifications and BufferedSink usage for fast nio operations.

This is how it could be done with Retrofit2 and RxJava2. Code is witten in Kotlin for Android, but it can be easily ported to pure JVM: just get rid from AndroidSchedulers

Code may contain bugs as it was written from scratch in short time and was barely tested.

import com.google.gson.GsonBuilder
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okio.Buffer
import okio.BufferedSink
import okio.ForwardingSource
import okio.Okio
import org.slf4j.LoggerFactory
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Streaming
import retrofit2.http.Url
import java.io.File
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
import java.util.regex.Pattern

class FileDownloader(val baseUrl: String) {

    private val log = LoggerFactory.getLogger(FileDownloader::class.java)

    private val expectedFileLength = ConcurrentHashMap<String, Long>()
    private val eTag = ConcurrentHashMap<String, String>()

    private val apiChecker: FileDownloaderAPI

    init {
        apiChecker = Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(OkHttpClient())
                .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
                .build()
                .create(FileDownloaderAPI::class.java)

    }

    /**
     *
     * @return File Observable
     */
    fun download(
            urlPath: String,
            file: File,
            dlProgressConsumer: Consumer<Int>): Observable<File> {
        return Observable.create(ObservableOnSubscribe<File> {
            val downloadObservable: Observable<Int>

            if (file.exists() &&
                    file.length() > 0L &&
                    file.length() != expectedFileLength[file.name]
                    ) {
                /**
                 * Try to get rest of the file according to:
                 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
                 */
                downloadObservable = apiChecker.downloadFile(
                        urlPath,
                        "bytes=${file.length()}-",
                        eTag[file.name] ?: "0"
                ).flatMap(
                        DownloadFunction(file, it)
                )
            } else {
                /**
                 * Last time file was fully downloaded or not present at all
                 */
                if (!file.exists())
                    eTag[file.name] = ""

                downloadObservable = apiChecker.downloadFile(
                        urlPath,
                        eTag[file.name] ?: "0"
                ).flatMap(
                        DownloadFunction(file, it)
                )

            }

            downloadObservable
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(dlProgressConsumer)

        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
    }

    private inner class DownloadFunction(
            val file: File,
            val fileEmitter: ObservableEmitter<File>
    ) : Function<Response<ResponseBody>, Observable<Int>> {

        var contentLength = 0L

        var startingByte = 0L
        var endingByte = 0L
        var totalBytes = 0L

        var contentRangePattern = "bytes ([0-9]*)-([0-9]*)/([0-9]*)"
        fun parseContentRange(contentRange: String) {
            val matcher = Pattern.compile(contentRangePattern).matcher(contentRange)
            if (matcher.find()) {
                startingByte = matcher.group(1).toLong()
                endingByte = matcher.group(2).toLong()
                totalBytes = matcher.group(3).toLong()
            }
        }

        var totalRead = 0L

        var lastPercentage = 0

        override fun apply(response: Response<ResponseBody>): Observable<Int> {
            return Observable.create { subscriber ->
                try {
                    if (!response.isSuccessful) {
                        /**
                         * Including response 304 Not Modified
                         */
                        fileEmitter.onError(IllegalStateException("Code: ${response.code()}, ${response.message()}; Response $response"))
                        return@create
                    }

                    contentLength = response.body().contentLength()

                    log.info("{}", response)
                    /**
                     * Receiving partial content, which in general means that download is resumed
                     */
                    if (response.code() == 206) {
                        parseContentRange(response.headers().get("Content-Range"))
                        log.debug("Getting range from {} to {} of {} bytes", startingByte, endingByte, totalBytes)
                    } else {
                        endingByte = contentLength
                        totalBytes = contentLength
                        if (file.exists())
                            file.delete()
                    }

                    log.info("Starting byte: {}, ending byte {}", startingByte, endingByte)

                    totalRead = startingByte

                    eTag.put(file.name, response.headers().get("ETag"))
                    expectedFileLength.put(file.name, totalBytes)

                    val sink: BufferedSink
                    if (startingByte > 0) {
                        sink = Okio.buffer(Okio.appendingSink(file))
                    } else {
                        sink = Okio.buffer(Okio.sink(file))
                    }

                    sink.use {
                        it.writeAll(object : ForwardingSource(response.body().source()) {

                            override fun read(sink: Buffer, byteCount: Long): Long {
                                val bytesRead = super.read(sink, byteCount)

                                totalRead += bytesRead

                                /**
                                 * May not wok good if we get some shit from the middle of the file,
                                 * though that's not the case of this function, as we plan only to
                                 * resume downloads
                                 */
                                val currentPercentage = (totalRead * 100 / totalBytes).toInt()
                                if (currentPercentage > lastPercentage) {
                                    val progress = "$currentPercentage%"
                                    lastPercentage = currentPercentage
                                    subscriber.onNext(currentPercentage)
                                    log.debug("Downloading {} progress: {}", file.name, progress)
                                }
                                return bytesRead
                            }
                        })
                    }

                    subscriber.onComplete()
                    fileEmitter.onNext(file)
                    fileEmitter.onComplete()
                } catch (e: IOException) {
                    log.error("Last percentage: {}, Bytes read: {}", lastPercentage, totalRead)
                    fileEmitter.onError(e)
                }
            }
        }

    }

    interface FileDownloaderAPI {

        @Streaming @GET
        fun downloadFile(
                @Url fileUrl: String,
                @Header("If-None-Match") eTag: String
        ): Observable<Response<ResponseBody>>

        @Streaming @GET
        fun downloadFile(
                @Url fileUrl: String,

                // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
                @Header("Range") bytesRange: String,

                // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.27
                @Header("If-Range") eTag: String
        ): Observable<Response<ResponseBody>>
    }
}
```

<p>And then use it where you want</p>

```    val fileDownloader = FileDownloader("http://wwww.example.com")
    fileDownloader.download(
            "/huge-video.mkv",
            File("file-where-I-will-save-this-video.mkv"),
            Consumer { progress ->
                updateProgressNotificatuin()
            }
    ).subscribe({
        log.info("File saved at path {}", it.absolutePath)
    },{
        log.error("Download error {}", it.message, it)
    },{
        log.info("Download completed")
    })
```

<p>Dependencies used in this sample:</p>

```dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:1.1.1"
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.2.0'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
    compile 'com.google.code.gson:gson:2.7'

    compile 'org.slf4j:slf4j-api:1.7.25'
}
```

Body:
I also faced this problem today and didn't find any good solutions which implemented at once download resumes, progress notifications and BufferedSink usage for fast nio operations.

This is how it could be done with Retrofit2 and RxJava2. Code is witten in Kotlin for Android, but it can be easily ported to pure JVM: just get rid from AndroidSchedulers

Code may contain bugs as it was written from scratch in short time and was barely tested.

import com.google.gson.GsonBuilder
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okio.Buffer
import okio.BufferedSink
import okio.ForwardingSource
import okio.Okio
import org.slf4j.LoggerFactory
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Streaming
import retrofit2.http.Url
import java.io.File
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
import java.util.regex.Pattern

class FileDownloader(val baseUrl: String) {

    private val log = LoggerFactory.getLogger(FileDownloader::class.java)

    private val expectedFileLength = ConcurrentHashMap<String, Long>()
    private val eTag = ConcurrentHashMap<String, String>()

    private val apiChecker: FileDownloaderAPI

    init {
        apiChecker = Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(OkHttpClient())
                .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
                .build()
                .create(FileDownloaderAPI::class.java)

    }

    /**
     *
     * @return File Observable
     */
    fun download(
            urlPath: String,
            file: File,
            dlProgressConsumer: Consumer<Int>): Observable<File> {
        return Observable.create(ObservableOnSubscribe<File> {
            val downloadObservable: Observable<Int>

            if (file.exists() &&
                    file.length() > 0L &&
                    file.length() != expectedFileLength[file.name]
                    ) {
                /**
                 * Try to get rest of the file according to:
                 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
                 */
                downloadObservable = apiChecker.downloadFile(
                        urlPath,
                        "bytes=${file.length()}-",
                        eTag[file.name] ?: "0"
                ).flatMap(
                        DownloadFunction(file, it)
                )
            } else {
                /**
                 * Last time file was fully downloaded or not present at all
                 */
                if (!file.exists())
                    eTag[file.name] = ""

                downloadObservable = apiChecker.downloadFile(
                        urlPath,
                        eTag[file.name] ?: "0"
                ).flatMap(
                        DownloadFunction(file, it)
                )

            }

            downloadObservable
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(dlProgressConsumer)

        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
    }

    private inner class DownloadFunction(
            val file: File,
            val fileEmitter: ObservableEmitter<File>
    ) : Function<Response<ResponseBody>, Observable<Int>> {

        var contentLength = 0L

        var startingByte = 0L
        var endingByte = 0L
        var totalBytes = 0L

        var contentRangePattern = "bytes ([0-9]*)-([0-9]*)/([0-9]*)"
        fun parseContentRange(contentRange: String) {
            val matcher = Pattern.compile(contentRangePattern).matcher(contentRange)
            if (matcher.find()) {
                startingByte = matcher.group(1).toLong()
                endingByte = matcher.group(2).toLong()
                totalBytes = matcher.group(3).toLong()
            }
        }

        var totalRead = 0L

        var lastPercentage = 0

        override fun apply(response: Response<ResponseBody>): Observable<Int> {
            return Observable.create { subscriber ->
                try {
                    if (!response.isSuccessful) {
                        /**
                         * Including response 304 Not Modified
                         */
                        fileEmitter.onError(IllegalStateException("Code: ${response.code()}, ${response.message()}; Response $response"))
                        return@create
                    }

                    contentLength = response.body().contentLength()

                    log.info("{}", response)
                    /**
                     * Receiving partial content, which in general means that download is resumed
                     */
                    if (response.code() == 206) {
                        parseContentRange(response.headers().get("Content-Range"))
                        log.debug("Getting range from {} to {} of {} bytes", startingByte, endingByte, totalBytes)
                    } else {
                        endingByte = contentLength
                        totalBytes = contentLength
                        if (file.exists())
                            file.delete()
                    }

                    log.info("Starting byte: {}, ending byte {}", startingByte, endingByte)

                    totalRead = startingByte

                    eTag.put(file.name, response.headers().get("ETag"))
                    expectedFileLength.put(file.name, totalBytes)

                    val sink: BufferedSink
                    if (startingByte > 0) {
                        sink = Okio.buffer(Okio.appendingSink(file))
                    } else {
                        sink = Okio.buffer(Okio.sink(file))
                    }

                    sink.use {
                        it.writeAll(object : ForwardingSource(response.body().source()) {

                            override fun read(sink: Buffer, byteCount: Long): Long {
                                val bytesRead = super.read(sink, byteCount)

                                totalRead += bytesRead

                                /**
                                 * May not wok good if we get some shit from the middle of the file,
                                 * though that's not the case of this function, as we plan only to
                                 * resume downloads
                                 */
                                val currentPercentage = (totalRead * 100 / totalBytes).toInt()
                                if (currentPercentage > lastPercentage) {
                                    val progress = "$currentPercentage%"
                                    lastPercentage = currentPercentage
                                    subscriber.onNext(currentPercentage)
                                    log.debug("Downloading {} progress: {}", file.name, progress)
                                }
                                return bytesRead
                            }
                        })
                    }

                    subscriber.onComplete()
                    fileEmitter.onNext(file)
                    fileEmitter.onComplete()
                } catch (e: IOException) {
                    log.error("Last percentage: {}, Bytes read: {}", lastPercentage, totalRead)
                    fileEmitter.onError(e)
                }
            }
        }

    }

    interface FileDownloaderAPI {

        @Streaming @GET
        fun downloadFile(
                @Url fileUrl: String,
                @Header("If-None-Match") eTag: String
        ): Observable<Response<ResponseBody>>

        @Streaming @GET
        fun downloadFile(
                @Url fileUrl: String,

                // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
                @Header("Range") bytesRange: String,

                // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.27
                @Header("If-Range") eTag: String
        ): Observable<Response<ResponseBody>>
    }
}

And then use it where you want

    val fileDownloader = FileDownloader("http://wwww.example.com")
    fileDownloader.download(
            "/huge-video.mkv",
            File("file-where-I-will-save-this-video.mkv"),
            Consumer { progress ->
                updateProgressNotificatuin()
            }
    ).subscribe({
        log.info("File saved at path {}", it.absolutePath)
    },{
        log.error("Download error {}", it.message, it)
    },{
        log.info("Download completed")
    })

Dependencies used in this sample:

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:1.1.1"
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.2.0'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
    compile 'com.google.code.gson:gson:2.7'

    compile 'org.slf4j:slf4j-api:1.7.25'
}


问:
Android: Displaying contact names in a Spinner
I'm trying to simply get contacts from the Device phone book and display them on a Spinner, the code:

```<code>    // Form an array specifying which columns to return.
    String[] PROJECTION = new String[] {
        People._ID, People.NAME
    };

    // Get the base URI for the People table in the Contacts content provider.
    Uri contacts =  People.CONTENT_URI;

    Spinner contactsSpinner = (Spinner) findViewById(R.id.recipient_names);

    // Make the query.
    Cursor contactsCursor = managedQuery(contacts,
                             PROJECTION, // Which columns to return
                             null,       // Which rows to return (all rows)
                             null,       // Selection arguments (none)
                             // Put the results in ascending order by name
                             People.NAME + " ASC");

    Log.e("EE", String.valueOf(contactsCursor.getCount()));

    SimpleCursorAdapter sca = new SimpleCursorAdapter(
        this, android.R.layout.simple_spinner_item,
        contactsCursor, new String[] {People.NAME}, new int[] {android.R.id.text1}
    );

    Log.e("EE", String.valueOf(sca.getCount()));

    sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    contactsSpinner.setAdapter(sca);
</code>```

Compiles and runs fine, just that... The logs is showing 1 for both Log.e() call, which I think imply that contacts were actually retrieved successfully, however the Spinner is empty... Could anyone tell me I am doing wrong?

答: Turns out that it's not supported on sdk > 2.0 </p>

Body:
I'm trying to simply get contacts from the Device phone book and display them on a Spinner, the code:

    // Form an array specifying which columns to return.
    String[] PROJECTION = new String[] {
        People._ID, People.NAME
    };

    // Get the base URI for the People table in the Contacts content provider.
    Uri contacts =  People.CONTENT_URI;

    Spinner contactsSpinner = (Spinner) findViewById(R.id.recipient_names);

    // Make the query.
    Cursor contactsCursor = managedQuery(contacts,
                             PROJECTION, // Which columns to return
                             null,       // Which rows to return (all rows)
                             null,       // Selection arguments (none)
                             // Put the results in ascending order by name
                             People.NAME + " ASC");

    Log.e("EE", String.valueOf(contactsCursor.getCount()));

    SimpleCursorAdapter sca = new SimpleCursorAdapter(
        this, android.R.layout.simple_spinner_item,
        contactsCursor, new String[] {People.NAME}, new int[] {android.R.id.text1}
    );

    Log.e("EE", String.valueOf(sca.getCount()));

    sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    contactsSpinner.setAdapter(sca);

Compiles and runs fine, just that... The logs is showing 1 for both Log.e() call, which I think imply that contacts were actually retrieved successfully, however the Spinner is empty... Could anyone tell me I am doing wrong?


问:
Delete a record from a file using python
I'm creating a very basic banking record program in python 3.6. I created a file "accounts.txt" in which users can add their accounts -- name, account number, balance. After they add, the file looks something like this:

213123                    |dgfdg                     |21312.0

123124                    |vxcvx                     |213123.0

123123                    |sfsdf                     |123123.0

column represents account no., name, balance respectively.

I want to delete a particular record from this file. I take account no. as input of the record to be deleted. I just can't figure how to do it.  Ex- if the user enters 213123, the entire record should be deleted.

A separate problem in the same case- when I ask the user to input their account number, name, balance, i want to scan "accounts.txt" and if the account number already exists, produce an error instead of creating a new record. Avoid duplicate account numbers.

I'm new to python and this is a basic program so please don't suggest using mysql or mariadb. :D

```<code>def account_set():
    accno = int(input("Enter Account Number \t"))
    name = str(input("Enter Name \t"))
    balance = float(input("Enter Balance \t"))
    return accno, name, balance

def new():
    account = open("accounts.txt", "a+")
    info = account_set()
    account.seek(0, 2)
    for items in info:
        account.write("{0:<25} {1}".format(items, "|"))
    account.write("\n")
    account.close()

def delete():
    accno = (input("Enter Account number to delete"))
    file = open("accounts.txt", "r+")

print("""
Please choose any one of the Following Options: \n \n
1. New Account \n
2. Delete Account \n
3. Exit
""")

x = True
while x:
    user_input = int(input("Enter an option \t"))
    if user_input == 1:
        new()
    elif user_input == 2:
        delete()
    elif user_input == 3:
        print("Thank you for banking with us.")
        x = False
    else:
        print("Invalid Choice")
</code>```

答:
A possible way to do this is to ask the user for input and see what number it is. If the number is 213123, then you can use this code:

```<code>filename.seek(0)
filename.truncate()
</code>```

The code above will delete the entire file.

This SO post explains how to delete single lines perfectly: Deleting a specific line in a file (python)

To see if an account number exists, you can read the file like this:

```<code> f = open("filename.txt").readlines()
 f = [i.strip('\n') for i in f]
 file = [map(int, i.split()) for i in f]
 #then, you can loop through file and see if the account number exists:
 #account numbers are first in the list, so you can make a list of them
 account_numbers = [i[0] for i in file]
 number = 123456
 if number in account_numbers:
     print "account number ", number, " all ready exists"

 else:
     print "account number", number, " does not exist"
</code>```

Body:
I'm creating a very basic banking record program in python 3.6. I created a file "accounts.txt" in which users can add their accounts -- name, account number, balance. After they add, the file looks something like this:

213123                    |dgfdg                     |21312.0

123124                    |vxcvx                     |213123.0

123123                    |sfsdf                     |123123.0

column represents account no., name, balance respectively.

I want to delete a particular record from this file. I take account no. as input of the record to be deleted. I just can't figure how to do it.  Ex- if the user enters 213123, the entire record should be deleted.

A separate problem in the same case- when I ask the user to input their account number, name, balance, i want to scan "accounts.txt" and if the account number already exists, produce an error instead of creating a new record. Avoid duplicate account numbers.

I'm new to python and this is a basic program so please don't suggest using mysql or mariadb. :D

def account_set():
    accno = int(input("Enter Account Number \t"))
    name = str(input("Enter Name \t"))
    balance = float(input("Enter Balance \t"))
    return accno, name, balance

def new():
    account = open("accounts.txt", "a+")
    info = account_set()
    account.seek(0, 2)
    for items in info:
        account.write("{0:<25} {1}".format(items, "|"))
    account.write("\n")
    account.close()

def delete():
    accno = (input("Enter Account number to delete"))
    file = open("accounts.txt", "r+")

print("""
Please choose any one of the Following Options: \n \n
1. New Account \n
2. Delete Account \n
3. Exit
""")

x = True
while x:
    user_input = int(input("Enter an option \t"))
    if user_input == 1:
        new()
    elif user_input == 2:
        delete()
    elif user_input == 3:
        print("Thank you for banking with us.")
        x = False
    else:
        print("Invalid Choice")

Body:
A possible way to do this is to ask the user for input and see what number it is. If the number is 213123, then you can use this code:

filename.seek(0)
filename.truncate()

The code above will delete the entire file.

This SO post explains how to delete single lines perfectly: Deleting a specific line in a file (python)

To see if an account number exists, you can read the file like this:

 f = open("filename.txt").readlines()
 f = [i.strip('\n') for i in f]
 file = [map(int, i.split()) for i in f]
 #then, you can loop through file and see if the account number exists:
 #account numbers are first in the list, so you can make a list of them
 account_numbers = [i[0] for i in file]
 number = 123456
 if number in account_numbers:
     print "account number ", number, " all ready exists"

 else:
     print "account number", number, " does not exist"


问:
Can I stop an IIS?
In a .NET windows application to to modify a remote machine config file that is used by an ASP.NET application. However, I keep getting the error:

System.IO.IOException: The process cannot access the file '[file name]' because it is being used by another process.

Now, this may not be the problem, but I'm figuring that if I can stop the IIS, then I can modify the machine config file (without getting the exception), and then I can restart the IIS using this code:

```<code> Process proc = new Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.StartInfo.FileName = "iisreset";
            proc.StartInfo.Arguments = serverName;
            try
            {
                proc.Start();
                proc.WaitForExit();
                ...
</code>```

1) Is there a way to stop the IIS without restarting it, and 2) Doe this approach to changing the server.config file even make sense?

(note, I am modifying the file with regular expressions search and replace; is this a problem?)

答:
```<code>Using System.Diagnostics;

//to stop ISS
ProcessStartInfo startInfo = new ProcessStartInfo("iisreset.exe", " /stop");
System.Diagnostics.Process.Start(startInfo);

//to start ISS
ProcessStartInfo stopInfo = new ProcessStartInfo("iisreset.exe", " /start");
System.Diagnostics.Process.Start(stopInfo);
</code>```

Title: Can I stop an IIS?

Body:
In a .NET windows application to to modify a remote machine config file that is used by an ASP.NET application. However, I keep getting the error:

System.IO.IOException: The process cannot access the file '[file name]' because it is being used by another process.

Now, this may not be the problem, but I'm figuring that if I can stop the IIS, then I can modify the machine config file (without getting the exception), and then I can restart the IIS using this code:

 Process proc = new Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.StartInfo.FileName = "iisreset";
            proc.StartInfo.Arguments = serverName;
            try
            {
                proc.Start();
                proc.WaitForExit();
                ...

1) Is there a way to stop the IIS without restarting it, and 2) Doe this approach to changing the server.config file even make sense?

(note, I am modifying the file with regular expressions search and replace; is this a problem?)


问:
Xtext , Defining a Structure for a plot
i have to make a type curve that is a curve plot , the data is given by a CSV file (The interpreter is who read the data file). i have two type of values , x-axis, time (i think INT:INT) minutes:seconds format ; and y-axis voltage ( double ) . My grammar datatypes are the following :

```<code>Model:
elements+=Element*;

Element:
     DataType /* | Operation | Control*/ ;

DataType :
     Text | Real
;
Text:
    ("String" | "Text") name=ID (value=STRING)?
;
Double returns ecore::EDouble:
     INT ('.' INT)?
;
Real:
     ("Double" | "Real") name=ID (value=Double)?
;
</code>```

I was traying to make a map in my grammar with this format : Curve(Double voltage,time INT:INT) but i dont know why it doesnt work . what do you think guys ? should i define a new type for the type time ? or how make the map properly? Thanks for your time

```<code>   CurveCollection :
        'Curve['keys+=[Real]*','values+=Time*']'
;
 Time:
     INT':'INT
 ;
</code>```

I tried to define the structure , but i dont know if is going to work like to arrays of (keys , values ) like a Map in java

答:
you can enable a default unique name validation by uncommenting in and rerunning the language workflow

```<code>validator = {
    composedCheck = "org.eclipse.xtext.validation.NamesAreUniqueValidator"
}
</code>```

alternatively you can implement a own unique name validation in <YourDsl>Validator

Title: Xtext , Defining a Structure for a plot

Body:
i have to make a type curve that is a curve plot , the data is given by a CSV file (The interpreter is who read the data file). i have two type of values , x-axis, time (i think INT:INT) minutes:seconds format ; and y-axis voltage ( double ) . My grammar datatypes are the following :

Model:
elements+=Element*;

Element:
     DataType /* | Operation | Control*/ ;

DataType :
     Text | Real
;
Text:
    ("String" | "Text") name=ID (value=STRING)?
;
Double returns ecore::EDouble:
     INT ('.' INT)?
;
Real:
     ("Double" | "Real") name=ID (value=Double)?
;

I was traying to make a map in my grammar with this format : Curve(Double voltage,time INT:INT) but i dont know why it doesnt work . what do you think guys ? should i define a new type for the type time ? or how make the map properly? Thanks for your time

   CurveCollection :
        'Curve['keys+=[Real]*','values+=Time*']'
;
 Time:
     INT':'INT
 ;

I tried to define the structure , but i dont know if is going to work like to arrays of (keys , values ) like a Map in java

Body:
you can enable a default unique name validation by uncommenting in and rerunning the language workflow

validator = {
    composedCheck = "org.eclipse.xtext.validation.NamesAreUniqueValidator"
}

alternatively you can implement a own unique name validation in <YourDsl>Validator


问:
C++11 get current date and time as string
What is the state of the art way to get date and time as string in c++11?

I know about std::put_time, but the reference says I shall use it only in streams.

There is std::chrono::system_clock which provides to_time_t returning the time as time_t and lacking the date, doesn't it?

I could use a stringstream like bames53: Outputting Date and Time in C++ using std::chrono but that seems to be a workaround.

答:
Using Howard Hinnant's free, open-source header-only datetime library, you can get the current UTC time as a std::string in a single line of code:

```<code>std::string s = date::format("%F %T", std::chrono::system_clock::now());
</code>```

I just ran this, and the string contains:

```<code>2017-03-30 17:05:13.400455
</code>```

That's right, it even gives you the full precision.  If you don't like that format, all of the strftime formatting flags are available.  If you want your local time, there is a timezone library also available, though it is not header only.

```<code>std::string s = date::format("%F %T %Z", date::make_zoned(date::current_zone(),
                                         std::chrono::system_clock::now()));
</code>```

Output:

```<code>2017-03-30 13:05:13.400455 EDT
</code>```

Body:
Using Howard Hinnant's free, open-source header-only datetime library, you can get the current UTC time as a std::string in a single line of code:

std::string s = date::format("%F %T", std::chrono::system_clock::now());

I just ran this, and the string contains:

2017-03-30 17:05:13.400455

That's right, it even gives you the full precision.  If you don't like that format, all of the strftime formatting flags are available.  If you want your local time, there is a timezone library also available, though it is not header only.

std::string s = date::format("%F %T %Z", date::make_zoned(date::current_zone(),
                                         std::chrono::system_clock::now()));

Output:

2017-03-30 13:05:13.400455 EDT


问:
How to truncate seconds in TSQL?
I have time, select cast(SYSDATETIME() AS time)
14:59:09.2834595

What is the way to truncate seconds?
14:59

答:
If you want to truncate seconds and still have a T-SQL Date datatype, first convert the date into minutes from the date '0' and then add the minutes back to '0'. This answer doesn't require any additional parsing/converting. This method works to truncate other parts just change MINUTE.
Example:
SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, 0, '2016-01-01 23:22:56.997'), 0)

Title: How to truncate seconds in TSQL?


问:
Color of the lines
I'm writing an app for Android, what works with rhythms. I've tried to make two lines where the app draws the original rate of the rhythm and the other draws what you've hit back.

It's working fine until I try to color the indicator lines of the players try.

```<code>for (int i = 0; i < gameosszido.size()-1; i++)
    {
        if (i == 0)
        {
            paint.setColor(Color.GREEN);
            startx = 0;
            starty = 0;
            endx = startx;
            endy = 50;
            canvas.drawLine(startx, starty, endx, endy, paint);
        }
        else
        {
line 433     if ((gameTimes.get(i-1) < hezagTimes.get(i-1)*1.25 && gameTimes.get(i-1) > hezagTimes.get(i-1)*0.85))
            {
                paint.setColor(Color.GREEN);
            }
            else if (gameTimes.get(i-1) < hezagTimes.get(i-1)*1.45 && gameTimes.get(i-1) > hezagTimes.get(i-1)*0.55)
            {
                paint.setColor(Color.YELLOW);
            }
            else
            {
                paint.setColor(Color.RED);
            }
            double d = (double)gameosszido.get(i);
            double c = (double)gameosszido.get(gameosszido.size()-2);
            startx = (int) (1050*(d/c));
            starty = 0;
            endx = startx;
            endy = 50;
            canvas.drawLine(startx, starty, endx, endy, paint);
        }
    }
</code>```

It gives the following error:

```<code>    E/AndroidRuntime: FATAL EXCEPTION: main Process: hu.qnszt.rhythmapp,  PID: 2646 java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
at java.util.ArrayList.get(ArrayList.java:411)
at u.qnszt.rhythmapp.GameActivity.drawLineHit(GameActivity.java:433)
at hu.qnszt.rhythmapp.GameActivity.VerifyGame(GameActivity.java:194)
at hu.qnszt.rhythmapp.GameActivity$3.onClick(GameActivity.java:134)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

答: Probably the problem is that one of your ArrayList gameTimes or hezagTimes does´t have the correct Size, to fix this you need to make the size of this 2 ArrayList at least gameosszido.size()-1. As this is the last position that you will access. If you complete your code with the whole class I could help more, but that my guess.

Title: Color of the lines

Body:
I'm writing an app for Android, what works with rhythms. I've tried to make two lines where the app draws the original rate of the rhythm and the other draws what you've hit back.

It's working fine until I try to color the indicator lines of the players try.

for (int i = 0; i < gameosszido.size()-1; i++)
    {
        if (i == 0)
        {
            paint.setColor(Color.GREEN);
            startx = 0;
            starty = 0;
            endx = startx;
            endy = 50;
            canvas.drawLine(startx, starty, endx, endy, paint);
        }
        else
        {
line 433     if ((gameTimes.get(i-1) < hezagTimes.get(i-1)*1.25 && gameTimes.get(i-1) > hezagTimes.get(i-1)*0.85))
            {
                paint.setColor(Color.GREEN);
            }
            else if (gameTimes.get(i-1) < hezagTimes.get(i-1)*1.45 && gameTimes.get(i-1) > hezagTimes.get(i-1)*0.55)
            {
                paint.setColor(Color.YELLOW);
            }
            else
            {
                paint.setColor(Color.RED);
            }
            double d = (double)gameosszido.get(i);
            double c = (double)gameosszido.get(gameosszido.size()-2);
            startx = (int) (1050*(d/c));
            starty = 0;
            endx = startx;
            endy = 50;
            canvas.drawLine(startx, starty, endx, endy, paint);
        }
    }

It gives the following error:

    E/AndroidRuntime: FATAL EXCEPTION: main Process: hu.qnszt.rhythmapp,  PID: 2646 java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
at java.util.ArrayList.get(ArrayList.java:411)
at u.qnszt.rhythmapp.GameActivity.drawLineHit(GameActivity.java:433)
at hu.qnszt.rhythmapp.GameActivity.VerifyGame(GameActivity.java:194)
at hu.qnszt.rhythmapp.GameActivity$3.onClick(GameActivity.java:134)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)


问:
how to save arraylist<object> after app is closed
how to save arraylist after the app is closed.
This is my global class

```<code>public class GlobalClass extends Application {

ArrayList<Trip> allTrips = new ArrayList<>();

public ArrayList<String> allTripsString() {
    ArrayList<String> allTripsString = new ArrayList<String>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getName());
    }
    return allTripsString;
    }
}
</code>```

This is my trip class

```<code>public class Trip {

/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;

private String name;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public double budget = 0;

/** An item in the expanses list */
static class Item {
    final String name;
    final double cost;
    final String Category;
    public Item(String name, double cost, String Category) {
        this.name = name;
        this.cost = cost;
        this.Category = Category;
    }
    @Override public String toString() {
        return this.name + " (" + this.cost + "$)";
    }
    public String getName(){
        return name;
    }
    public String getCategory(){
        return Category;
    }
    public double getCost(){
        return cost;
    }
}

public Trip(String name) {
    this.name = name;
    this.expanses = new HashMap<String,List<Item>>();
    for (String cat: ExpensesCategory) { // init the categories with empty lists
        this.expanses.put(cat, new ArrayList<Item>());
    }
}

public String getName(){
    return name;
}

/** Register a new expanse to the trip. */
public void add(String item, double cost, String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        throw new IllegalArgumentException("Category '"+category+"' does not exist.");
    list.add( new Item(item, cost, category) );
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing the category elements, or null if the category does not exists
 */
public List<Item> getItems(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return null;
    return new ArrayList<Item>(list);
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing all the elements
 */
public List<Item> getItems() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    return list;
}

public ArrayList<String> getItemsString() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getName());
    }
    return listString;
}

public ArrayList<Double> getItemsCost(){
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Item item : list){
        listDouble.add(item.getCost());
    }
    return listDouble;
}

public ArrayList<String> getItemsCategory() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getCategory());
    }
    return listString;
}

/** Get the total cost, given a category. */
public double getCost(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return -1;
    double cost = 0;
    for (Item item: list)
        cost += item.cost;
    return cost;
}

/** Get the total cost. */
public double getCost() {
    double cost = 0;
    for (List<Item> l: this.expanses.values())
        for (Item item: l)
            cost += item.cost;
    cost *= 1000;
    cost = (int)(cost);
    cost /= 1000;
    return cost;
    }
}
</code>```

I want to save the array list and when I close and open the app the array list (alltrips) is saved. How to do this?

I want to use shared preferences but I don't know how to do this because it is not a string it array list with Trip. Can anyone help me to save the arraylist in shared preferences?

答:
You can save serialized object and read them by using those methods :

```<code>public static boolean writeObjectInCache(Context context, String key, Object object) {
    try {
        FileOutputStream fos = context.openFileOutput(key, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(object);
        oos.close();
        fos.close();
    } catch (IOException ex) {
        return false;
    }

    return true;
}

public static Object readObjectFromCache(Context context, String key) {
    try {
        FileInputStream fis = context.openFileInput(key);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object object = ois.readObject();
        return object;
    } catch (Exception ex) {
        return null;
    }
}
</code>```

To read the list , you should cast the Object by your type :

```<code>  ArrayList<TypeOfYourObject> list = new ArrayList<>();
        list = (ArrayList<TypeOfYourObject>) readObjectFromCache(context, CACHE_KEY);
</code>```

Don't forget to add those permission in your manifest :

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

Body:
how to save arraylist after the app is closed.
This is my global class

public class GlobalClass extends Application {

ArrayList<Trip> allTrips = new ArrayList<>();

public ArrayList<String> allTripsString() {
    ArrayList<String> allTripsString = new ArrayList<String>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getName());
    }
    return allTripsString;
    }
}

This is my trip class

public class Trip {

/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;

private String name;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public double budget = 0;

/** An item in the expanses list */
static class Item {
    final String name;
    final double cost;
    final String Category;
    public Item(String name, double cost, String Category) {
        this.name = name;
        this.cost = cost;
        this.Category = Category;
    }
    @Override public String toString() {
        return this.name + " (" + this.cost + "$)";
    }
    public String getName(){
        return name;
    }
    public String getCategory(){
        return Category;
    }
    public double getCost(){
        return cost;
    }
}

public Trip(String name) {
    this.name = name;
    this.expanses = new HashMap<String,List<Item>>();
    for (String cat: ExpensesCategory) { // init the categories with empty lists
        this.expanses.put(cat, new ArrayList<Item>());
    }
}

public String getName(){
    return name;
}

/** Register a new expanse to the trip. */
public void add(String item, double cost, String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        throw new IllegalArgumentException("Category '"+category+"' does not exist.");
    list.add( new Item(item, cost, category) );
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing the category elements, or null if the category does not exists
 */
public List<Item> getItems(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return null;
    return new ArrayList<Item>(list);
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing all the elements
 */
public List<Item> getItems() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    return list;
}

public ArrayList<String> getItemsString() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getName());
    }
    return listString;
}

public ArrayList<Double> getItemsCost(){
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Item item : list){
        listDouble.add(item.getCost());
    }
    return listDouble;
}

public ArrayList<String> getItemsCategory() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getCategory());
    }
    return listString;
}

/** Get the total cost, given a category. */
public double getCost(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return -1;
    double cost = 0;
    for (Item item: list)
        cost += item.cost;
    return cost;
}

/** Get the total cost. */
public double getCost() {
    double cost = 0;
    for (List<Item> l: this.expanses.values())
        for (Item item: l)
            cost += item.cost;
    cost *= 1000;
    cost = (int)(cost);
    cost /= 1000;
    return cost;
    }
}

I want to save the array list and when I close and open the app the array list (alltrips) is saved. How to do this?

I want to use shared preferences but I don't know how to do this because it is not a string it array list with Trip. Can anyone help me to save the arraylist in shared preferences?

Body:
You can save serialized object and read them by using those methods :

public static boolean writeObjectInCache(Context context, String key, Object object) {
    try {
        FileOutputStream fos = context.openFileOutput(key, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(object);
        oos.close();
        fos.close();
    } catch (IOException ex) {
        return false;
    }

    return true;
}

public static Object readObjectFromCache(Context context, String key) {
    try {
        FileInputStream fis = context.openFileInput(key);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object object = ois.readObject();
        return object;
    } catch (Exception ex) {
        return null;
    }
}

To read the list , you should cast the Object by your type :

  ArrayList<TypeOfYourObject> list = new ArrayList<>();
        list = (ArrayList<TypeOfYourObject>) readObjectFromCache(context, CACHE_KEY);

Don't forget to add those permission in your manifest :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


问:
Getting a prev/next | first/last button to work with list.js
I am building a paginated index with search. I have the index paginated and working, however I want to add a prev/next and a first/last button because this has to be scalable.

List.JS does not seem to have one of these out of the box, so I tried to do it by appending/prepending the lis into the pagination div ul. This does work, except for after click they are removed.

Adding into pagination div

```<code>$('.pagination').prepend('<li class="btn-next"> 9 </li>');

$('.pagination').append('<li class="btn-prev"> 0 </li>');
</code>```

Functions to run the buttons

```<code>$('.btn-next').on('click', function(){
    var list = $('.pagination').find('li');
    $.each(list, function(position, element){
        if($(element).is('.active')){
            $(list[position+1]).trigger('click');
        }
    })

})

$('.btn-prev').on('click', function(){
    var list = $('.pagination').find('li');
    $.each(list, function(position, element){
        if($(element).is('.active')){
            $(list[position-1]).trigger('click');
        }
    })
</code>```

After this, Im not sure how I can even get them to stay appended since it seems to rewrite it on click every time. Has anyone else created these buttons using List.JS?

Here is my fiddle.

答:
The problem is the plugin reloads the html every time you change the page, one option to avoid modify the plugin will be create an extra container and style your elements to be next other.

The HTML will be like:

```<code><div class="nav">
  <ul class="pagination">
  </ul>
</div>
</code>```

And then append your buttons:

```<code>$('.nav').append('<div class="btn-next"> > </div><div class="btn-last"> >> </div>');
$('.nav').prepend('<div class="btn-first"> << </div><div class="btn-prev"> < </div>');
</code>```

Updated Fiddle

Still searching how to trigger first and last page

For First and Last elements use the show() function:

```<code>$('.btn-first').on('click', function(){
    monkeyList.show(1,1)
})
$('.btn-last').on('click', function(){
    monkeyList.show(monkeyList.size(),1)
})
</code>```

Updated Fiddle 2

Body:
I am building a paginated index with search. I have the index paginated and working, however I want to add a prev/next and a first/last button because this has to be scalable.

List.JS does not seem to have one of these out of the box, so I tried to do it by appending/prepending the lis into the pagination div ul. This does work, except for after click they are removed.

Adding into pagination div

$('.pagination').prepend('
 9
');

$('.pagination').append('
 0
');

Functions to run the buttons

$('.btn-next').on('click', function(){
    var list = $('.pagination').find('li');
    $.each(list, function(position, element){
        if($(element).is('.active')){
            $(list[position+1]).trigger('click');
        }
    })

})

$('.btn-prev').on('click', function(){
    var list = $('.pagination').find('li');
    $.each(list, function(position, element){
        if($(element).is('.active')){
            $(list[position-1]).trigger('click');
        }
    })

After this, Im not sure how I can even get them to stay appended since it seems to rewrite it on click every time. Has anyone else created these buttons using List.JS?

Here is my fiddle.

Body:
The problem is the plugin reloads the html every time you change the page, one option to avoid modify the plugin will be create an extra container and style your elements to be next other.

The HTML will be like:

<div class="nav">
  <ul class="pagination">
  </ul>
</div>

And then append your buttons:

$('.nav').append('<div class="btn-next"> > </div><div class="btn-last"> >> </div>');
$('.nav').prepend('<div class="btn-first"> << </div><div class="btn-prev"> < </div>');

Updated Fiddle

Still searching how to trigger first and last page

For First and Last elements use the show() function:

$('.btn-first').on('click', function(){
    monkeyList.show(1,1)
})
$('.btn-last').on('click', function(){
    monkeyList.show(monkeyList.size(),1)
})

Updated Fiddle 2


问:
Extracting list-elements that appear more than once
I have the following list:

```<code>tmp <- list(c(1,2,1,2,11,29),
            c(2,3,2,3,20,21),
            c(10,11,12,13,14,15))

names(tmp) <- c("ID1","ID2","ID3")
</code>```

If we write out each of the 5 vectors of this list, we then have

```<code>(1,2,10)
(2,3,11)
(1,2,12)
(2,3,13)
(11,20,14)
(29,21,15)
</code>```

Note that the combination (1,2,X) and (2,3,Y) appear twice, both of them. I would like to extract those vectors, where the first two elements appear n times. So for n=2 we would get

```<code>(1,2,10)
(1,2,12)
</code>```

and

```<code>(2,3,11)
(2,3,13)
</code>```

答:
We loop through the list elements, check whether the vector elements are %in% 'one' ('two'), get the sum of the logical vectors, check if it is greater than or equal to 2, then use this index to subset the list elements

```<code>tmp[sapply(tmp, function(x) sum(x %in% tmp$one)>=2)]
tmp[sapply(tmp, function(x) sum(x %in% tmp$two)>=2)]
</code>```

It can be combined in a single call

```<code>lapply(tmp[c("one", "two")], function(x) tmp[sapply(tmp, function(y) sum(y %in% x)>=2)])
#$one
#$one$one
#[1] 1 2 3 4 5 6

#$one$four
#[1]  1  2 15 16 17 18

#$two
#$two$two
#[1]  7  8  9 10 11 12

#$two$five
#[1]  7  8 15 16 17 18

#$two$<NA>
#[1]  7  8 20 21 22 23
</code>```

Based on the output showed, it can be also a matrix

```<code>lapply(tmp[c("one", "two")], function(x)
         do.call(rbind, tmp[sapply(tmp, function(y) sum(y %in% x)>=2)]))
</code>```

In general, if we want to compare elements of list for any number of combinations, combn can be used

```<code>lst1 <- combn(tmp, 3, FUN = list)
lst1[sapply(lst1, function(x) length(Reduce(intersect, x))>=3)]
</code>```

Update

Based on the new question

```<code>library(purrr)
tmp1 <- transpose(tmp) %>%
            map(unlist, use.names = FALSE)
lst1 <- combn(tmp1, 2, FUN = list)
lapply(lst1[sapply(lst1, function(x) length(Reduce(intersect, x))==2)],
               function(x) do.call(rbind, x))
#[[1]]
#     [,1] [,2] [,3]
#[1,]    1    2   10
#[2,]    1    2   12

#[[2]]
#     [,1] [,2] [,3]
#[1,]    2    3   11
#[2,]    2    3   13
</code>```

Body:
I have the following list:

tmp <- list(c(1,2,1,2,11,29),
            c(2,3,2,3,20,21),
            c(10,11,12,13,14,15))

names(tmp) <- c("ID1","ID2","ID3")

If we write out each of the 5 vectors of this list, we then have

(1,2,10)
(2,3,11)
(1,2,12)
(2,3,13)
(11,20,14)
(29,21,15)

Note that the combination (1,2,X) and (2,3,Y) appear twice, both of them. I would like to extract those vectors, where the first two elements appear n times. So for n=2 we would get

(1,2,10)
(1,2,12)

and

(2,3,11)
(2,3,13)

Body:
We loop through the list elements, check whether the vector elements are %in% 'one' ('two'), get the sum of the logical vectors, check if it is greater than or equal to 2, then use this index to subset the list elements

tmp[sapply(tmp, function(x) sum(x %in% tmp$one)>=2)]
tmp[sapply(tmp, function(x) sum(x %in% tmp$two)>=2)]

It can be combined in a single call

lapply(tmp[c("one", "two")], function(x) tmp[sapply(tmp, function(y) sum(y %in% x)>=2)])
#$one
#$one$one
#[1] 1 2 3 4 5 6

#$one$four
#[1]  1  2 15 16 17 18

#$two
#$two$two
#[1]  7  8  9 10 11 12

#$two$five
#[1]  7  8 15 16 17 18

#$two$<NA>
#[1]  7  8 20 21 22 23

Based on the output showed, it can be also a matrix

lapply(tmp[c("one", "two")], function(x)
         do.call(rbind, tmp[sapply(tmp, function(y) sum(y %in% x)>=2)]))

In general, if we want to compare elements of list for any number of combinations, combn can be used

lst1 <- combn(tmp, 3, FUN = list)
lst1[sapply(lst1, function(x) length(Reduce(intersect, x))>=3)]

Update

Based on the new question

library(purrr)
tmp1 <- transpose(tmp) %>%
            map(unlist, use.names = FALSE)
lst1 <- combn(tmp1, 2, FUN = list)
lapply(lst1[sapply(lst1, function(x) length(Reduce(intersect, x))==2)],
               function(x) do.call(rbind, x))
#[[1]]
#     [,1] [,2] [,3]
#[1,]    1    2   10
#[2,]    1    2   12

#[[2]]
#     [,1] [,2] [,3]
#[1,]    2    3   11
#[2,]    2    3   13


问:
C++, find_if with vector<unique_ptr> is not working properly
I realize that similar questions has been asked before but i didn't find the answer to my question so I'm just gonna post it here.

iteratorHelper takes an accountNr as argument, searches a vector of unique_ptrs and returns a bool.

The problems is in the second method.

The if-statement in getAccInfo(size_t pAccNr) is giving me problems.
My IDE is complaining about the "iteratorHelper" saying that

The object has type qualifiers that are not compatible with the member function "Client::iteratorHelper". Object type is const Client

I'm not entirely sure what I'm missing here so if anyone could point me in the right direction?

```<code>auto Client::iteratorHelper(size_t accountNr ) {
  return find_if(
    accounts.begin(), accounts.end(),
    [&accountNr ](const unique_ptr<Account>& account) {
      return account->getAccountNr() == accountNr;
    }
  );

unique_ptr<Account> const & Client::getAccInfo(size_t pAccNr) const {
  if (iteratorHelper(pAccNr) != accounts.end()) {
    auto const& index = distance(accounts.begin(), iteratorHelper(pAccNr));
    return accounts[index];
  }
  return nullptr;
}
</code>```

答: iteratorHelper is not const.  You are calling it from a const function getAccInfo.  This is illegal.

Body:
I realize that similar questions has been asked before but i didn't find the answer to my question so I'm just gonna post it here.

iteratorHelper takes an accountNr as argument, searches a vector of unique_ptrs and returns a bool.

The problems is in the second method.

The if-statement in getAccInfo(size_t pAccNr) is giving me problems.
My IDE is complaining about the "iteratorHelper" saying that

The object has type qualifiers that are not compatible with the member function "Client::iteratorHelper". Object type is const Client

I'm not entirely sure what I'm missing here so if anyone could point me in the right direction?

auto Client::iteratorHelper(size_t accountNr ) {
  return find_if(
    accounts.begin(), accounts.end(),
    [&accountNr ](const unique_ptr<Account>& account) {
      return account->getAccountNr() == accountNr;
    }
  );

unique_ptr<Account> const & Client::getAccInfo(size_t pAccNr) const {
  if (iteratorHelper(pAccNr) != accounts.end()) {
    auto const& index = distance(accounts.begin(), iteratorHelper(pAccNr));
    return accounts[index];
  }
  return nullptr;
}


问:
Finding the position of an item in another list from a number in a different list
Developing on my previous question I'm wondering whether there is a way to have an element in a list and find that position in another list and return what is in the position as a variable. for example:

```<code>list1 = [0,1,2,3,4]
list2 = ["0","hello","my","name","is","Daniel"]
</code>```

if the user enters the number 14 the program will return "hello Daniel" in the sense that the computer reads 14 as 1 and 4 and finds the position in list as an example.

I've tired using [list2.index(x) for x in list1] hoping that it would work but I've been unable to change the code so it does work. is there a simple way to do it

答:
I think that this will solve your problem:
for x in list1:
   print list2[x]

Is it that what you were asking ?

Body:
Developing on my previous question I'm wondering whether there is a way to have an element in a list and find that position in another list and return what is in the position as a variable. for example:

list1 = [0,1,2,3,4]
list2 = ["0","hello","my","name","is","Daniel"]

if the user enters the number 14 the program will return "hello Daniel" in the sense that the computer reads 14 as 1 and 4 and finds the position in list as an example.

I've tired using [list2.index(x) for x in list1] hoping that it would work but I've been unable to change the code so it does work. is there a simple way to do it


问:
updating an attibute on ruby on rails associated object with the has one association error
Please I need your help. I tried to update an attribute on a table but it is not updating. below is a run of the code.

user = User.find(7)
  User Load (4.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 7], ["LIMIT", 1]]

login_details = user.login_detail
login_details = user.login_detail
  LoginDetail Load (0.0ms)  SELECT  "login_details".* FROM "login_details" WHERE "login_details"."user_id" = ? LIMIT ?  [["user_id", 7], ["LIMIT", 1]]

login_details.status = 1
login_details.status = 1
1
login_details.save
login_details.save
   (1.0ms)  begin transaction
   (0.0ms)  commit transaction
true

The user has one login detail.

答: Are you sure that your login_details object doesn't have status = 1 already? If it's true ActiveRecord not start database query.</p>


问:
byte swapping and C++/C
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

```<code>int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}
</code>```

Best,
U.

答:
htonl (host to network long) and htons (host to network short) will go from whatever platform you are on to big-endian. That was because back in those days most network hosts ran a form of UNIX that used native big-endian.

ntohl and ntohs will convert big endian to native, regardless of your platform. If your are on a big endian platform, these will be a no-op.

Aside from byte order, the other potential portability issue is the size of the short and the long. ntohl will read 4 bytes and convert to a 32 bit integer. The target int therefore be at least 32 bits to hold it, it doesn't need to be exactly that length. ntohs reads 2 bytes and convert to a short int of 16 bits. Note that if your native platform does use more than 32 bits for long or 16 bits for short, you have to manage the "sign" issue if they are signed integers (because the actual type for ntohl is unsigned).

As more machines now including Linux ones use Intel processors with little-endian notation, a lot more frequently now you use that as the "default" format and get big-endian formats to change. In such a case you may want to write macros of your own to convert to little-endian (on an already little-endian platform they would be no-op).

For actually reversing bytes you can use std::reverse, by the way, and you will need two pointers, one pointing to the first byte and the other one to be one past the last byte.

You can also implement "byte-swap" and then your right pointer should be on the last byte, not one-past-the-end. You byteswap like this:

```<code>void byteswap( unsigned char & byte1, unsigned char & byte2 )
{
   byte1 ^= byte2;
   byte2 ^= byte1;
   byte1 ^= byte2;
}
</code>```

To implement in C (rather than C++) you would use a pointer rather than a reference as the parameter.

In the actual example you have given, the file appears to be stored in 32-bit big-endian (i.e. network) byte order by its specification, so you can here simply use ntohl, however ntohl takes an unsigned int as a parameter. Thus correct your code to:

```<code>uint32_t count = 0;
myfile.open ("truss.rst", ios::binary);
myfile.read(reinterpret_cast<char*>(&count), sizeof(uint32_t));
   // ideally validate that the read succeeded
count = ntohl( count );
</code>```

One of the weakenesses in iostream in my opinion that you have to do that cast. Whoever wrote it never really liked the concept of binary i/o. Of course if you are writing this in C rather than C++ you would use FILE* and fread.

Title: byte swapping and C++/C

Body:
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}

Best,
U.

Body:
htonl (host to network long) and htons (host to network short) will go from whatever platform you are on to big-endian. That was because back in those days most network hosts ran a form of UNIX that used native big-endian.

ntohl and ntohs will convert big endian to native, regardless of your platform. If your are on a big endian platform, these will be a no-op.

Aside from byte order, the other potential portability issue is the size of the short and the long. ntohl will read 4 bytes and convert to a 32 bit integer. The target int therefore be at least 32 bits to hold it, it doesn't need to be exactly that length. ntohs reads 2 bytes and convert to a short int of 16 bits. Note that if your native platform does use more than 32 bits for long or 16 bits for short, you have to manage the "sign" issue if they are signed integers (because the actual type for ntohl is unsigned).

As more machines now including Linux ones use Intel processors with little-endian notation, a lot more frequently now you use that as the "default" format and get big-endian formats to change. In such a case you may want to write macros of your own to convert to little-endian (on an already little-endian platform they would be no-op).

For actually reversing bytes you can use std::reverse, by the way, and you will need two pointers, one pointing to the first byte and the other one to be one past the last byte.

You can also implement "byte-swap" and then your right pointer should be on the last byte, not one-past-the-end. You byteswap like this:

void byteswap( unsigned char & byte1, unsigned char & byte2 )
{
   byte1 ^= byte2;
   byte2 ^= byte1;
   byte1 ^= byte2;
}

To implement in C (rather than C++) you would use a pointer rather than a reference as the parameter.

In the actual example you have given, the file appears to be stored in 32-bit big-endian (i.e. network) byte order by its specification, so you can here simply use ntohl, however ntohl takes an unsigned int as a parameter. Thus correct your code to:

uint32_t count = 0;
myfile.open ("truss.rst", ios::binary);
myfile.read(reinterpret_cast<char*>(&count), sizeof(uint32_t));
   // ideally validate that the read succeeded
count = ntohl( count );

One of the weakenesses in iostream in my opinion that you have to do that cast. Whoever wrote it never really liked the concept of binary i/o. Of course if you are writing this in C rather than C++ you would use FILE* and fread.