问:
Why is this simple regular expression not working
This is a sample code from a scala book.
This object has a method that will remove any html tags in a given string.
But for reason, it removes the entire string content not just HTML tags. May i know why?</p>

```<code>object HtmlUtils {
 def removeMarkup(input: String) = {
    input.replaceAll("""</?\w[^>]*>""","")
    input.replaceAll("<.*>","")
   }
 }

val ahtmlText = "<html><body><h1>Introduction</h1></body></html>"

val anewhtmlText = HtmlUtils.removeMarkup(ahtmlText)

println(anewhtmlText)

println(s"Before removing html tags, the string was $ahtmlText and after rmoving html tags the string became $anewhtmlText")
</code>```

答:
Your 2nd replaceAll is not needed and will remove everything due to greedy match by .*.  Also, your 1st replaceAll can be generalized, if wanted.  The following revised removeMarkup should work for you:

```<code>object HtmlUtils {
  def removeMarkup(input: String) = {
    input.replaceAll("""</?[^>]*>""", "")
  }
}

scala> val ahtmlText = "<html><body><h1>Introduction</h1></body></html>"
ahtmlText: String = <html><body><h1>Introduction</h1></body></html>

scala> val anewhtmlText = HtmlUtils.removeMarkup(ahtmlText)
anewhtmlText: String = Introduction
</code>```

Body:
This is a sample code from a scala book.
This object has a method that will remove any html tags in a given string.
But for reason, it removes the entire string content not just HTML tags. May i know why?

object HtmlUtils {
 def removeMarkup(input: String) = {
    input.replaceAll("""</?\w[^>]*>""","")
    input.replaceAll("<.*>","")
   }
 }

val ahtmlText = "
Introduction
"

val anewhtmlText = HtmlUtils.removeMarkup(ahtmlText)

println(anewhtmlText)

println(s"Before removing html tags, the string was $ahtmlText and after rmoving html tags the string became $anewhtmlText")

Body:
Your 2nd replaceAll is not needed and will remove everything due to greedy match by .*.  Also, your 1st replaceAll can be generalized, if wanted.  The following revised removeMarkup should work for you:

object HtmlUtils {
  def removeMarkup(input: String) = {
    input.replaceAll("""</?[^>]*>""", "")
  }
}

scala> val ahtmlText = "<html><body><h1>Introduction</h1></body></html>"
ahtmlText: String = <html><body><h1>Introduction</h1></body></html>

scala> val anewhtmlText = HtmlUtils.removeMarkup(ahtmlText)
anewhtmlText: String = Introduction


来源: stackexchange

问:
CSS: background-color on section tag doesn't cover full width?
Foremost there are a lot of posts relating to background-color. I have read several and have tried various solutions posted there from setting background-size to making overflow hidden. Nothing seems to work....
How can I get background-color to cover the whole section?

I have a very simple M.W.E. below:

html

```<code><body>
<section>
  TEST!
</section>
</body>
</code>```

css

```<code>body {
  background-color: coral;
}

section {
  background-color: blue;
  width: 100%;
}
</code>```

Fiddle

答:
I would recommend reading about "reseting css", zeroing margin and padding of body, html, p and etc. It can solve your problem.
reset-css</p>

ContentLicense: CC BY-SA 3.0

Body:
Foremost there are a lot of posts relating to background-color. I have read several and have tried various solutions posted there from setting background-size to making overflow hidden. Nothing seems to work....
How can I get background-color to cover the whole section?

I have a very simple M.W.E. below:

html

  TEST!

css

body {
  background-color: coral;
}

section {
  background-color: blue;
  width: 100%;
}

Fiddle


问:
How expensive is it to dereference a pointer?
How expensive is it to perform the dereference operation on a pointer?

I can imagine that the memory transfer is somehow proportional to the object size, but I want to know how expensive the dereference operation part is.

答:
The most important factor in dereferencing pointers on ordinary systems is that you're likely to generate a cache miss. A random access in SDRAM memory costs tens of nanoseconds (e.g. 64). On gigaherz processors, this means that your processor is idling hundreds (or > thousand) of cycles, without being able of doing anything else in the meantime.

Only on SRAM based systems (which you'll only find in embedded software), or when your software is cache optimized, the factors discussed in the other posts come into play.

OwnerDisplayName: Tunnuz

LastEditorDisplayName: ChrisN

ContentLicense: CC BY-SA 2.5


问:
cannot resolve com.google.android.gsm;play-services:25.1.0
i was working on a project, everything was fine but when i tried to run the app, i couldn't,i guess because i'm using a bundled version of google play services. so i i made sure that i update android studio and install the lastest google repository.
but it still wouldn't work. And when i click on install Repostiroy and sync project, still nothing happens.

please help me : this is my gradle ;

```<code>apply plugin: 'com.android.application'

 android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.example.nefissa.pfe2"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner       "android.support.test.runner.AndroidJUnitRunner"
 }
  buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',     {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:design:25.1.0'
compile 'com.android.support:cardview-v7:25.1.0'
compile 'com.google.android.gms:play-services:25.1.0'

testCompile 'junit:junit:4.12'
}
</code>```

please where did i go wrong?

a screenshot;please what can i do? the click on install wouldn't work

答:
replace it with compile 'com.google.android.gms:play-services:10.2.0'

and add apply plugin: 'com.google.gms.google-services' on the bottom of your gradle,

and make sure you added classpath 'com.google.gms:google-services:3.0.0'
in the Top-level build.gradle file

Body:
i was working on a project, everything was fine but when i tried to run the app, i couldn't,i guess because i'm using a bundled version of google play services. so i i made sure that i update android studio and install the lastest google repository.
but it still wouldn't work. And when i click on install Repostiroy and sync project, still nothing happens.

please help me : this is my gradle ;

apply plugin: 'com.android.application'

 android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.example.nefissa.pfe2"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner       "android.support.test.runner.AndroidJUnitRunner"
 }
  buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',     {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:design:25.1.0'
compile 'com.android.support:cardview-v7:25.1.0'
compile 'com.google.android.gms:play-services:25.1.0'

testCompile 'junit:junit:4.12'
}

please where did i go wrong?

a screenshot;please what can i do? the click on install wouldn't work


问:
how to display name after login php in all other pages not only homepage
I'm having trouble to display my name in all the pages that I have after login in the website :

AuthentificationController.php

```<code> public  function Connex($db,$login,$mdp)
 {

$requser = $db->prepare("SELECT * FROM users WHERE login = ? AND motdepasse
 = ?");
$requser->execute(array($login,$mdp));
$userexist = $requser->rowCount();
if($userexist == 1)
{
$userinfo = $requser->fetch();
$_SESSION['login'] = $userinfo['login'];
$_SESSION['motdepasse'] = $userinfo['motdepasse'];
if($userinfo['role']=="admin")
{
session_start();
header("Location:/ProjetWeb2A1 - Copie/account.php?id=".$_SESSION['login']);
}

else if($userinfo['role']=="client")
{
session_start();

header("Location:/ProjetWeb2A1 - Copie/accueil.php?id=".$_SESSION['login']);
}
}
</code>```

Homepage.php

```<code><div class="header">
        <div class="header-left">
            <ul>
                <li><a href="account.php">Inscription</a></li>
                <li class="login">
                    <div id="loginContainer"><a id="loginButton"><span>Se Connecter</span></a>
                        <div id="loginBox" style="display: none;">
                            <form id="loginForm"  method="POST" action="\ProjetWeb2A1 - Copie\controllers\Authentification_controller.php">
                                        <label>Login</label>
                                        <input type="text" name="login" id="email" >
                                        <label for="password">Mot de passe</label>
                                        <input type="password" name="password" id="password">
                                    <input type="submit" id="login" value="Connexion" name="xxl1">
                                    <label for="checkbox"><input type="checkbox" id="checkbox"> <i>Rester Connecté</i></label>
                                <span><a href="#">Mot de passe oublié?</a></span>
                            </form>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
</code>```

If someone could answer me what i need to do to change that Inscription and Se

Connecter with my username in all my other pages please

答:
As long as you use $_SESSION, and want to populate it, start each page with :

```<code> <?php
 session_start();
 $login = $_SESSION['login'];
 echo"Welcome $login";
 ?>
</code>```

simple code example, only to give you a hint... then, do whatever you need : check it, secure it...

Body:
I'm having trouble to display my name in all the pages that I have after login in the website :

AuthentificationController.php

 public  function Connex($db,$login,$mdp)
 {

$requser = $db->prepare("SELECT * FROM users WHERE login = ? AND motdepasse
 = ?");
$requser->execute(array($login,$mdp));
$userexist = $requser->rowCount();
if($userexist == 1)
{
$userinfo = $requser->fetch();
$_SESSION['login'] = $userinfo['login'];
$_SESSION['motdepasse'] = $userinfo['motdepasse'];
if($userinfo['role']=="admin")
{
session_start();
header("Location:/ProjetWeb2A1 - Copie/account.php?id=".$_SESSION['login']);
}

else if($userinfo['role']=="client")
{
session_start();

header("Location:/ProjetWeb2A1 - Copie/accueil.php?id=".$_SESSION['login']);
}
}

Homepage.php

Inscription

Se Connecter

                            <form id="loginForm"  method="POST" action="\ProjetWeb2A1 - Copie\controllers\Authentification_controller.php">
                                        Login
                                        <input type="text" name="login" id="email" >
                                        Mot de passe
                                        <input type="password" name="password" id="password">
                                    <input type="submit" id="login" value="Connexion" name="xxl1">
                                    <input type="checkbox" id="checkbox"> Rester Connecté
                                Mot de passe oublié?
                            </form>

If someone could answer me what i need to do to change that Inscription and Se

Connecter with my username in all my other pages please

Body:
As long as you use $_SESSION, and want to populate it, start each page with :

 <?php
 session_start();
 $login = $_SESSION['login'];
 echo"Welcome $login";
 ?>

simple code example, only to give you a hint... then, do whatever you need : check it, secure it...


问:
Rendered text looks very different in Qt and Blink, although same font is set
The upper font is from a QLabel with QFont("Arial").
The lower font is rendered with QWebEngine, e.g. Chromium/Blink backend, using css

```<code>font-family: Arial, Helvetica, sans-serif;
font-size: 8pt;
</code>```

Is there a way to make the blink one look as dark and sharp as the Qt one? It looks blurry and as both texts in the app are placed next to each other, it does not look good enough.

(Qt5.8 msvc 2015 on windows 8.1)

Edit

The reason is that chromium since version 52 did drop GDI support. In former version GDI rendering could be activated by disabling the DirectWrite flag. So basically I need to recompile Qt with a different chromium backend. Or perhaps with Cent Browser because it still supports that flag despite using newest chromium.

答:
First get the font family using  QFontInfo::family().
This function returns matched family name of windows system font.

```<code>QFont f("Arial");
QFontInfo info(f);
QString family = info.family();
</code>```

In simple terms "QFontInfo object is used to determine the attributes of the font actually used in the window system."

Use the family name returned by QFontInfo and set the same for QWebEngine by QWebEngineSettings::setFontFamily or using CSS.

useful links:

http://doc.qt.io/qt-5/qfontinfo.html#family

http://doc.qt.io/qt-5/qwebenginesettings.html#setFontFamily

Body:
The upper font is from a QLabel with QFont("Arial").
The lower font is rendered with QWebEngine, e.g. Chromium/Blink backend, using css

font-family: Arial, Helvetica, sans-serif;
font-size: 8pt;

Is there a way to make the blink one look as dark and sharp as the Qt one? It looks blurry and as both texts in the app are placed next to each other, it does not look good enough.

(Qt5.8 msvc 2015 on windows 8.1)

Edit

The reason is that chromium since version 52 did drop GDI support. In former version GDI rendering could be activated by disabling the DirectWrite flag. So basically I need to recompile Qt with a different chromium backend. Or perhaps with Cent Browser because it still supports that flag despite using newest chromium.

Body:
First get the font family using  QFontInfo::family().
This function returns matched family name of windows system font.

QFont f("Arial");
QFontInfo info(f);
QString family = info.family();

In simple terms "QFontInfo object is used to determine the attributes of the font actually used in the window system."

Use the family name returned by QFontInfo and set the same for QWebEngine by QWebEngineSettings::setFontFamily or using CSS.

useful links:

http://doc.qt.io/qt-5/qfontinfo.html#family

http://doc.qt.io/qt-5/qwebenginesettings.html#setFontFamily


问:
Comparing 2 arrays for equal elements and deleting the entries from both arrays
Suppose i have 2 numpy arrays which have elements like these:

```<code>arr1 = [[1, 2], [3, 5], [3, 4]]
arr2 = [[2, 3], [3, 4], [6, 6]]
</code>```

I want the resultant array to have arr2 appended or horizontally stacked to
 arr1 containing the elements which are NOT present in both the arrays:

```<code>arr3 = [[1, 2], [3, 5], [2, 3], [6, 6]]
</code>```

As you can see, [3, 4] is not there in the expected resultant array. What is the best numpy and pythonic implementation for this?

答:
how about:

```<code>[l for l in arr1+arr2 if (arr1+arr2).count(l)==1]
</code>```

output:

```<code>[[1, 2], [3, 5], [2, 3], [6, 6]]
</code>```

or, if you want it a bit more efficient:

```<code>c=arr1+arr2
[l for l in c if c.count(l)==1]
</code>```

Body:
Suppose i have 2 numpy arrays which have elements like these:

arr1 = [[1, 2], [3, 5], [3, 4]]
arr2 = [[2, 3], [3, 4], [6, 6]]

I want the resultant array to have arr2 appended or horizontally stacked to
 arr1 containing the elements which are NOT present in both the arrays:

arr3 = [[1, 2], [3, 5], [2, 3], [6, 6]]

As you can see, [3, 4] is not there in the expected resultant array. What is the best numpy and pythonic implementation for this?

Body:
how about:

[l for l in arr1+arr2 if (arr1+arr2).count(l)==1]

output:

[[1, 2], [3, 5], [2, 3], [6, 6]]

or, if you want it a bit more efficient:

c=arr1+arr2
[l for l in c if c.count(l)==1]


问:
Quicksort in Ruby with Pivot being the first element
This method never ends... stuck in a continuous loop. But, I don't understand why.
Could somebody please point this out for me.
The idea is to do everything in place. Once the array has been fully sorted, to return the array.</p>

```<code>def quicksort(array, start=0, finish=array.size-1)
  return array if start >= finish
  pivot_index = start
  pivot_value = array[pivot_index]
  i = pivot_index + 1     # this sets apart the less than and greater than
  j = i                   # this sets apart the section that has/hasn't been evaluated

  # evaluate the pivot to the range of elements
  while j <= finish

    # if pivot > element being evaluated, put the evaluted elements inside "less than" section
    if array[pivot_index] > array[j]
      array[i], array[j] = array[j], array[i]
      i += 1
    end
    j += 1
  end

  # swap the pivot with the right-most element in the "less than" section
  array[pivot_index], array[i-1] = array[i-1], array[pivot_index]
  new_pivot_index = array.index(pivot_value)

  # sort to the right of the pivot
  unless new_pivot_index + 1 >= finish
    start = new_pivot_index + 1
    quicksort(array, start, finish)
  end

  # sort to the left of the pivot
  unless new_pivot_index == 0
    finish = new_pivot_index - 1
    start = 0
    quicksort(array, start, finish)
  end
  return array
end
</code>```

答:
It turns out I just needed to remove some of the unless statements that were prevented the base case from being called.

Answer is below.

```<code>def quicksort(array, start=0, finish=array.size-1)
  return if start >= finish
  pivot_index = start
  pivot_value = array[pivot_index]
  i = pivot_index + 1     # this sets apart the less than and greater than
  j = i                   # this sets apart the section that has/hasn't been evaluated

  # evaluate the pivot to the range of elements
  while j <= finish

    # if pivot > element being evaluated, put the evaluted elements inside "less than" section
    if array[pivot_index] > array[j]
      array[i], array[j] = array[j], array[i]
      i += 1
    end
    j += 1
  end

  # swap the pivot with the right-most element in the "less than" section
  array[pivot_index], array[i-1] = array[i-1], array[pivot_index]
  new_pivot_index = array.index(pivot_value)

  # sort to the right of the pivot
  quicksort(array, new_pivot_index + 1, finish)

  # sort to the left of the pivot
  quicksort(array, start, new_pivot_index - 1)
  return array
end
</code>```

Body:
This method never ends... stuck in a continuous loop. But, I don't understand why.
Could somebody please point this out for me.
The idea is to do everything in place. Once the array has been fully sorted, to return the array.

def quicksort(array, start=0, finish=array.size-1)
  return array if start >= finish
  pivot_index = start
  pivot_value = array[pivot_index]
  i = pivot_index + 1     # this sets apart the less than and greater than
  j = i                   # this sets apart the section that has/hasn't been evaluated

  # evaluate the pivot to the range of elements
  while j <= finish

    # if pivot > element being evaluated, put the evaluted elements inside "less than" section
    if array[pivot_index] > array[j]
      array[i], array[j] = array[j], array[i]
      i += 1
    end
    j += 1
  end

  # swap the pivot with the right-most element in the "less than" section
  array[pivot_index], array[i-1] = array[i-1], array[pivot_index]
  new_pivot_index = array.index(pivot_value)

  # sort to the right of the pivot
  unless new_pivot_index + 1 >= finish
    start = new_pivot_index + 1
    quicksort(array, start, finish)
  end

  # sort to the left of the pivot
  unless new_pivot_index == 0
    finish = new_pivot_index - 1
    start = 0
    quicksort(array, start, finish)
  end
  return array
end

Body:
It turns out I just needed to remove some of the unless statements that were prevented the base case from being called.

Answer is below.

def quicksort(array, start=0, finish=array.size-1)
  return if start >= finish
  pivot_index = start
  pivot_value = array[pivot_index]
  i = pivot_index + 1     # this sets apart the less than and greater than
  j = i                   # this sets apart the section that has/hasn't been evaluated

  # evaluate the pivot to the range of elements
  while j <= finish

    # if pivot > element being evaluated, put the evaluted elements inside "less than" section
    if array[pivot_index] > array[j]
      array[i], array[j] = array[j], array[i]
      i += 1
    end
    j += 1
  end

  # swap the pivot with the right-most element in the "less than" section
  array[pivot_index], array[i-1] = array[i-1], array[pivot_index]
  new_pivot_index = array.index(pivot_value)

  # sort to the right of the pivot
  quicksort(array, new_pivot_index + 1, finish)

  # sort to the left of the pivot
  quicksort(array, start, new_pivot_index - 1)
  return array
end


问:
Concat & Indexing Several Different Time Series In Pandas
I've got several different futures price time series combined into one data frame using concat. For example, soybeans and corn futures contracts for a number of different years.

I would like to compare the prices of the varying contracts graphically on the same time basis, in this case Nov 1 through July 1, disregarding the year. To do that, I used reset_index() to combine them together.

Only problem is when I graph them, I'd like to have an x-axis that is a bit more intuitive than just a 0 to 160 numerical index interval. Ideally, I would like to have the labels Nov 1 through Jul 1 monthly and omit the year.

This of course is fairly easy to do in excel, but I’d like to be able to do it in Python as well.

```<code>dfc14 = quandl.get('CME/CZ2014.6', start_date='2013-11-01', end_date='2014-07-\ 01', authtoken=api_key)

dfs14 = quandl.get('CME/SX2014.6', start_date='2013-11-01', end_date='2014-07-01', authtoken=api_key)
dfr14 = dfs14.div(dfc14)
dfr14 = dfr14.rename(columns={'Settle':'2014'})
dfr14 = dfr14.reset_index()
# ...
com_df = pd.concat([dfr17, dfr16, dfr14],)
</code>```

答:
The way I did this was to get a mmdd column and use that as the index -- for the x-axis and x-axis labels.

I did it for two of the three DataFrames.

```<code>dfr14['mmdd'] = (dfr14['Date'].dt.month.astype(str).str.zfill(2) +
                 dfr14['Date'].dt.day.astype(str).str.zfill(2))
dfr15['mmdd'] = (dfr15['Date'].dt.month.astype(str).str.zfill(2) +
                 dfr15['Date'].dt.day.astype(str).str.zfill(2))

dfr15 = dfr15.set_index('mmdd')
dfr14 = dfr14.set_index('mmdd')

ax = dfr15.plot()
dfr14.plot(ax=ax)
plt.show()
</code>```

Result of the two:

Body:
I've got several different futures price time series combined into one data frame using concat. For example, soybeans and corn futures contracts for a number of different years.

I would like to compare the prices of the varying contracts graphically on the same time basis, in this case Nov 1 through July 1, disregarding the year. To do that, I used reset_index() to combine them together.

Only problem is when I graph them, I'd like to have an x-axis that is a bit more intuitive than just a 0 to 160 numerical index interval. Ideally, I would like to have the labels Nov 1 through Jul 1 monthly and omit the year.

This of course is fairly easy to do in excel, but I’d like to be able to do it in Python as well.

dfc14 = quandl.get('CME/CZ2014.6', start_date='2013-11-01', end_date='2014-07-\ 01', authtoken=api_key)

dfs14 = quandl.get('CME/SX2014.6', start_date='2013-11-01', end_date='2014-07-01', authtoken=api_key)
dfr14 = dfs14.div(dfc14)
dfr14 = dfr14.rename(columns={'Settle':'2014'})
dfr14 = dfr14.reset_index()
# ...
com_df = pd.concat([dfr17, dfr16, dfr14],)

Body:
The way I did this was to get a mmdd column and use that as the index -- for the x-axis and x-axis labels.

I did it for two of the three DataFrames.

dfr14['mmdd'] = (dfr14['Date'].dt.month.astype(str).str.zfill(2) +
                 dfr14['Date'].dt.day.astype(str).str.zfill(2))
dfr15['mmdd'] = (dfr15['Date'].dt.month.astype(str).str.zfill(2) +
                 dfr15['Date'].dt.day.astype(str).str.zfill(2))

dfr15 = dfr15.set_index('mmdd')
dfr14 = dfr14.set_index('mmdd')

ax = dfr15.plot()
dfr14.plot(ax=ax)
plt.show()

Result of the two:


问:
How to generate Calendars in java?
I need to build a backend Java class that generates Calenders. The Calendar has 12 months to complete a year. In that year, the first month is July and the last month is June. In a sense, the months in the generated calender will have a different years. For instance, the first month will be July-2016 and the last month will be June-2017 and so on. Below is what I have so far. </p>

```<code>public class Calendars {

    public Date startDate;
    public Date endDate;
    public String periodName;//This is the name of the year(e.g July-2016 to June-2017 may be called period01)
    public short physicalYear;//This is the normal year

    public Calendars() {
    }

    public Calendars(Date startDate, Date endDate, String periodName, short physicalYear) {
        this.startDate = startDate;
        this.endDate = endDate;
        this.periodName = periodName;
        this.physicalYear = physicalYear;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public String getPeriodName() {
        return periodName;
    }

    public void setPeriodName(String periodName) {
        this.periodName = periodName;
    }

    public short getPhysicalYear() {
        return physicalYear;
    }

    public void setPhysicalYear(short physicalYear) {
        this.physicalYear = physicalYear;
    }

    @Override
    public String toString() {
        return "Calendars{" +
                "startDate=" + startDate +
                ", endDate=" + endDate +
                ", periodName='" + periodName + '\'' +
                ", physicalYear=" + physicalYear +
                '}';
    }
}
</code>```

答:
tl;dr

```<code>YearMonth.of( 2017 , Month.JULY )
         .plusYears( 1 )
</code>```

Avoid legacy date-time classes

Avoid the old legacy date-time classes such as Date & Calendar. They are troublesome, confusing, poorly designed, and flawed. Now supplanted by the java.time classes.

YearMonth

You seem to want to track a span of time as whole months. For that use the YearMonth class.

Note that unlike the legacy classes, in java.time the months have sane numbering, 1-12 for January-December.

```<code>YearMonth start = YearMonth.of( 2017 , 7 );
YearMonth stop = start.plusYears( 1 );
</code>```

Or specify the month using the handy Month enum.

```<code>YearMonth start = YearMonth.of( 2017 , Month.JULY );
</code>```

If you want the current YearMonth, specify a time zone. Remember that for any given moment, the date varies around the globe by zone, and therefore the month may vary.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

```<code>ZoneId z = ZoneId.of( "America/Montreal" );
YearMonth ym = YearMonth.now( z );
</code>```

LocalDate

To work with individual dates, use the LocalDate class.

```<code>LocalDate firstOfMonth = ym.atDay( 1 );
LocalDate dayAfter = firstOfMonth.plusDays( 1 );
LocalDate endOfMonth = ym.atEndOfMonth();
</code>```

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8 and SE 9 and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Title: How to generate Calendars in java?

Body:
I need to build a backend Java class that generates Calenders. The Calendar has 12 months to complete a year. In that year, the first month is July and the last month is June. In a sense, the months in the generated calender will have a different years. For instance, the first month will be July-2016 and the last month will be June-2017 and so on. Below is what I have so far.

public class Calendars {

    public Date startDate;
    public Date endDate;
    public String periodName;//This is the name of the year(e.g July-2016 to June-2017 may be called period01)
    public short physicalYear;//This is the normal year

    public Calendars() {
    }

    public Calendars(Date startDate, Date endDate, String periodName, short physicalYear) {
        this.startDate = startDate;
        this.endDate = endDate;
        this.periodName = periodName;
        this.physicalYear = physicalYear;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public String getPeriodName() {
        return periodName;
    }

    public void setPeriodName(String periodName) {
        this.periodName = periodName;
    }

    public short getPhysicalYear() {
        return physicalYear;
    }

    public void setPhysicalYear(short physicalYear) {
        this.physicalYear = physicalYear;
    }

    @Override
    public String toString() {
        return "Calendars{" +
                "startDate=" + startDate +
                ", endDate=" + endDate +
                ", periodName='" + periodName + '\'' +
                ", physicalYear=" + physicalYear +
                '}';
    }
}

Body:
tl;dr

YearMonth.of( 2017 , Month.JULY )
         .plusYears( 1 )

Avoid legacy date-time classes

Avoid the old legacy date-time classes such as Date & Calendar. They are troublesome, confusing, poorly designed, and flawed. Now supplanted by the java.time classes.

YearMonth

You seem to want to track a span of time as whole months. For that use the YearMonth class.

Note that unlike the legacy classes, in java.time the months have sane numbering, 1-12 for January-December.

YearMonth start = YearMonth.of( 2017 , 7 );
YearMonth stop = start.plusYears( 1 );

Or specify the month using the handy Month enum.

YearMonth start = YearMonth.of( 2017 , Month.JULY );

If you want the current YearMonth, specify a time zone. Remember that for any given moment, the date varies around the globe by zone, and therefore the month may vary.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
YearMonth ym = YearMonth.now( z );

LocalDate

To work with individual dates, use the LocalDate class.

LocalDate firstOfMonth = ym.atDay( 1 );
LocalDate dayAfter = firstOfMonth.plusDays( 1 );
LocalDate endOfMonth = ym.atEndOfMonth();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8 and SE 9 and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
Generating CSV file from SqlDataSource/GridView
I need to be able to generate a basic CSV file of the results returned from an SqlDataSource/GridView upon the user clicking a button, then allow them to save this file.

Is this simple to do?

Thanks

答:
Since you are using a SqlDataSource then you can get a DataTable out of it like this:

```<code>var dv = new DataView();
var dt = new DataTable();
dv = (DataView)mySQLDataSource.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();
</code>```

I wrote a set of extension methods to do DataTable to CSV, which you should be able to use easily.

The rest of your code would be pretty simple then:

```<code>var csv = dt.ToCSV();
</code>```

Here is a full example using this very method.

The Markup:

```<code><%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="SO.WebUI._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeId"
        DataSourceID="SqlDataSourceLocal">
        <Columns>
            <asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" InsertVisible="False"
                ReadOnly="True" SortExpression="EmployeeId" Visible="False" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
            <asp:BoundField DataField="Birthdate" HeaderText="Birthdate" SortExpression="Birthdate" />
        </Columns>
    </asp:GridView>

    <!-- This is the button to export CSV! -->
    <asp:Button ID="btnToCSV" runat="server" Text="Export to CSV" OnClick="GetCSV" />

    <asp:SqlDataSource ID="SqlDataSourceLocal" runat="server"
    ConnectionString="<%$ ConnectionStrings:StackOverflowExamplesConnectionString %>"
        SelectCommand="SELECT * FROM [Employee]"></asp:SqlDataSource>
</asp:Content>
</code>```

And the code-behind:

```<code>public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public void GetCSV(object sender, EventArgs e)
    {
        DataView dv = (DataView)SqlDataSourceLocal.Select(DataSourceSelectArguments.Empty);
        var dt = dv.ToTable();

        var csv = dt.ToCSV();

        WriteToOutput(csv, "export.csv", "text/csv");
    }

    private void WriteToOutput(String csv, String fileName, String mimeType)
    {
        Response.Clear();
        Response.ContentType = mimeType;
        Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName));
        Response.Write(csv);
        Response.End();
    }
}
</code>```

There you go. The only thing not included here is the extension method source, but since I've linked to it, you should have no problems getting that into a static class.

Body:
Since you are using a SqlDataSource then you can get a DataTable out of it like this:

var dv = new DataView();
var dt = new DataTable();
dv = (DataView)mySQLDataSource.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();

I wrote a set of extension methods to do DataTable to CSV, which you should be able to use easily.

The rest of your code would be pretty simple then:

var csv = dt.ToCSV();

Here is a full example using this very method.

The Markup:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="SO.WebUI._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeId"
        DataSourceID="SqlDataSourceLocal">
        <Columns>
            <asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" InsertVisible="False"
                ReadOnly="True" SortExpression="EmployeeId" Visible="False" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
            <asp:BoundField DataField="Birthdate" HeaderText="Birthdate" SortExpression="Birthdate" />
        </Columns>
    </asp:GridView>

    <!-- This is the button to export CSV! -->
    <asp:Button ID="btnToCSV" runat="server" Text="Export to CSV" OnClick="GetCSV" />

    <asp:SqlDataSource ID="SqlDataSourceLocal" runat="server"
    ConnectionString="<%$ ConnectionStrings:StackOverflowExamplesConnectionString %>"
        SelectCommand="SELECT * FROM [Employee]"></asp:SqlDataSource>
</asp:Content>

And the code-behind:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public void GetCSV(object sender, EventArgs e)
    {
        DataView dv = (DataView)SqlDataSourceLocal.Select(DataSourceSelectArguments.Empty);
        var dt = dv.ToTable();

        var csv = dt.ToCSV();

        WriteToOutput(csv, "export.csv", "text/csv");
    }

    private void WriteToOutput(String csv, String fileName, String mimeType)
    {
        Response.Clear();
        Response.ContentType = mimeType;
        Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName));
        Response.Write(csv);
        Response.End();
    }
}

There you go. The only thing not included here is the extension method source, but since I've linked to it, you should have no problems getting that into a static class.


问:
How to use timeit module
How do I use timeit to compare the performance of my own functions such as "insertion_sort" and "tim_sort"?

答:
```<code># Генерация целых чисел

def gen_prime(x):
    multiples = []
    results = []
    for i in range(2, x+1):
        if i not in multiples:
            results.append(i)
            for j in range(i*i, x+1, i):
                multiples.append(j)

    return results

import timeit

# Засекаем время

start_time = timeit.default_timer()
gen_prime(3000)
print(timeit.default_timer() - start_time)

# start_time = timeit.default_timer()
# gen_prime(1001)
# print(timeit.default_timer() - start_time)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to use timeit module


答:
If only items in same index can be similar you can use a simply numpythonic approach like following:

```<code>In [10]: mask = ~(arr1 == arr2).all(1)

In [11]: np.vstack((arr1[mask], arr2[mask]))
Out[11]:
array([[1, 2],
       [3, 5],
       [2, 3],
       [6, 6]])
</code>```

Otherwise you can find the intersections based on Jaime's answer then exclude them from combined array.

Or use following approach:

```<code>In [17]: arr1_view = arr1.view([('', arr1.dtype)] * arr1.shape[1])

In [18]: arr2_view = arr2.view([('', arr2.dtype)] * arr2.shape[1])

In [19]: diff_arr1 = np.setdiff1d(arr1_view, arr2_view).view(arr1.dtype).reshape(-1, arr1.shape[1])

In [20]: diff_arr2 = np.setdiff1d(arr2_view, arr1_view).view(arr2.dtype).reshape(-1, arr2.shape[1])

In [21]: np.vstack((diff_arr1, diff_arr2))
Out[21]:
array([[1, 2],
       [3, 5],
       [2, 3],
       [6, 6]])
</code>```

If you are dealing with python arrays and specially short arrays you can just use a list comprehension like following:

```<code>In [204]: [i for i in arr1 + arr2 if not (i in arr1 and i in arr2)]
Out[204]: [[1, 2], [3, 5], [2, 3], [6, 6]]
</code>```

Note that its faster than converting the lists to tuple and using set for short arrays bit for larger arrays the set based approach takes the cake, which in that case it's still better to use Numpy:

```<code>In [209]: %timeit set(map(tuple, arr1)).symmetric_difference(map(tuple, arr2))
100000 loops, best of 3: 1.51 µs per loop

In [210]: %timeit [i for i in arr1 + arr2 if not (i in arr1 and i in arr2)]
1000000 loops, best of 3: 1.28 µs per loop
</code>```

Title: Comparing 2 arrays for equal elements and deleting the entries from both arrays

Body:
If only items in same index can be similar you can use a simply numpythonic approach like following:

In [10]: mask = ~(arr1 == arr2).all(1)

In [11]: np.vstack((arr1[mask], arr2[mask]))
Out[11]:
array([[1, 2],
       [3, 5],
       [2, 3],
       [6, 6]])

Otherwise you can find the intersections based on Jaime's answer then exclude them from combined array.

Or use following approach:

In [17]: arr1_view = arr1.view([('', arr1.dtype)] * arr1.shape[1])

In [18]: arr2_view = arr2.view([('', arr2.dtype)] * arr2.shape[1])

In [19]: diff_arr1 = np.setdiff1d(arr1_view, arr2_view).view(arr1.dtype).reshape(-1, arr1.shape[1])

In [20]: diff_arr2 = np.setdiff1d(arr2_view, arr1_view).view(arr2.dtype).reshape(-1, arr2.shape[1])

In [21]: np.vstack((diff_arr1, diff_arr2))
Out[21]:
array([[1, 2],
       [3, 5],
       [2, 3],
       [6, 6]])

If you are dealing with python arrays and specially short arrays you can just use a list comprehension like following:

In [204]: [i for i in arr1 + arr2 if not (i in arr1 and i in arr2)]
Out[204]: [[1, 2], [3, 5], [2, 3], [6, 6]]

Note that its faster than converting the lists to tuple and using set for short arrays bit for larger arrays the set based approach takes the cake, which in that case it's still better to use Numpy:

In [209]: %timeit set(map(tuple, arr1)).symmetric_difference(map(tuple, arr2))
100000 loops, best of 3: 1.51 µs per loop

In [210]: %timeit [i for i in arr1 + arr2 if not (i in arr1 and i in arr2)]
1000000 loops, best of 3: 1.28 µs per loop


问:
variable doesn't increase when code is executed
Tester is called and executed if the player inputs a certain name.

Variable testerWrong doesnt add one when testerWrong++ is executed

```<code>private void Tester(){

    int testerTotal;
    int testerScore;
    int testerWrong;
    testerTotal = 0;
    testerScore = 0;
    testerWrong = 0;

    System.out.println("");
    System.out.println("Hello tester, you're the designated tester. Would you like to take the quiz? Y/N");
    Scanner yesno = new Scanner(System.in);
    String YesNo = yesno.next();
    if(YesNo.equals("Y") || YesNo.equals("y")){                 //This type of code will appear very often
        System.out.println("Okay, let's being!");       //if the user input (YesNo) is Y or y then...
    }else{
        if(YesNo.equals("N") || YesNo.equals("n")){
            System.out.println("Okay, maybe some other time");
        }else{                                                  //else...
            System.out.println("Sorry, i do not recognise what you entered. Please restart the program.");
        }
    }
    System.out.println("");
    QUIZ enter = new QUIZ();
    enter.e2c();
    System.out.println("");
    System.out.println("");
    System.out.println("");
    System.out.println("Question #1");
    System.out.println("");
    System.out.println("The answer is A");
    System.out.println("");
    System.out.println(" - A. ");
    System.out.println(" - B. ");
    System.out.println(" - C. ");
    System.out.println(" - D. ");
    Scanner testerQ1 = new Scanner(System.in);
    String TesterQ1 = testerQ1.next();
    if(TesterQ1.equals("A") || TesterQ1.equals("a")){
        testerScore++;
        System.out.println("Correct! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
        System.out.println("");
        System.out.println("Next Question.");
        System.out.println("");
    }else{
        testerWrong++;
        System.out.println("Incorrect! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
        System.out.println("");
    }
</code>```

Is there a way to make the variable execute without having to add a system output before it?

Thanks

答:
This is not a minimal (way too many print statements) or even complete example (the QUIZ class is not included).

Narrowing your code down to a minimum example:

```<code>import java.util.Scanner;

public class Tester {
    public static void main(String args[]) {
        int testerScore = 0;
        int testerWrong = 0;

        System.out.println("The answer is A");
        Scanner scanner = new Scanner(System.in);
        String answer = scanner.next();
        if (answer.equals("A") || answer.equals("a")) {
            testerScore++;
            System.out.print("Correct!");
        }
        else {
            testerWrong++;
            System.out.println("Incorrect! ");
        }
        System.out.println(" You hve answered " + testerScore +
            " correct and " + testerWrong + " incorrect!");
    }
}
</code>```

This works for me. Compare your code against this and see what you are doing differently.

If you cannot find the problem that way, run your code in a debugger. Step through the program to see what it does when.

You may also want to follow Java naming conventions (variables start with lower case letters, classes start with upper case letters but aren't all upper case), to make it easier for others to read your code.

Body:
Tester is called and executed if the player inputs a certain name.

Variable testerWrong doesnt add one when testerWrong++ is executed

private void Tester(){

    int testerTotal;
    int testerScore;
    int testerWrong;
    testerTotal = 0;
    testerScore = 0;
    testerWrong = 0;

    System.out.println("");
    System.out.println("Hello tester, you're the designated tester. Would you like to take the quiz? Y/N");
    Scanner yesno = new Scanner(System.in);
    String YesNo = yesno.next();
    if(YesNo.equals("Y") || YesNo.equals("y")){                 //This type of code will appear very often
        System.out.println("Okay, let's being!");       //if the user input (YesNo) is Y or y then...
    }else{
        if(YesNo.equals("N") || YesNo.equals("n")){
            System.out.println("Okay, maybe some other time");
        }else{                                                  //else...
            System.out.println("Sorry, i do not recognise what you entered. Please restart the program.");
        }
    }
    System.out.println("");
    QUIZ enter = new QUIZ();
    enter.e2c();
    System.out.println("");
    System.out.println("");
    System.out.println("");
    System.out.println("Question #1");
    System.out.println("");
    System.out.println("The answer is A");
    System.out.println("");
    System.out.println(" - A. ");
    System.out.println(" - B. ");
    System.out.println(" - C. ");
    System.out.println(" - D. ");
    Scanner testerQ1 = new Scanner(System.in);
    String TesterQ1 = testerQ1.next();
    if(TesterQ1.equals("A") || TesterQ1.equals("a")){
        testerScore++;
        System.out.println("Correct! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
        System.out.println("");
        System.out.println("Next Question.");
        System.out.println("");
    }else{
        testerWrong++;
        System.out.println("Incorrect! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
        System.out.println("");
    }

Is there a way to make the variable execute without having to add a system output before it?

Thanks

Body:
This is not a minimal (way too many print statements) or even complete example (the QUIZ class is not included).

Narrowing your code down to a minimum example:

import java.util.Scanner;

public class Tester {
    public static void main(String args[]) {
        int testerScore = 0;
        int testerWrong = 0;

        System.out.println("The answer is A");
        Scanner scanner = new Scanner(System.in);
        String answer = scanner.next();
        if (answer.equals("A") || answer.equals("a")) {
            testerScore++;
            System.out.print("Correct!");
        }
        else {
            testerWrong++;
            System.out.println("Incorrect! ");
        }
        System.out.println(" You hve answered " + testerScore +
            " correct and " + testerWrong + " incorrect!");
    }
}

This works for me. Compare your code against this and see what you are doing differently.

If you cannot find the problem that way, run your code in a debugger. Step through the program to see what it does when.

You may also want to follow Java naming conventions (variables start with lower case letters, classes start with upper case letters but aren't all upper case), to make it easier for others to read your code.


问:
(Android App/Web App) (Noob) How do I get started on making an app like this?
Ok so first off: I am a complete noob when it comes to Android app development. I used to have Android studio and wanted to make an app. I found it very confusing and hard to learn.

Second: I know HTML and CSS pretty well, but not JS or XML or any other languages.

I want to make an app that is basically a vault. When you open it, you get a login screen (with fingerprint login preferred). Then you login and are presented with a vault to store images, files, and etc.

I have no clue where to get started or what to learn. I want to learn how, but it seems very confusing to me.

I could also make this a web app so which ever is easier, let me know.

Thanks for the help!

答:
What I suggest is you start with very small projects. In each one, aim to make something you haven't tried before (don't be repetitive in your apps). I suggest you make the following apps, so in each one you learn a little about what shall be useful:

+/- Calculator

Application which asks for a password, and if correct, sends you to a second activity

Application which can save information even if the application is closed

Application which can shows a series of images one below another
(scrolling down)

This will get you a nice idea on Android Basics which will be useful for your project. If you were to jump directly into it, you would find yourself in a sea of abstract information and have no idea what to do.

Remember: small projects give you better understanding. Google and StackOverflow are your best friends


问:
Paper.js doesn't draw multiple shapes
I'm totally new to JavaScript, so I'm asking for help. I'm trying to create a simple Solar system simulation which is represented as several small circles (planets) moving around one big circle (Sun). I use Paper.js to create animations.

I created two classes: Star and Planet. Star class has draw() method which draws the star, and Planet class has motion() method which makes a planet move.

The problem is that when I create several objects and call their draw()/motion() methods, and then try to run script, the last object I created is the only one to be drawn/animated.

For instance, in this code:

```<code>var sun = new Star("Sun", 400, 400, 50, '#fff250');
sun.draw();

var earth = new Planet("Earth", sun, 100, 10, 1.5, '#b6f7ff');
earth.motion();

var mars = new Planet("Mars", sun, 200, 10, 0.5, '#ff9485');
mars.motion();
</code>```

mars.motion() will work just fine, but two other methods are just ignored. If I remove this method, The Earth will appear and so on.

Here is full code:

function Star(name, xCoordinate, yCoordinate, radius, color) {
    this.name = name;
    this.xCoordinate = xCoordinate;
    this.yCoordinate = yCoordinate;
    this.radius = radius;
    this.color = color;

    var canvas = document.getElementById("canvas1");
    paper.setup(canvas);

    this.draw = function () {

        var circle = new paper.Path.Circle(new paper.Point(xCoordinate, yCoordinate), radius);
        circle.fillColor = color;
    }

}

function Planet(name, parentStar, distanceFromStar, radius, period, color) {
    this.name = name;
    this.parentStar = parentStar;
    this.distanceFromStar = distanceFromStar;
    this.radius = radius;
    this.period = period;
    this.color = color;

    var xCoordinate = parentStar.xCoordinate + distanceFromStar;
    var yCoordinate = parentStar.yCoordinate + distanceFromStar;

    var canvas = document.getElementById("canvas1");
    paper.setup(canvas);

    this.motion = function () {

        var circle = new paper.Path.Circle(new paper.Point(xCoordinate, yCoordinate), radius);
        circle.fillColor = color;

        paper.view.onFrame = function (event) {

            circle.position.x = parentStar.xCoordinate - distanceFromStar * Math.cos(period * event.time);
            circle.position.y = parentStar.yCoordinate - distanceFromStar * Math.sin(period * event.time);
        }

    }
}

window.onload = function() {
    var sun = new Star("Sun", 400, 400, 50, '#fff250');
    sun.draw();

    var earth = new Planet("Earth", sun, 100, 10, 1.5, '#b6f7ff');
    earth.motion();

    var mars = new Planet("Mars", sun, 200, 10, 0.5, '#ff9485');
    mars.motion();

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="paper-core.js"></script>
    <script src="solar-system.js"></script>
</head>
<body>
<canvas id="canvas1" resize="" style="user-select: none; touch-action: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);" width="800" height="800" ></canvas>
</body>
</html></code>```

I think that the possible reason is that I do this

```<code>var canvas = document.getElementById("canvas1");
paper.setup(canvas);
</code>```

every time I create a new object, but I'm not sure about it. Please help. Thank you in advance.

答:
You are correct in your assumption of the problem.

You are setting up the whole canvas each time you draw an element.

You only need to set it up once (just removed the setup from the draw methods and added it to the window.onload).

Another issue is that you are assigning each planets update code as the  paper.view.onFrame. But it can only contain a single function. For this i have create a list in which the update functions of each planet go and then in the paper.view.onFrame i iterate over the array and execute each planets function.

Here is your code with the changes

var planetList = [];

function Star(name, xCoordinate, yCoordinate, radius, color, canvas) {
  this.name = name;
  this.xCoordinate = xCoordinate;
  this.yCoordinate = yCoordinate;
  this.radius = radius;
  this.color = color;

  this.draw = function() {

    var circle = new paper.Path.Circle(new paper.Point(xCoordinate, yCoordinate), radius);
    circle.fillColor = color;
  }

}

function Planet(name, parentStar, distanceFromStar, radius, period, color, canvas) {
  this.name = name;
  this.parentStar = parentStar;
  this.distanceFromStar = distanceFromStar;
  this.radius = radius;
  this.period = period;
  this.color = color;

  var xCoordinate = parentStar.xCoordinate + distanceFromStar;
  var yCoordinate = parentStar.yCoordinate + distanceFromStar;

  this.motion = function() {

    var circle = new paper.Path.Circle(new paper.Point(xCoordinate, yCoordinate), radius);
    circle.fillColor = color;
    planetList.push( function(event) {

      circle.position.x = parentStar.xCoordinate - distanceFromStar * Math.cos(period * event.time);
      circle.position.y = parentStar.yCoordinate - distanceFromStar * Math.sin(period * event.time);
    });
  }
}

window.onload = function() {
  var canvas = document.getElementById("canvas1");
  paper.setup(canvas);

  var sun = new Star("Sun", 400, 400, 50, '#fff250', );
  sun.draw();

  var earth = new Planet("Earth", sun, 100, 10, 1.5, '#b6f7ff');
  earth.motion();

  var mars = new Planet("Mars", sun, 200, 10, 0.5, '#ff9485');
  mars.motion();

  paper.view.onFrame = function(event){
    var pLen = planetList.length,
        p;
    for (p=0;p<pLen;p++){
      planetList[p](event);
    }
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.10.3/paper-full.min.js"></script>
</head>

<body>
  <canvas id="canvas1" resize="" style="user-select: none; touch-action: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);" width="800" height="800"></canvas>
</body>

</html></code>```

Title: Paper.js doesn't draw multiple shapes

Body:
I'm totally new to JavaScript, so I'm asking for help. I'm trying to create a simple Solar system simulation which is represented as several small circles (planets) moving around one big circle (Sun). I use Paper.js to create animations.

I created two classes: Star and Planet. Star class has draw() method which draws the star, and Planet class has motion() method which makes a planet move.

The problem is that when I create several objects and call their draw()/motion() methods, and then try to run script, the last object I created is the only one to be drawn/animated.

For instance, in this code:

var sun = new Star("Sun", 400, 400, 50, '#fff250');
sun.draw();

var earth = new Planet("Earth", sun, 100, 10, 1.5, '#b6f7ff');
earth.motion();

var mars = new Planet("Mars", sun, 200, 10, 0.5, '#ff9485');
mars.motion();

mars.motion() will work just fine, but two other methods are just ignored. If I remove this method, The Earth will appear and so on.

Here is full code:

function Star(name, xCoordinate, yCoordinate, radius, color) {
    this.name = name;
    this.xCoordinate = xCoordinate;
    this.yCoordinate = yCoordinate;
    this.radius = radius;
    this.color = color;

    var canvas = document.getElementById("canvas1");
    paper.setup(canvas);

    this.draw = function () {

        var circle = new paper.Path.Circle(new paper.Point(xCoordinate, yCoordinate), radius);
        circle.fillColor = color;
    }

}

function Planet(name, parentStar, distanceFromStar, radius, period, color) {
    this.name = name;
    this.parentStar = parentStar;
    this.distanceFromStar = distanceFromStar;
    this.radius = radius;
    this.period = period;
    this.color = color;

    var xCoordinate = parentStar.xCoordinate + distanceFromStar;
    var yCoordinate = parentStar.yCoordinate + distanceFromStar;

    var canvas = document.getElementById("canvas1");
    paper.setup(canvas);

    this.motion = function () {

        var circle = new paper.Path.Circle(new paper.Point(xCoordinate, yCoordinate), radius);
        circle.fillColor = color;

        paper.view.onFrame = function (event) {

            circle.position.x = parentStar.xCoordinate - distanceFromStar * Math.cos(period * event.time);
            circle.position.y = parentStar.yCoordinate - distanceFromStar * Math.sin(period * event.time);
        }

    }
}

window.onload = function() {
    var sun = new Star("Sun", 400, 400, 50, '#fff250');
    sun.draw();

    var earth = new Planet("Earth", sun, 100, 10, 1.5, '#b6f7ff');
    earth.motion();

    var mars = new Planet("Mars", sun, 200, 10, 0.5, '#ff9485');
    mars.motion();

}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

<canvas id="canvas1" resize="" style="user-select: none; touch-action: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);" width="800" height="800" ></canvas>

I think that the possible reason is that I do this

var canvas = document.getElementById("canvas1");
paper.setup(canvas);

every time I create a new object, but I'm not sure about it. Please help. Thank you in advance.

Body:
You are correct in your assumption of the problem.

You are setting up the whole canvas each time you draw an element.

You only need to set it up once (just removed the setup from the draw methods and added it to the window.onload).

Another issue is that you are assigning each planets update code as the  paper.view.onFrame. But it can only contain a single function. For this i have create a list in which the update functions of each planet go and then in the paper.view.onFrame i iterate over the array and execute each planets function.

Here is your code with the changes

var planetList = [];

function Star(name, xCoordinate, yCoordinate, radius, color, canvas) {
  this.name = name;
  this.xCoordinate = xCoordinate;
  this.yCoordinate = yCoordinate;
  this.radius = radius;
  this.color = color;

  this.draw = function() {

    var circle = new paper.Path.Circle(new paper.Point(xCoordinate, yCoordinate), radius);
    circle.fillColor = color;
  }

}

function Planet(name, parentStar, distanceFromStar, radius, period, color, canvas) {
  this.name = name;
  this.parentStar = parentStar;
  this.distanceFromStar = distanceFromStar;
  this.radius = radius;
  this.period = period;
  this.color = color;

  var xCoordinate = parentStar.xCoordinate + distanceFromStar;
  var yCoordinate = parentStar.yCoordinate + distanceFromStar;

  this.motion = function() {

    var circle = new paper.Path.Circle(new paper.Point(xCoordinate, yCoordinate), radius);
    circle.fillColor = color;
    planetList.push( function(event) {

      circle.position.x = parentStar.xCoordinate - distanceFromStar * Math.cos(period * event.time);
      circle.position.y = parentStar.yCoordinate - distanceFromStar * Math.sin(period * event.time);
    });
  }
}

window.onload = function() {
  var canvas = document.getElementById("canvas1");
  paper.setup(canvas);

  var sun = new Star("Sun", 400, 400, 50, '#fff250', );
  sun.draw();

  var earth = new Planet("Earth", sun, 100, 10, 1.5, '#b6f7ff');
  earth.motion();

  var mars = new Planet("Mars", sun, 200, 10, 0.5, '#ff9485');
  mars.motion();

  paper.view.onFrame = function(event){
    var pLen = planetList.length,
        p;
    for (p=0;p<pLen;p++){
      planetList[p](event);
    }
  }

}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.10.3/paper-full.min.js"></script>
</head>

<body>
  <canvas id="canvas1" resize="" style="user-select: none; touch-action: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);" width="800" height="800"></canvas>
</body>

</html>


问:
EJB3 Entities - Join on Entities in different jar files
I am trying to do a join on 2 entities using the following query -

```<code>String qry = "SELECT o.attr1, o.attr2, o.attr3, r.description FROM AttrEntity o,  DescEntity r WHERE (o.code=r.code)";
Query query = entityManager.createQuery(qry);
resultList = query.getResultList();
</code>```

The problem is that the AttrEntity and DescEnity are in different jar files so when I execute the query I get an exception saying that the entity DescEntity was not found. Is there anyway I can execute a this query while not modifying my jar files?

答:
You probably defined a persistence unit in one of those jars (the containing AttrEntity probably). In that persistence unit, you may have listed the classes belonging to that PU. Not sure this is even allowed by the spec, but you may try to change the MANIFEST.MF for the jar containing the PU, adding a "classpath" entry pointing to the other jar containing DescEntity. </p>

<p>But really, if that works, consider it as an UGLY workaround. The proper solution would be to keep them in the same jar. </p>

Body:
I am trying to do a join on 2 entities using the following query -

String qry = "SELECT o.attr1, o.attr2, o.attr3, r.description FROM AttrEntity o,  DescEntity r WHERE (o.code=r.code)";
Query query = entityManager.createQuery(qry);
resultList = query.getResultList();

The problem is that the AttrEntity and DescEnity are in different jar files so when I execute the query I get an exception saying that the entity DescEntity was not found. Is there anyway I can execute a this query while not modifying my jar files?

Body:
You probably defined a persistence unit in one of those jars (the containing AttrEntity probably). In that persistence unit, you may have listed the classes belonging to that PU. Not sure this is even allowed by the spec, but you may try to change the MANIFEST.MF for the jar containing the PU, adding a "classpath" entry pointing to the other jar containing DescEntity.

But really, if that works, consider it as an UGLY workaround. The proper solution would be to keep them in the same jar.


问:
How to recursively remove the caret (^) character recursively in all files in a directory?
I wish to remove all caret characters from all files present in the current directory. Please help.</p>

答:
You must tell sed to edit the file in place by specifying the the -i option, otherwise sed will write to its stdout.
You're not passing any file names to sed. Use {} syntax of find to pass matched file names.

```<code>find . -type f -exec sed -i 's/\^//g' {} +
</code>```

Please note that to replace matched patterns with nothing, you must leave the replace part of the substitution empty.

Body:
You must tell sed to edit the file in place by specifying the the -i option, otherwise sed will write to its stdout.
You're not passing any file names to sed. Use {} syntax of find to pass matched file names.

find . -type f -exec sed -i 's/\^//g' {} +

Please note that to replace matched patterns with nothing, you must leave the replace part of the substitution empty.


问:
Forming new object with array of objects
From the object 1, I am trying to form another object 2. I have written this below piece of code but I dono is this the right approach to achieve object 2.

```<code>var arr = [];
    object1.filter(function(value) {
                                return value.hasOwnProperty("This Year"); // Get only elements, which have such a key
                                    }).map(function(value) {
                                arr.push({value:value["This Year"]}); // Extract the values only
                                    });
</code>```

Object 1

```<code>var obj=[
  {
    "sno": 1,
    "Last Year": 10000
  },
  {
    "sno": 2,
    "Last Year": 11500
  },
  {
    "sno": 3,
    "Last Year": 12500
  },
  {
    "sno": 4,
    "This Year": 25400
  },
  {
    "sno": 5,
    "Last Year": 15000
  },
  {
    "sno": 6,
    "This Year": 29800
  }
]
</code>```

Object 2 - Desired Result

```<code>var dataset = [
        {
            "seriesname": "Last Year",
            "data": [
                {
                    "value": "10000"
                },
                {
                    "value": "11500"
                },
                {
                    "value": "12500"
                },
                {
                    "value": "15000"
                }
            ]
        },
        {
            "seriesname": "This Year",
            "data": [
                {
                    "value": "25400"
                },
                {
                    "value": "29800"
                }
            ]
        }
    ]
</code>```

If anyone can help me with better approach. In my code I am hard coding the key name of object 1. Is it possible in any other way?

答:
```<code>var obj1 = [
  {
    "sno": 1,
    "Last Year": 10000
  },
  {
    "sno": 2,
    "Last Year": 11500
  },
  {
    "sno": 3,
    "Last Year": 12500
  },
  {
    "sno": 4,
    "This Year": 25400
  },
  {
    "sno": 5,
    "Last Year": 15000
  },
  {
    "sno": 6,
    "This Year": 29800
  }
];

var dataset = [];

["This Year", "Last Year"].forEach((series) => {
    dataset.push({
        seriesname: series,
        data: obj1.filter((el) => {
                return el[series];
            }).map((el) => {
                return {
                    value: el[series]
                }
            })
        });
});

console.log(JSON.stringify(dataset, null, 2));
</code>```

Body:
From the object 1, I am trying to form another object 2. I have written this below piece of code but I dono is this the right approach to achieve object 2.

var arr = [];
    object1.filter(function(value) {
                                return value.hasOwnProperty("This Year"); // Get only elements, which have such a key
                                    }).map(function(value) {
                                arr.push({value:value["This Year"]}); // Extract the values only
                                    });

Object 1

var obj=[
  {
    "sno": 1,
    "Last Year": 10000
  },
  {
    "sno": 2,
    "Last Year": 11500
  },
  {
    "sno": 3,
    "Last Year": 12500
  },
  {
    "sno": 4,
    "This Year": 25400
  },
  {
    "sno": 5,
    "Last Year": 15000
  },
  {
    "sno": 6,
    "This Year": 29800
  }
]

Object 2 - Desired Result

var dataset = [
        {
            "seriesname": "Last Year",
            "data": [
                {
                    "value": "10000"
                },
                {
                    "value": "11500"
                },
                {
                    "value": "12500"
                },
                {
                    "value": "15000"
                }
            ]
        },
        {
            "seriesname": "This Year",
            "data": [
                {
                    "value": "25400"
                },
                {
                    "value": "29800"
                }
            ]
        }
    ]

If anyone can help me with better approach. In my code I am hard coding the key name of object 1. Is it possible in any other way?


问:
FBSDK swift 3 with 53 errors
I'm trying to download Facebook's sdk on Cocoapods following the instructions in the README
https://github.com/facebook/facebook-sdk-swift

I downloaded Cocoapods, inserted

```<code>pod 'FacebookCore'
pod 'FacebookLogin'
pod 'FacebookShare'
</code>```

into my Podfile, executed pod install and opened my xcworkspace. But when I run my app I get 53 error messages like

```<code>"Function types cannot have argument label 'bytesSent'; use'_' instead"
</code>```

I could try manually fixing these errors but is this supposed to happen?

I'm using Swift 3

答: Try clean and re-build the project or refactor it to the newest Swift syntax again. This seems to be a bug in the newest Xcode release (I exprerienced it in the previous version though).</p>

Title: FBSDK swift 3 with 53 errors

Body:
I'm trying to download Facebook's sdk on Cocoapods following the instructions in the README
https://github.com/facebook/facebook-sdk-swift

I downloaded Cocoapods, inserted

pod 'FacebookCore'
pod 'FacebookLogin'
pod 'FacebookShare'

into my Podfile, executed pod install and opened my xcworkspace. But when I run my app I get 53 error messages like

"Function types cannot have argument label 'bytesSent'; use'_' instead"

I could try manually fixing these errors but is this supposed to happen?

I'm using Swift 3


问:
Merge continuous 15-min time series dataset with discontinuous 15-min time series dataset
Pretty new to R, I appreciate any help you can give me on this issue.

I have two 15-min time series datasets that I would like to merge.  I would like to then plot a combination of variables from this merged dataset on a common x-axis. Here’s the catch, one of the datasets is missing values/dates.  Let’s call the datasets A and B.

A has a date-time column formatted as posixlt and 14 numeric variables (related to water quality).  Readings are at 15 minute intervals.  However, the time series is incomplete, some readings, due to equipment error are missing.
B also has a 15-minute interval date-time column formatted as posixlt and 1 numeric variable. However this series is continuous i.e. no missing data.

Here is a shortened example but the data covers about 6 months, with this problem repeated randomly throughout (notice data A is missing the 2:45 reading):

```<code>Temp Turb            DATETIME                 Q            DATETIME
1   21    5 2017-03-19 02:00:00             1 3 2017-03-19 02:00:00
2   15    5 2017-03-19 02:15:00             2 3 2017-03-19 02:15:00
3   18    5 2017-03-19 02:30:00             3 3 2017-03-19 02:30:00
4   17   17 2017-03-19 03:00:00             4 5 2017-03-19 02:45:00
5   18    5 2017-03-19 03:15:00             5 7 2017-03-19 03:00:00
6   17    5 2017-03-19 03:30:00             6 6 2017-03-19 03:15:00
7   17    6 2017-03-19 03:45:00             7 4 2017-03-19 03:30:00
                                            8 3 2017-03-19 03:45:00
</code>```

Here is the code for the shortened example.

```<code>A<- data.frame("DATE" =c("3/19/17","3/19/17","3/19/17","3/19/17",
                        "3/19/17","3/19/17","3/19/17"), "TIME"=c("02:00:00","02:15:00",
                         "02:30:00","03:00:00","03:15:00","03:30:00","03:45:00"),
                        "Temp" = c(21,15,18,17,18,17,17), "Turb" = c(5,5,5,17,5,5,6))
                          A$DATETIME <-paste(A$DATE,A$TIME)
                         A$DATETIME <- strptime(A$DATETIME, "%m/%d/%y %H:%M:%S")
                         A<-subset( A, select = -c(DATE,TIME) )
B <- data.frame("DATE" =c("3/19/17","3/19/17","3/19/17","3/19/17",
                        "3/19/17","3/19/17","3/19/17","3/19/17"), "TIME"=c("02:00:00","02:15:00",
                         "02:30:00","02:45:00","03:00:00","03:15:00","03:30:00","03:45:00"),
                         "Q" = c(3,3,3,5,7,6,4,3))
                          B$DATETIME <-paste(B$DATE,B$TIME)
                          B$DATETIME <- strptime(B$DATETIME, "%m/%d/%y %H:%M:%S")
                         B<-subset( B, select = -c(DATE,TIME) )
</code>```

I was hoping to use padr to fill in missing data in A with blanks so that the numeric variables from A and B could be interchangeably plotted with the time of A and B. Unfortunately 15 minutes is a nonstandard time interval for using padr. I have looked at stack overflow for examples and the closest I could find was here  but couldn’t make it work. It fleshed my dataset out to 1 minute data intervals but NA’s replaced all my numeric variables even at the 15-minute mark. Errors included statements such as DateTime variable was unsorted.

Any other recommendations or more specific guidance on the linked example? Thanks!!!

Body:
Pretty new to R, I appreciate any help you can give me on this issue.

I have two 15-min time series datasets that I would like to merge.  I would like to then plot a combination of variables from this merged dataset on a common x-axis. Here’s the catch, one of the datasets is missing values/dates.  Let’s call the datasets A and B.

A has a date-time column formatted as posixlt and 14 numeric variables (related to water quality).  Readings are at 15 minute intervals.  However, the time series is incomplete, some readings, due to equipment error are missing.
B also has a 15-minute interval date-time column formatted as posixlt and 1 numeric variable. However this series is continuous i.e. no missing data.

Here is a shortened example but the data covers about 6 months, with this problem repeated randomly throughout (notice data A is missing the 2:45 reading):

Temp Turb            DATETIME                 Q            DATETIME
1   21    5 2017-03-19 02:00:00             1 3 2017-03-19 02:00:00
2   15    5 2017-03-19 02:15:00             2 3 2017-03-19 02:15:00
3   18    5 2017-03-19 02:30:00             3 3 2017-03-19 02:30:00
4   17   17 2017-03-19 03:00:00             4 5 2017-03-19 02:45:00
5   18    5 2017-03-19 03:15:00             5 7 2017-03-19 03:00:00
6   17    5 2017-03-19 03:30:00             6 6 2017-03-19 03:15:00
7   17    6 2017-03-19 03:45:00             7 4 2017-03-19 03:30:00
                                            8 3 2017-03-19 03:45:00

Here is the code for the shortened example.

A<- data.frame("DATE" =c("3/19/17","3/19/17","3/19/17","3/19/17",
                        "3/19/17","3/19/17","3/19/17"), "TIME"=c("02:00:00","02:15:00",
                         "02:30:00","03:00:00","03:15:00","03:30:00","03:45:00"),
                        "Temp" = c(21,15,18,17,18,17,17), "Turb" = c(5,5,5,17,5,5,6))
                          A$DATETIME <-paste(A$DATE,A$TIME)
                         A$DATETIME <- strptime(A$DATETIME, "%m/%d/%y %H:%M:%S")
                         A<-subset( A, select = -c(DATE,TIME) )
B <- data.frame("DATE" =c("3/19/17","3/19/17","3/19/17","3/19/17",
                        "3/19/17","3/19/17","3/19/17","3/19/17"), "TIME"=c("02:00:00","02:15:00",
                         "02:30:00","02:45:00","03:00:00","03:15:00","03:30:00","03:45:00"),
                         "Q" = c(3,3,3,5,7,6,4,3))
                          B$DATETIME <-paste(B$DATE,B$TIME)
                          B$DATETIME <- strptime(B$DATETIME, "%m/%d/%y %H:%M:%S")
                         B<-subset( B, select = -c(DATE,TIME) )

I was hoping to use padr to fill in missing data in A with blanks so that the numeric variables from A and B could be interchangeably plotted with the time of A and B. Unfortunately 15 minutes is a nonstandard time interval for using padr. I have looked at stack overflow for examples and the closest I could find was here  but couldn’t make it work. It fleshed my dataset out to 1 minute data intervals but NA’s replaced all my numeric variables even at the 15-minute mark. Errors included statements such as DateTime variable was unsorted.

Any other recommendations or more specific guidance on the linked example? Thanks!!!

Body:
You can solve this with xts, but keep in mind that xts is like a matrix: it can only store one type of data. Also, you should use POSIXct instead of POSIXlt, unless you need to access the specific elements contained in POSIXlt objects.

require(xts)
a <- xts(A[,c("Temp","Turb")], as.POSIXct(A$DATETIME))
b <- xts(B["Q"], as.POSIXct(B$DATETIME))
(x <- merge(a, b))
#                     Temp Turb Q
# 2017-03-19 02:00:00   21    5 3
# 2017-03-19 02:15:00   15    5 3
# 2017-03-19 02:30:00   18    5 3
# 2017-03-19 02:45:00   NA   NA 5
# 2017-03-19 03:00:00   17   17 7
# 2017-03-19 03:15:00   18    5 6
# 2017-03-19 03:30:00   17    5 4
# 2017-03-19 03:45:00   17    6 3

If you want, you can convert the result back to a data.frame:

d <- data.frame(DATETIME=index(x), x)
# remove the rownames, if you want
rownames(d) <- NULL
print(d)
#              DATETIME Temp Turb Q
# 1 2017-03-19 02:00:00   21    5 3
# 2 2017-03-19 02:15:00   15    5 3
# 3 2017-03-19 02:30:00   18    5 3
# 4 2017-03-19 02:45:00   NA   NA 5
# 5 2017-03-19 03:00:00   17   17 7
# 6 2017-03-19 03:15:00   18    5 6
# 7 2017-03-19 03:30:00   17    5 4
# 8 2017-03-19 03:45:00   17    6 3


问:
Will Multi threading increase the speed of the calculation on Single Processor
On a single processor, Will multi-threading increse the speed of the calculation. As we all know that, multi-threading is used for Increasing the User responsiveness and achieved by sepating UI thread and calculation thread. But lets talk about only console application. Will multi-threading increases the speed of the calculation. Do we get culculation result faster when we calculate through multi-threading.

what about on multi cores, will multi threading increse the speed or not.

Please help me. If you have any material to learn more about threading. please post.

Edit:
I have been asked a question, At any given time, only one thread is allowed to run on a single core. If so, why people use multithreading in a console application.

Thanks in advance,
Harsha

答:
Treads don't increase performance. Threads sacrifice performance in favor of keeping parts of the code responsive.

The only exception is if you are doing a computation that is so parallelizeable that you can run different threads on different cores (which is the exception, not the rule).


问:
How to order sections in React Native ListView
I followed the example here to create a ListView with sections. In my case each section maps to a date and each item is a reminder with a time. How do I make sure that the sections and items will get rendered in chronological order?</p>

答: I got this to work by sorting the items first. Here's the code.</p>


问:
Define multiple things on a single selector
It's my code:

```<code>$('body').on('click', '.class1', function() {
    sth ...
});
</code>```

I wanna add these lines to my code:

```<code>$('body').on('click', '.class2', function() {
    some other things ...
});
</code>```

But it seems to be a wrong way to do ... And my IDE (pyCharm) says 'you shouldn't use duplicate jQuery selector'

What Can I Do Know ?

答:
There is nothing structurally wrong and your IDE is giving false alarms that are more performance oriented than related to code validity

To satisfy the IDE you could cache $('body') in a variable or chain multiple on()

```<code>var $body=$('body');

$body.on('click', '.class1', function(){...});
$body.on('click', '.class2', function(){...});
</code>```

Or

```<code>$('body').on('click', '.class1', function(){...})
         .on('click', '.class2', function(){...});
</code>```

Another approach is to use one click listener for multiple classes and use conditionals inside the handler

```<code>$('body').on('click', '.class1, .class2', function(){
  if($(this).hasClass('class1')){
     // do class 1 stuff
  }else{
   // do class 2 stuff
  }
});
</code>```

Body:
It's my code:

$('body').on('click', '.class1', function() {
    sth ...
});

I wanna add these lines to my code:

$('body').on('click', '.class2', function() {
    some other things ...
});

But it seems to be a wrong way to do ... And my IDE (pyCharm) says 'you shouldn't use duplicate jQuery selector'

What Can I Do Know ?

Body:
There is nothing structurally wrong and your IDE is giving false alarms that are more performance oriented than related to code validity

To satisfy the IDE you could cache $('body') in a variable or chain multiple on()

var $body=$('body');

$body.on('click', '.class1', function(){...});
$body.on('click', '.class2', function(){...});

Or

$('body').on('click', '.class1', function(){...})
         .on('click', '.class2', function(){...});

Another approach is to use one click listener for multiple classes and use conditionals inside the handler

$('body').on('click', '.class1, .class2', function(){
  if($(this).hasClass('class1')){
     // do class 1 stuff
  }else{
   // do class 2 stuff
  }
});


答:
You can chain .on calls, as they will act on the same selector:

```<code>$('body').on('click', '.class1', function() {
    sth ...
}).on('click', '.class2', function() {
    some other things ...
});
</code>```

That will silence pyCharm :-)

You could also solve it with one click hander, and make the distinction with an .is() call, although that could make your code less readable:

```<code>$('body').on('click', '.class1, .class2', function() {
    if ($(this).is('.class1')) {
        sth ...
    } else {
        some other things ...
    }
});
</code>```

Title: Define multiple things on a single selector

Body:
You can chain .on calls, as they will act on the same selector:

$('body').on('click', '.class1', function() {
    sth ...
}).on('click', '.class2', function() {
    some other things ...
});

That will silence pyCharm :-)

You could also solve it with one click hander, and make the distinction with an .is() call, although that could make your code less readable:

$('body').on('click', '.class1, .class2', function() {
    if ($(this).is('.class1')) {
        sth ...
    } else {
        some other things ...
    }
});


问:
Local Variable to Pointer to Cast
I have a relatively simple question, which I tried to keep as minimal as possible, but wanted to include an example so people would understand what I am referencing.

I have a function which declares a local variable (unsigned int), I then use a pointer to copy the value of that unsigned int to a pointer. I know that after that function ends, that local variable will no longer exist. The only thing that really matters to me is the value. I then try to pass it to func2() which has to have a void * as the argument (wasn't my choice) and just simply look at the value, which I think should be 2 since I added 1:

```<code>void func2( void * arg){
    //was not my choice to have void * be the argument.. was a requirment

    unsigned int val = *(unsigned int) arg;
    //When I print this the value should be 2..

}

void createPointer(){
  unsigned int localVariable = 1;
  localVariable = localVariable + 1;
  unsigned int *pointer = &localValue;
  *pointer = localValue;
  //my goal here is to copy the VALUE of the local variable
  //as I need this pointer to still point to this value after this function returns

  //in my actual code, this function is on a whole seperate file.. so it is really important that the pointer is stored in memory

func2( (void *) pointer );

}

int main(int argc, char *argv[]){
   createPointer();
}
</code>```

However, instead when I try to print that variable val in func2(), it just prints out some random address as text, which makes me assume it is somehow still referencing the localVariable, which I only wanted to copy the value of.

So, my question being is there a proper syntax way to copy the value of the local variable? Am I doing something wrong when I cast and uncast to void *?

答:
The problem appears to be here

```<code>unsigned int val = *(unsigned int) arg;
</code>```

which is ill formed and I would be very surprised if it compiles at all, but since you say the problem is the printed value is strange, I would assume that it is the reason, the correct way is

```<code>unsigned int val = *(unsigned int *) arg;
</code>```

which means, cast arg to an unsigned int pointer and dereference it.

There are a few things to mention about this

Whether or not the original value which you passed a pointer to is no longer valid after the caller returns is irrelevant, because if you call this sequentially func2() should return before the caller and thus the deallocation would occur after, so the value will be valid for the lifetime of func2().

The value inside the function, stored now in val lives in the stack frame of func2() and is a copy of the original value, but in a different memory location in principle.

If this function will execute in a different thread, you can't assume that you copied the value before the function that started the new thread returns, so you would need to store the value in the heap, like this

```<code>int *pointer;
pointer = malloc(sizeof pointer);
if (pointer == NULL) {
    handle_allocation_error();
} else {
    *pointer = value;
    func2(pointer);
    pointer = NULL; // Prevent having a dangling
                    // pointer
}
</code>```

and at some point in func2() you would need to free() the pointer.

In principle, this would work given that your sample code is not like your real code. Next time, include the actual code instead and if it's really too much, write a smaller version that would reproduce the problem. Sometimes, while you are writing such smaller version, you find out why the unexpected behavior is happening and you would not need to ask at all.

Also, you don't need (void *) in

```<code>func2((void *) pointer);
</code>```

just

```<code>func2(pointer);
</code>```

should compile fine.

Title: Local Variable to Pointer to Cast

Body:
I have a relatively simple question, which I tried to keep as minimal as possible, but wanted to include an example so people would understand what I am referencing.

I have a function which declares a local variable (unsigned int), I then use a pointer to copy the value of that unsigned int to a pointer. I know that after that function ends, that local variable will no longer exist. The only thing that really matters to me is the value. I then try to pass it to func2() which has to have a void * as the argument (wasn't my choice) and just simply look at the value, which I think should be 2 since I added 1:

void func2( void * arg){
    //was not my choice to have void * be the argument.. was a requirment

    unsigned int val = *(unsigned int) arg;
    //When I print this the value should be 2..

}

void createPointer(){
  unsigned int localVariable = 1;
  localVariable = localVariable + 1;
  unsigned int *pointer = &localValue;
  *pointer = localValue;
  //my goal here is to copy the VALUE of the local variable
  //as I need this pointer to still point to this value after this function returns

  //in my actual code, this function is on a whole seperate file.. so it is really important that the pointer is stored in memory

func2( (void *) pointer );

}

int main(int argc, char *argv[]){
   createPointer();
}

However, instead when I try to print that variable val in func2(), it just prints out some random address as text, which makes me assume it is somehow still referencing the localVariable, which I only wanted to copy the value of.

So, my question being is there a proper syntax way to copy the value of the local variable? Am I doing something wrong when I cast and uncast to void *?

Body:
The problem appears to be here

unsigned int val = *(unsigned int) arg;

which is ill formed and I would be very surprised if it compiles at all, but since you say the problem is the printed value is strange, I would assume that it is the reason, the correct way is

unsigned int val = *(unsigned int *) arg;

which means, cast arg to an unsigned int pointer and dereference it.

There are a few things to mention about this

Whether or not the original value which you passed a pointer to is no longer valid after the caller returns is irrelevant, because if you call this sequentially func2() should return before the caller and thus the deallocation would occur after, so the value will be valid for the lifetime of func2().

The value inside the function, stored now in val lives in the stack frame of func2() and is a copy of the original value, but in a different memory location in principle.

If this function will execute in a different thread, you can't assume that you copied the value before the function that started the new thread returns, so you would need to store the value in the heap, like this

int *pointer;
pointer = malloc(sizeof pointer);
if (pointer == NULL) {
    handle_allocation_error();
} else {
    *pointer = value;
    func2(pointer);
    pointer = NULL; // Prevent having a dangling
                    // pointer
}

and at some point in func2() you would need to free() the pointer.

In principle, this would work given that your sample code is not like your real code. Next time, include the actual code instead and if it's really too much, write a smaller version that would reproduce the problem. Sometimes, while you are writing such smaller version, you find out why the unexpected behavior is happening and you would not need to ask at all.

Also, you don't need (void *) in

func2((void *) pointer);

just

func2(pointer);

should compile fine.


问:
How can I use Scanner on switch case for String of array so that case takes in value from String b
How can I use Scanner class in "switch case" to determine the result;

Goal is to be able to use Scanner to determine the case. When user will input value in the scanner the select case will be able to use that String value (e.g if user type Mocking Bird in the Scanner it will be recognized in the switch case and out the code

```<code>    import java.util.Scanner;

    Scanner input = new Scanner(System.in);
    String b = input.next();

    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    for (int t = 0; t < Books.length; t++) {

      switch (Books[t]) {

        case "Harry Potter":
         System.out.println("Getting from switch case " + t + " " + Books[t]);
             break;

        case "To Kill a Mocking Bird"
         System.out.println("Getting from switch case " + t + " " + Books[t]);
              break;

        default:
            break;
        }
     }
</code>```

答:
You have to use equals() to check the identity of Strings.
Use </p>

```<code>   if (Books[0].equals(b)){
   ....
    }
   else  if (Books[1].equals(b)){
   ....
    }
</code>```

Body:
How can I use Scanner class in "switch case" to determine the result;

Goal is to be able to use Scanner to determine the case. When user will input value in the scanner the select case will be able to use that String value (e.g if user type Mocking Bird in the Scanner it will be recognized in the switch case and out the code

    import java.util.Scanner;

    Scanner input = new Scanner(System.in);
    String b = input.next();

    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    for (int t = 0; t < Books.length; t++) {

      switch (Books[t]) {

        case "Harry Potter":
         System.out.println("Getting from switch case " + t + " " + Books[t]);
             break;

        case "To Kill a Mocking Bird"
         System.out.println("Getting from switch case " + t + " " + Books[t]);
              break;

        default:
            break;
        }
     }

Body:
You have to use equals() to check the identity of Strings.
Use

   if (Books[0].equals(b)){
   ....
    }
   else  if (Books[1].equals(b)){
   ....
    }


问:
Microsoft Access 2007 & VBA & CSV and ...stuff
I have an assignment for work purpose which isn't really hard to do but I'm not a proficient access user so I, hereby, come to you guys :)

I'm about to write VBA code that is actually a custom CSV files loader. It's going to parse some files and insert their content in the appropriate tables.
My question is: What is the most appropriate way of creating this loader and triggering it?
I guess I have to create a VBA Module in my database project, but then what are the possiblities for the user to invoke the script and load the files ?
Like... is there any file system browser control that I can pop open and ask the user to choose a csv file then load it or whatever else ?

Thank you for your hints guys

Miloud B

答: Have a look at DoCmd.TransferText acImportDelim/acLinkDelim