问:
Fetch all Nuget dependencies from .csproj file as DLLs to a specified directory
Is there any way to fetch all Nuget dependencies from .csproj file as DLLs to a specified directory?</p>

答:
Is there any way to fetch all Nuget dependencies from .csproj file as DLLs to a specified directory?

Do you want to fetch dll files to a specified directory based on .csproj file? If yes, NuGet doesn't support this, but you can use other technologies to meet this requirement, like Power Shell.

To accomplish this, create a Power Shell scripts GetDllFiles.ps1 under the project file directory with following code:

```<code>$projectFiles = get-childitem . *.csproj -Recurse

foreach( $projectFile in $projectFiles )
{
    $projectXml = [xml] (get-content $projectFile.FullName)
    $projectDir = $projectFile.DirectoryName

    Write-Host "# $($projectFile.FullName) #"

    foreach( $itemGroup in $projectXml.Project.ItemGroup )
    {
        if( $itemGroup.Reference.Count -eq 0 )
        {
            continue
        }

        foreach( $reference in $itemGroup.Reference )
        {
            if( $reference.Include -eq $null )
            {
                continue
            }

            if( $reference.HintPath -eq $null )
            {
                Write-Host ("{0}" -f $reference.Include)
            }
            else
            {
                $fullpath = $reference.HintPath
                if(-not [System.IO.Path]::IsPathRooted( $fullpath ) )
                {
                    $fullPath = (join-path $projectDir $fullpath)
                    $fullPath = [System.IO.Path]::GetFullPath("$fullPath")
                }
                Write-Host $fullPath
                Copy-Item $fullPath D:\Test
            }
        }
    }

    Write-Host ''
    Start-Sleep –s 10
}
</code>```

This Power Shell scripts grabs every .csproj file under the current directory, and inspects each Reference. For assemblies referenced from the GAC, just the name is output. For assemblies outside the GAC, output the full path of the assemblies, then you can copy them to the specified directory.

Update for Comment:

but I want a bit different thing - to fetch all NuGet packages from .csproj and "unpack" them into a specified directory in order to have all DLLs that my application depends on.

If you want to fetch entire nuget packages to the specified directory instead of just the dll files, you can use a simple nuget command line to achieve it:

```<code>nuget restore "xx.csproj" -OutputDirectory "SpecifiedDirectoryPath"
</code>```

This command line will fetch entire nuget packages and unpack them into a specified directory.

Body:
Is there any way to fetch all Nuget dependencies from .csproj file as DLLs to a specified directory?

Do you want to fetch dll files to a specified directory based on .csproj file? If yes, NuGet doesn't support this, but you can use other technologies to meet this requirement, like Power Shell.

To accomplish this, create a Power Shell scripts GetDllFiles.ps1 under the project file directory with following code:

$projectFiles = get-childitem . *.csproj -Recurse

foreach( $projectFile in $projectFiles )
{
    $projectXml = [xml] (get-content $projectFile.FullName)
    $projectDir = $projectFile.DirectoryName

    Write-Host "# $($projectFile.FullName) #"

    foreach( $itemGroup in $projectXml.Project.ItemGroup )
    {
        if( $itemGroup.Reference.Count -eq 0 )
        {
            continue
        }

        foreach( $reference in $itemGroup.Reference )
        {
            if( $reference.Include -eq $null )
            {
                continue
            }

            if( $reference.HintPath -eq $null )
            {
                Write-Host ("{0}" -f $reference.Include)
            }
            else
            {
                $fullpath = $reference.HintPath
                if(-not [System.IO.Path]::IsPathRooted( $fullpath ) )
                {
                    $fullPath = (join-path $projectDir $fullpath)
                    $fullPath = [System.IO.Path]::GetFullPath("$fullPath")
                }
                Write-Host $fullPath
                Copy-Item $fullPath D:\Test
            }
        }
    }

    Write-Host ''
    Start-Sleep –s 10
}

This Power Shell scripts grabs every .csproj file under the current directory, and inspects each Reference. For assemblies referenced from the GAC, just the name is output. For assemblies outside the GAC, output the full path of the assemblies, then you can copy them to the specified directory.

Update for Comment:

but I want a bit different thing - to fetch all NuGet packages from .csproj and "unpack" them into a specified directory in order to have all DLLs that my application depends on.

If you want to fetch entire nuget packages to the specified directory instead of just the dll files, you can use a simple nuget command line to achieve it:

nuget restore "xx.csproj" -OutputDirectory "SpecifiedDirectoryPath"

This command line will fetch entire nuget packages and unpack them into a specified directory.


来源: stackexchange

问:
Names of constructors and destructors of templates
From n4459:

635. Names of constructors and destructors of templates

There is a discrepancy between the syntaxes allowed for defining a
  constructor and a destructor of a class template. For example:

```<code>template <class> struct S { S(); ~S (); };
template <class T> S<T>::S<T>() { }        // error
template <class T> S<T>::~S<T>() { }       // okay
</code>```

The reason for this is that 3.4.3.1 [class.qual] paragraph 2 says that
  S::S is “considered to name the constructor,” which is not a template and thus cannot accept a template argument list. On the
  other hand, the second S in S::~S finds the injected-class-name, which
  “can be used with or without a template-argument-list” (14.6.1
  [temp.local] paragraph 1) and thus satisfies the requirement to name
  the destructor's class (12.4 [class.dtor] paragraph 1).

I don't understand, What does say that S::S is “considered to name the constructor,” which is not a template?

答:
S::S is “considered to name the constructor,” which is not a template and thus cannot accept a template argument list

Yes, it is possibly because a constructor might be templated. So by preventing non-template constructor to not have S<T>::S<T> syntax, the language reserves this syntax for the templated constructor.

Here is an example:

```<code>template <typename T>
struct X
{
   template<typename U>
   X();
  ~X ();
};

template <typename T>
template <typename U>
X<T>::X<U>() { }        //OK now

template <class T>
X<T>::~X<T>() { }       // okay
</code>```

If the syntax S<T>::S<T>() was allowed, then in this case you would have to write X<T>::X<T>() — that is an ugly and a new syntax. So in a sense, by preventing this, the syntax is slightly cleaner and that also avoids introducing a new syntax.

On the other hand, the destructor can never be a template.

ContentLicense: CC BY-SA 3.0

Body:
From n4459:

635. Names of constructors and destructors of templates

There is a discrepancy between the syntaxes allowed for defining a
  constructor and a destructor of a class template. For example:

template <class> struct S { S(); ~S (); };
template <class T> S<T>::S<T>() { }        // error
template <class T> S<T>::~S<T>() { }       // okay

The reason for this is that 3.4.3.1 [class.qual] paragraph 2 says that
  S::S is “considered to name the constructor,” which is not a template and thus cannot accept a template argument list. On the
  other hand, the second S in S::~S finds the injected-class-name, which
  “can be used with or without a template-argument-list” (14.6.1
  [temp.local] paragraph 1) and thus satisfies the requirement to name
  the destructor's class (12.4 [class.dtor] paragraph 1).

I don't understand, What does say that S::S is “considered to name the constructor,” which is not a template?

Body:
S::S is “considered to name the constructor,” which is not a template and thus cannot accept a template argument list

Yes, it is possibly because a constructor might be templated. So by preventing non-template constructor to not have S<T>::S<T> syntax, the language reserves this syntax for the templated constructor.

Here is an example:

template <typename T>
struct X
{
   template<typename U>
   X();
  ~X ();
};

template <typename T>
template <typename U>
X<T>::X<U>() { }        //OK now

template <class T>
X<T>::~X<T>() { }       // okay

If the syntax S<T>::S<T>() was allowed, then in this case you would have to write X<T>::X<T><U>() — that is an ugly and a new syntax. So in a sense, by preventing this, the syntax is slightly cleaner and that also avoids introducing a new syntax.

On the other hand, the destructor can never be a template.


问:
Linux unity editor : unity-editor depends on npm; however: Package npm is not installed
I am trying to install the linux unity editor as posted here https://forum.unity.com/threads/unity-on-linux-release-notes-and-known-issues.350256/page-2
I got the latest nodejs package version v9.2.0 I can run the node , npm from console as a root. I added the path for node package to .bashrc file
However during the .deb installation, its failing to detect npm. Please see the log below. Request help on this issue.</p>

```<code> root@VirtualMazeLinux:/home/mkandula# dpkg -i ./Downloads/unity-editor_amd64-2017.2.0f3.deb
 Selecting previously unselected package unity-editor.
 (Reading database ... 189549 files and directories currently installed.)
 Preparing to unpack .../unity-editor_amd64-2017.2.0f3.deb ...
 Unpacking unity-editor (2017.2.0f3) ...
 dpkg: dependency problems prevent configuration of unity-editor:
  unity-editor depends on npm; however:
   Package npm is not installed.

 dpkg: error processing package unity-editor (--install):
  dependency problems - leaving unconfigured
 Processing triggers for gnome-menus (3.13.3-9) ...
 Processing triggers for desktop-file-utils (0.23-1) ...
 Processing triggers for mime-support (3.60) ...
 Processing triggers for hicolor-icon-theme (0.15-1) ...
 Errors were encountered while processing:
  unity-editor
 root@VirtualMazeLinux:/home/mkandula# node -v
 v9.2.0
 root@VirtualMazeLinux:/home/mkandula# npm -v
 5.5.1
 root@VirtualMazeLinux:/home/mkandula#
</code>```

答:
You can install NodeJS from repository of your distro:</p>

```<code>sudo apt-get install nodejs
sudo apt-get install npm
</code>```

Body:
I am trying to install the linux unity editor as posted here https://forum.unity.com/threads/unity-on-linux-release-notes-and-known-issues.350256/page-2
I got the latest nodejs package version v9.2.0 I can run the node , npm from console as a root. I added the path for node package to .bashrc file
However during the .deb installation, its failing to detect npm. Please see the log below. Request help on this issue.

 root@VirtualMazeLinux:/home/mkandula# dpkg -i ./Downloads/unity-editor_amd64-2017.2.0f3.deb
 Selecting previously unselected package unity-editor.
 (Reading database ... 189549 files and directories currently installed.)
 Preparing to unpack .../unity-editor_amd64-2017.2.0f3.deb ...
 Unpacking unity-editor (2017.2.0f3) ...
 dpkg: dependency problems prevent configuration of unity-editor:
  unity-editor depends on npm; however:
   Package npm is not installed.

 dpkg: error processing package unity-editor (--install):
  dependency problems - leaving unconfigured
 Processing triggers for gnome-menus (3.13.3-9) ...
 Processing triggers for desktop-file-utils (0.23-1) ...
 Processing triggers for mime-support (3.60) ...
 Processing triggers for hicolor-icon-theme (0.15-1) ...
 Errors were encountered while processing:
  unity-editor
 root@VirtualMazeLinux:/home/mkandula# node -v
 v9.2.0
 root@VirtualMazeLinux:/home/mkandula# npm -v
 5.5.1
 root@VirtualMazeLinux:/home/mkandula#

Body:
You can install NodeJS from repository of your distro:

sudo apt-get install nodejs
sudo apt-get install npm


问:
validation of email with specific domain
This coding on separate page works fine. but if i included in below form not working

<form id="signup" method="post">
    <input type="email" placeholder="Your e-mail." />
    <button>Submit</button>
</form>

```
</div>
</div>
</p>

<p><em>i have an registration page where  all fields are entered,it should check whether email id column should contain @c-e.com domain,if user entered abcd@c-e.com it should proceed or else should pop up a message like need to enter c-e.com domain name,for that i have written a script but for all email id's it is displaying message like not an valid email address.none of the part works.If i paste same code with form of email ,submit button alone in other page,it pops up message ,but in this register.php not works</em></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
session_start();

if(isset($_SESSION['usr_id'])) {
 header("Location: index.php");
}

include_once 'dbconnect.php';

//set validation error flag as false
$error = false;

//check if form is submitted
if (isset($_POST['signup'])) {
 $name = mysqli_real_escape_string($con, $_POST['name']);
 $email = mysqli_real_escape_string($con, $_POST['email']);
 $password = mysqli_real_escape_string($con, $_POST['password']);
 $cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);

 //name can contain only alpha characters and space
 if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
  $error = true;
  $name_error = "Name must contain only alphabets and space";
 }
 if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
  $error = true;
  $email_error = "Please Enter Valid Email ID";
 }
 if(strlen($password) < 6) {
  $error = true;
  $password_error = "Password must be minimum of 6 characters";
 }
 if($password != $cpassword) {
  $error = true;
  $cpassword_error = "Password and Confirm Password doesn't match";
 }
 if (!$error) {
  if(mysqli_query($con, "INSERT INTO users(name,email,password) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
   $successmsg = "Successfully Registered! Click here to Login";
  } else {
   $errormsg = "Error in registering...Please try again later!";
  }
 }
}
?>

<!DOCTYPE html>
<html>
<head>
 <title>User Registration Script</title>
 <meta content="width=device-width, initial-scale=1.0" name="viewport" >
 <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

 </head>
<body>
</br></br>

<div class="container">
 <div class="row">
  <div class="col-md-4 col-md-offset-4 well">
   <form role="form" id="signup" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
    <fieldset>
     <legend>Sign Up</legend>

     <div class="form-group">
      <label for="name">Name</label>
      <input type="text" name="name" placeholder="Enter Full Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
      <span class="text-danger"><?php if (isset($name_error)) echo $name_error; ?></span>
     </div>

     <div class="form-group">
      <label for="name">Email</label>
      <input type="email" name="email" placeholder="Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
      <span class="text-danger"><?php if (isset($email_error)) echo $email_error; ?></span>
     </div>

     <div class="form-group">
      <label for="name">Password</label>
      <input type="password" name="password" placeholder="Password" required class="form-control" />
      <span class="text-danger"><?php if (isset($password_error)) echo $password_error; ?></span>
     </div>

     <div class="form-group">
      <label for="name">Confirm Password</label>
      <input type="password" name="cpassword" placeholder="Confirm Password" required class="form-control" />
      <span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
     </div>

     <div class="form-group">
      <input type="submit" name="signup" value="Sign Up" class="btn btn-primary" />
     </div>
    </fieldset>
   </form>
   <span class="text-success"><?php if (isset($successmsg)) { echo $successmsg; } ?></span>
   <span class="text-danger"><?php if (isset($errormsg)) { echo $errormsg; } ?></span>
  </div>
 </div>
 <div class="row">
  <div class="col-md-4 col-md-offset-4 text-center">
  Already Registered? Login Here
  </div>
 </div>
</div>

<script type="text/javascript">

$('#signup').submit(function() {
    validateEmail($('input').val());
    return false;
});

function validateEmail(email) {
    var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    if (re.test(email)) {
        if (email.indexOf('@c-e.com', email.length - '@c-e.com'.length) !== -1) {
            alert('Submission was successful.');
        } else {
            alert('Email must be a CE e-mail address (your.name@c-e.com).');
        }
    } else {
        alert('Not a valid e-mail address.');
    }
}

</script>

<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html></code>```

答:
You can do this by following way :</p>

```<code>function validateEmail($email)
{
  // Check E-mail address is valid
  if (!preg_match('/^([a-z0-9\+\_\-\.]+)@([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) return false;
 // Check for specific domain(s)
  $SpecificDomains = array('c-e.com','gmail.com','example.com');
  list(, $email_domain) = explode('@', $email, 2);
  return !in_array($email_domain, $SpecificDomains);
}
</code>```

Body:
This coding on separate page works fine. but if i included in below form not working

<form id="signup" method="post">
    <input type="email" placeholder="Your e-mail." />
    <button>Submit</button>
</form>

i have an registration page where  all fields are entered,it should check whether email id column should contain @c-e.com domain,if user entered abcd@c-e.com it should proceed or else should pop up a message like need to enter c-e.com domain name,for that i have written a script but for all email id's it is displaying message like not an valid email address.none of the part works.If i paste same code with form of email ,submit button alone in other page,it pops up message ,but in this register.php not works

<?php
session_start();

if(isset($_SESSION['usr_id'])) {
 header("Location: index.php");
}

include_once 'dbconnect.php';

//set validation error flag as false
$error = false;

//check if form is submitted
if (isset($_POST['signup'])) {
 $name = mysqli_real_escape_string($con, $_POST['name']);
 $email = mysqli_real_escape_string($con, $_POST['email']);
 $password = mysqli_real_escape_string($con, $_POST['password']);
 $cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);

 //name can contain only alpha characters and space
 if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
  $error = true;
  $name_error = "Name must contain only alphabets and space";
 }
 if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
  $error = true;
  $email_error = "Please Enter Valid Email ID";
 }
 if(strlen($password) < 6) {
  $error = true;
  $password_error = "Password must be minimum of 6 characters";
 }
 if($password != $cpassword) {
  $error = true;
  $cpassword_error = "Password and Confirm Password doesn't match";
 }
 if (!$error) {
  if(mysqli_query($con, "INSERT INTO users(name,email,password) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
   $successmsg = "Successfully Registered! Click here to Login";
  } else {
   $errormsg = "Error in registering...Please try again later!";
  }
 }
}
?>

<!DOCTYPE html>

 <title>User Registration Script</title>
 <meta content="width=device-width, initial-scale=1.0" name="viewport" >
 <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />

   <form role="form" id="signup" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
    <fieldset>
     <legend>Sign Up</legend>

      Name
      <input type="text" name="name" placeholder="Enter Full Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
      <?php if (isset($name_error)) echo $name_error; ?>

      Email
      <input type="email" name="email" placeholder="Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
      <?php if (isset($email_error)) echo $email_error; ?>

      Password
      <input type="password" name="password" placeholder="Password" required class="form-control" />
      <?php if (isset($password_error)) echo $password_error; ?>

      Confirm Password
      <input type="password" name="cpassword" placeholder="Confirm Password" required class="form-control" />
      <?php if (isset($cpassword_error)) echo $cpassword_error; ?>

      <input type="submit" name="signup" value="Sign Up" class="btn btn-primary" />

    </fieldset>
   </form>
   <?php if (isset($successmsg)) { echo $successmsg; } ?>
   <?php if (isset($errormsg)) { echo $errormsg; } ?>

  Already Registered? Login Here

Body:
You can do this by following way :

function validateEmail($email)
{
  // Check E-mail address is valid
  if (!preg_match('/^([a-z0-9\+\_\-\.]+)@([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) return false;
 // Check for specific domain(s)
  $SpecificDomains = array('c-e.com','gmail.com','example.com');
  list(, $email_domain) = explode('@', $email, 2);
  return !in_array($email_domain, $SpecificDomains);
}


问:
c# : DLLImport for a particular dll not working, although an example app shows it working, How can i resolve this?
I am trying to import a dll using relative paths

```<code>private const string LzoDll32Bit = @"lib32\lzo_32.dll";

    #region Dll-Imports

    [DllImport(LzoDll32Bit, EntryPoint = "lzo_version_string")]
    private static extern IntPtr lzo_version_string32();
    [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_1_compress", CallingConvention = CallingConvention.Cdecl)]
    private static extern int lzo1x_1_compress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
    [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_decompress", CallingConvention = CallingConvention.Cdecl)]
    private static extern int lzo1x_decompress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
    [DllImport(LzoDll32Bit, EntryPoint = "__lzo_init_v2", CallingConvention = CallingConvention.Cdecl)]
    private static extern int __lzo_init_v2_32(uint v, int s1, int s2, int s3, int s4, int s5, int s6, int s7, int s8, int s9);

    #endregion
</code>```

{"Unable to load DLL 'lib32\lzo_32.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)"}

Now here is the weird thing,
http://wallaceturner.com/lzo-for-c, the link for the site where i downloaded a sample project to see how to work with the lzo compressor in c#.net.
And when i run the project it successfully works. I see no other dependencies apart from what i have in my project.
I am using .Net4.5.2 in both of them.

Here is my full source code for that class

```<code>using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace TradeAlgo
{
    public class LZOCompressor
    {
        private static TraceSwitch _traceSwitch = new TraceSwitch("Simplicit.Net.Lzo", "Switch for tracing of the LZOCompressor-Class");
        private const string LzoDll32Bit = @"lib32\lzo_32.dll";

        #region Dll-Imports

        [DllImport(LzoDll32Bit, EntryPoint = "lzo_version_string")]
        private static extern IntPtr lzo_version_string32();
        [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_1_compress", CallingConvention = CallingConvention.Cdecl)]
        private static extern int lzo1x_1_compress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
        [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_decompress", CallingConvention = CallingConvention.Cdecl)]
        private static extern int lzo1x_decompress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
        [DllImport(LzoDll32Bit, EntryPoint = "__lzo_init_v2", CallingConvention = CallingConvention.Cdecl)]
        private static extern int __lzo_init_v2_32(uint v, int s1, int s2, int s3, int s4, int s5, int s6, int s7, int s8, int s9);

        #endregion

        private byte[] _workMemory = new byte[16384L * 4];

        public LZOCompressor()
        {
            int init = 0;
            init = __lzo_init_v2_32(1, -1, -1, -1, -1, -1, -1, -1, -1, -1);

            if (init != 0)
            {
                throw new Exception("Initialization of LZO-Compressor failed !");
            }
        }

        public byte[] Compress(byte[] src)
        {
            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: trying to compress {0}", src.Length));
            }
            byte[] dst = new byte[src.Length + src.Length / 64 + 16 + 3 + 4];
            int outlen = 0;
            lzo1x_1_compress32(src, src.Length, dst, ref outlen, _workMemory);

            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: compressed {0} to {1} bytes", src.Length, outlen));
            }
            byte[] ret = new byte[outlen + 4];
            Array.Copy(dst, 0, ret, 0, outlen);
            byte[] outlenarr = BitConverter.GetBytes(src.Length);
            Array.Copy(outlenarr, 0, ret, outlen, 4);
            return ret;
        }

        public byte[] Decompress(byte[] src)
        {
            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: trying to decompress {0}", src.Length));
            }
            int origlen = BitConverter.ToInt32(src, src.Length - 4);
            byte[] dst = new byte[origlen];
            int outlen = origlen;
            lzo1x_decompress32(src, src.Length - 4, dst, ref outlen, _workMemory);

            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: decompressed {0} to {1} bytes", src.Length, origlen));
            }
            return dst;
        }
    }
}
</code>```

Please let me know if i am missing any details, would gladly provide anything required. Thanks.

答: I see the dll's are include in the project, make sure you set the dll's Properties for 'Copy To Output Directory' to 'Copy if newer'. Possibly they are not creating the folders with the dll's in them in your 'Release' folder.</p>

Body:
I am trying to import a dll using relative paths

private const string LzoDll32Bit = @"lib32\lzo_32.dll";

    #region Dll-Imports

    [DllImport(LzoDll32Bit, EntryPoint = "lzo_version_string")]
    private static extern IntPtr lzo_version_string32();
    [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_1_compress", CallingConvention = CallingConvention.Cdecl)]
    private static extern int lzo1x_1_compress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
    [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_decompress", CallingConvention = CallingConvention.Cdecl)]
    private static extern int lzo1x_decompress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
    [DllImport(LzoDll32Bit, EntryPoint = "__lzo_init_v2", CallingConvention = CallingConvention.Cdecl)]
    private static extern int __lzo_init_v2_32(uint v, int s1, int s2, int s3, int s4, int s5, int s6, int s7, int s8, int s9);

    #endregion

{"Unable to load DLL 'lib32\lzo_32.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)"}

Now here is the weird thing,
http://wallaceturner.com/lzo-for-c, the link for the site where i downloaded a sample project to see how to work with the lzo compressor in c#.net.
And when i run the project it successfully works. I see no other dependencies apart from what i have in my project.
I am using .Net4.5.2 in both of them.

Here is my full source code for that class

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace TradeAlgo
{
    public class LZOCompressor
    {
        private static TraceSwitch _traceSwitch = new TraceSwitch("Simplicit.Net.Lzo", "Switch for tracing of the LZOCompressor-Class");
        private const string LzoDll32Bit = @"lib32\lzo_32.dll";

        #region Dll-Imports

        [DllImport(LzoDll32Bit, EntryPoint = "lzo_version_string")]
        private static extern IntPtr lzo_version_string32();
        [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_1_compress", CallingConvention = CallingConvention.Cdecl)]
        private static extern int lzo1x_1_compress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
        [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_decompress", CallingConvention = CallingConvention.Cdecl)]
        private static extern int lzo1x_decompress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
        [DllImport(LzoDll32Bit, EntryPoint = "__lzo_init_v2", CallingConvention = CallingConvention.Cdecl)]
        private static extern int __lzo_init_v2_32(uint v, int s1, int s2, int s3, int s4, int s5, int s6, int s7, int s8, int s9);

        #endregion

        private byte[] _workMemory = new byte[16384L * 4];

        public LZOCompressor()
        {
            int init = 0;
            init = __lzo_init_v2_32(1, -1, -1, -1, -1, -1, -1, -1, -1, -1);

            if (init != 0)
            {
                throw new Exception("Initialization of LZO-Compressor failed !");
            }
        }

        public byte[] Compress(byte[] src)
        {
            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: trying to compress {0}", src.Length));
            }
            byte[] dst = new byte[src.Length + src.Length / 64 + 16 + 3 + 4];
            int outlen = 0;
            lzo1x_1_compress32(src, src.Length, dst, ref outlen, _workMemory);

            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: compressed {0} to {1} bytes", src.Length, outlen));
            }
            byte[] ret = new byte[outlen + 4];
            Array.Copy(dst, 0, ret, 0, outlen);
            byte[] outlenarr = BitConverter.GetBytes(src.Length);
            Array.Copy(outlenarr, 0, ret, outlen, 4);
            return ret;
        }

        public byte[] Decompress(byte[] src)
        {
            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: trying to decompress {0}", src.Length));
            }
            int origlen = BitConverter.ToInt32(src, src.Length - 4);
            byte[] dst = new byte[origlen];
            int outlen = origlen;
            lzo1x_decompress32(src, src.Length - 4, dst, ref outlen, _workMemory);

            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: decompressed {0} to {1} bytes", src.Length, origlen));
            }
            return dst;
        }
    }
}

Please let me know if i am missing any details, would gladly provide anything required. Thanks.


问:
android getting pictures from drawables
Bitmap picture = BitmapFactory.decodeResource(getResources(),R.drawable.phscale);

apart from above code any other ways to get the bitmap from drawables

答:
If you get your png name as string, you could use the following:

```<code>int resID = getResources().getIdentifier("bug", "drawable",   "org.anddev.android.testproject");
</code>```

source

Title: android getting pictures from drawables

Body:
If you get your png name as string, you could use the following:

int resID = getResources().getIdentifier("bug", "drawable",   "org.anddev.android.testproject");

source


问:
Using Jsoup to extract text from HTML, but returned left and right quotation mark chars
So I used Jsoup to extract some text from an html snippit, shown here:

```<code><font style="font-family:Times New Roman" size="2">BHI Finance LLC (“BHI Finance”)</font>
</code>```

Notice the left and right quotation marks. I store this text in a String in Java here:

```<code>Element firstEntry = row.select("td").first();
String toAdd = firstEntry.select("font").text();
</code>```

String toAdd gets printed as BHI Finance LLC (?BHI Finance?)

The two question mark chars when casted to an int are 147 and 148 respectively which I found to be left and right quotation marks on (certain?) html char encodings. My question is how do I make it so Jsoup parses left and right quotation marks as just regualar ascii quotation marks?

答:
Doesn't look like a parsing problem. More likely, whatever you're using to display the parsed content doesn't correctly display those characters.

The easiest is probably to just replace them:

```<code>toAdd = toAdd.replaceAll("[“”]", "\"");
</code>```

Body:
So I used Jsoup to extract some text from an html snippit, shown here:

BHI Finance LLC (“BHI Finance”)

Notice the left and right quotation marks. I store this text in a String in Java here:

Element firstEntry = row.select("td").first();
String toAdd = firstEntry.select("font").text();

String toAdd gets printed as BHI Finance LLC (?BHI Finance?)

The two question mark chars when casted to an int are 147 and 148 respectively which I found to be left and right quotation marks on (certain?) html char encodings. My question is how do I make it so Jsoup parses left and right quotation marks as just regualar ascii quotation marks?

Body:
Doesn't look like a parsing problem. More likely, whatever you're using to display the parsed content doesn't correctly display those characters.

The easiest is probably to just replace them:

toAdd = toAdd.replaceAll("[“”]", "\"");


问:
How to scrape the same url in loop with Scrapy
Needed content is located on the same page with a static URL.

I created a spider that scrapes this page and stores the items in CSV. But it does so only once and then finish the crawling process. But I need repeat the operation continuously. How can I do this?

Scrapy 0.12

Python 2.5

答:
I code this way:

```<code>def start_requests(self):
    while True:
        yield scrapy.Request(url, callback=self.parse, dont_filter=True)
</code>```

I have tried the way below, but there is a problem that when the Internet is unstable, It will stop and will break the loop.

```<code>from scrapy.http import Request

    class YourSpider(BaseSpider):
    # ...spider init details...
        def parse(self, response):
            # ...process item...
            yield item
            yield Request(response.url, callback=self.parse)
</code>```

Body:
I code this way:

def start_requests(self):
    while True:
        yield scrapy.Request(url, callback=self.parse, dont_filter=True)

I have tried the way below, but there is a problem that when the Internet is unstable, It will stop and will break the loop.

from scrapy.http import Request

    class YourSpider(BaseSpider):
    # ...spider init details...
        def parse(self, response):
            # ...process item...
            yield item
            yield Request(response.url, callback=self.parse)


问:
Adding all the values that has same class using jQuery
Here is my html

```<code><input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">
</code>```

I am trying to add all the values that has the same class name tt

So i am doing like this

```<code>$('.tt').each(function(i, obj) {
    var oo = obj;
    console.log(oo)
});
</code>```

When i do console.log(00)

It prints

```<code><input type="hidden" class="tt to_5" value="35">
</code>```

But when I try to do

```<code>console.log(oo.val())
</code>```

It is showing undefined How can I get the value ?

Am using jQuery

答:
You need to access the value of the element

```<code>var total = 0;
$('.tt').each(function(i, obj) {
    console.log(obj.value)//value is printed
    total += Number(obj.value);
});
</code>```

Body:
Here is my html

<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">

I am trying to add all the values that has the same class name tt

So i am doing like this

$('.tt').each(function(i, obj) {
    var oo = obj;
    console.log(oo)
});

When i do console.log(00)

It prints

<input type="hidden" class="tt to_5" value="35">

But when I try to do

console.log(oo.val())

It is showing undefined How can I get the value ?

Am using jQuery

Body:
You need to access the value of the element

var total = 0;
$('.tt').each(function(i, obj) {
    console.log(obj.value)//value is printed
    total += Number(obj.value);
});


问:
Fine-Uploader: setParams not adding new parameter to subsequent requests
My domain layer requires an entity to have 1:N images associated with it.

As FineUploader sends each image as a separate request, i am creating an entity (server side) on the first request and sending the ID of that back in the first response JSON to be added to the subsequent requests, so that the remaining images have an entity relationship ID to be saved with. This is all working well, except the new ID returned from the first request is not being appended to the next request.

I am using setParams to append the ID by hooking onto the onComplete event, as follows:

```<code>var uploader = new qq.FineUploader({
        debug: true,
        element: document.getElementById('fine-uploader'),
        allowedExtensions: ['jpg', 'jpeg', 'bmp', 'png','gif'],
        callbacks : {
            onComplete : function(id, name, responseJSON){
                this.setParams({entityId: responseJSON.entityId});
            }
        }
    });
</code>```

The new param is not added to request URI or post data. What am i doing wrong?

(Using FineUploader 5.15.3, debugged on FireFox Developer Edition, PHP 7.1 server side)

答:
Just a wild guess (I do not have the environment to try it myself):

```<code>var entityId = '';

var uploader = new qq.FineUploader({
        debug: true,
        // *** This is the part I added
        request: {
             params: { entityId: entityId }
        },
        element: document.getElementById('fine-uploader'),
        allowedExtensions: ['jpg', 'jpeg', 'bmp', 'png','gif'],
        callbacks : {
            onComplete : function(id, name, responseJSON){
                //**** This is the part I changed
                entityId = responseJSON.entityId;
                // this.setParams({entityId: responseJSON.entityId});
            }
        }
    });
</code>```

Basically what I intend to do is to get the entityId from the response and feed it as a parameter to the next request.

I hope it helps.

Body:
My domain layer requires an entity to have 1:N images associated with it.

As FineUploader sends each image as a separate request, i am creating an entity (server side) on the first request and sending the ID of that back in the first response JSON to be added to the subsequent requests, so that the remaining images have an entity relationship ID to be saved with. This is all working well, except the new ID returned from the first request is not being appended to the next request.

I am using setParams to append the ID by hooking onto the onComplete event, as follows:

var uploader = new qq.FineUploader({
        debug: true,
        element: document.getElementById('fine-uploader'),
        allowedExtensions: ['jpg', 'jpeg', 'bmp', 'png','gif'],
        callbacks : {
            onComplete : function(id, name, responseJSON){
                this.setParams({entityId: responseJSON.entityId});
            }
        }
    });

The new param is not added to request URI or post data. What am i doing wrong?

(Using FineUploader 5.15.3, debugged on FireFox Developer Edition, PHP 7.1 server side)

Body:
Just a wild guess (I do not have the environment to try it myself):

var entityId = '';

var uploader = new qq.FineUploader({
        debug: true,
        // *** This is the part I added
        request: {
             params: { entityId: entityId }
        },
        element: document.getElementById('fine-uploader'),
        allowedExtensions: ['jpg', 'jpeg', 'bmp', 'png','gif'],
        callbacks : {
            onComplete : function(id, name, responseJSON){
                //**** This is the part I changed
                entityId = responseJSON.entityId;
                // this.setParams({entityId: responseJSON.entityId});
            }
        }
    });

Basically what I intend to do is to get the entityId from the response and feed it as a parameter to the next request.

I hope it helps.


问:
Extract float from price-formatted string using regex in jQuery/JS
Reaching out to all the JS regex gurus out there. I am building a function that would remove $, white space, comma, [A-Z], [a-z] from string, leaving only float (if it exists within the string given) something like so:

```<code>var result = myFunction( 'USD $12, 345.95'); //result = 12345.95
var result = myFunction( 'ten dollars US' ); // result = false

function myFunction( weirdString ){

    // some code

}
</code>```

I know I can go something like (forgive me if I'm wrong):

```<code>weirdString.replace(/[&$<>"'`=\/\s]|[A-Z]|[a-z]/g, '');
isNaN( weirdString ) ? return false : return weirdString;
</code>```

But what is the right way?

答:
So here's the function I came up with:

```<code>function extractFloatFromString( input ){

    var result = input.match( /[\d+.]/g );
    return result == null ? 0 : result.join('');

}
</code>```

https://jsfiddle.net/7hq1dcwn/3/

Body:
Reaching out to all the JS regex gurus out there. I am building a function that would remove $, white space, comma, [A-Z], [a-z] from string, leaving only float (if it exists within the string given) something like so:

var result = myFunction( 'USD $12, 345.95'); //result = 12345.95
var result = myFunction( 'ten dollars US' ); // result = false

function myFunction( weirdString ){

    // some code

}

I know I can go something like (forgive me if I'm wrong):

weirdString.replace(/[&$<>"'`=\/\s]|[A-Z]|[a-z]/g, '');
isNaN( weirdString ) ? return false : return weirdString;

But what is the right way?

Body:
So here's the function I came up with:

function extractFloatFromString( input ){

    var result = input.match( /[\d+.]/g );
    return result == null ? 0 : result.join('');

}

https://jsfiddle.net/7hq1dcwn/3/


问:
What is the simplest way to create pagination using pure JavaScript without third party plugin?
I wonder about any customized JavaScript Framework, which can be used multiple times in a single html page.</p>

答:
There are many third party libraries of pagination that we can use, but there will be some project limitations where we can't use any external dependencies. Keeping this in my mind, I have created a custom JavaScript plugin for pagination. You will find this very easy to understand and it can be customized too. ;)

Below is some code examples of usage:

```<code>var array1 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'];
var array2 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50'];

var p1 = new Pagination(
           document.getElementById('abc'),
           array1,
           function(index, el){
              console.log(index, el);
           });
var p2 = new Pagination(document.getElementById('mno'), array2);
</code>```

You can find a full example on this Plnkr link.

Body:
There are many third party libraries of pagination that we can use, but there will be some project limitations where we can't use any external dependencies. Keeping this in my mind, I have created a custom JavaScript plugin for pagination. You will find this very easy to understand and it can be customized too. ;)

Below is some code examples of usage:

var array1 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'];
var array2 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50'];

var p1 = new Pagination(
           document.getElementById('abc'),
           array1,
           function(index, el){
              console.log(index, el);
           });
var p2 = new Pagination(document.getElementById('mno'), array2);

You can find a full example on this Plnkr link.


问:
Is there a way to get Maven to install javadocs for all dependencies to my local repo?
By running mvn dependency:sources I can force maven to resolve all dependencies in my project, download the sources, and install them into my local repo.

Is there something that does the same thing with my dependencies' JavaDocs?  I.e. grab them from upstream repos and install them into my local repo.

答:
There is a way to do it with the eclipse:eclipse mojo using the downloadJavadocs parameter.

```<code>mvn eclipse:eclipse -DdownloadJavadocs
</code>```

And if you don't use eclipse, just do

```<code>mvn eclipse:clean
</code>```

afterwards.

It's a hack, I know, but it works.

Actually, dependency:sources pretends to be configurable through the classifier and type parameters, so for a moment I thought you could do this:

```<code>mvn dependency:sources -Dclassifier=javadoc -Dtype=jar
</code>```

but I tried it and it didn't work. Then I checked the source code and found this:

```<code>private static final String SOURCE_TYPE = "java-source";
private static final String SOURCE_CLASSIFIER = "sources";

// ...

public void execute()
    throws MojoExecutionException
{
    // parameters are overwritten with constant values
    this.classifier = SOURCE_CLASSIFIER;
    this.type = SOURCE_TYPE;
</code>```

I have now submitted a Bug concerning this.

ContentLicense: CC BY-SA 2.5

Body:
There is a way to do it with the eclipse:eclipse mojo using the downloadJavadocs parameter.

mvn eclipse:eclipse -DdownloadJavadocs

And if you don't use eclipse, just do

mvn eclipse:clean

afterwards.

It's a hack, I know, but it works.

Actually, dependency:sources pretends to be configurable through the classifier and type parameters, so for a moment I thought you could do this:

mvn dependency:sources -Dclassifier=javadoc -Dtype=jar

but I tried it and it didn't work. Then I checked the source code and found this:

private static final String SOURCE_TYPE = "java-source";
private static final String SOURCE_CLASSIFIER = "sources";

// ...

public void execute()
    throws MojoExecutionException
{
    // parameters are overwritten with constant values
    this.classifier = SOURCE_CLASSIFIER;
    this.type = SOURCE_TYPE;

I have now submitted a Bug concerning this.


问:
Populate spinner from database content (SQLite)
How can I populate a spinner content from database (SQLite)

I have POJO: categories, contain id and name,
I have the table already, with a function to get the ArrayList like this:

```<code>public List<SetcardCategory> getAllSetcardCategory()
{
    List<SetcardCategory> setcardCategories = new ArrayList<SetcardCategory>();
    String selectQuery = "SELECT  * FROM " + TABLE_SETCARD_CATEGORIES;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (c.moveToFirst()) {
        do {
            SetcardCategory setcardCategory = new SetcardCategory();
            setcardCategory.setId(c.getInt((c.getColumnIndex("id"))));
            setcardCategory.setName(c.getString(c.getColumnIndex("name")));

            // adding to tags list
            setcardCategories.add(setcardCategory);
        } while (c.moveToNext());
    }
    return setcardCategories;
}
</code>```

Then on Activity I call it like this:

```<code>List<SetcardCategory> setcardCategories = db.getAllSetcardCategory();
    ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
            this, android.R.layout.simple_spinner_item, setcardCategories);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Spinner sItems = (Spinner) findViewById(R.id.setcardCategory);
    sItems.setAdapter(arrayAdapter);
</code>```

when I run it, it loads string like this: "schema.SetcardCategory@22293c98"  and many others values similar to that.

How can I populate the spinner to show the name field as a label, and id field as the value that we fetch to save into DB?

答:
```<code>class Pojo{
 private String name;
  @Override
    public String toString() {
        return name;
    }
}
</code>```

do it like this in the pojo class, so this will return a value for the object when it uses the to string method in the adapter, to load the data

Body:
How can I populate a spinner content from database (SQLite)

I have POJO: categories, contain id and name,
I have the table already, with a function to get the ArrayList like this:

public List<SetcardCategory> getAllSetcardCategory()
{
    List<SetcardCategory> setcardCategories = new ArrayList<SetcardCategory>();
    String selectQuery = "SELECT  * FROM " + TABLE_SETCARD_CATEGORIES;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (c.moveToFirst()) {
        do {
            SetcardCategory setcardCategory = new SetcardCategory();
            setcardCategory.setId(c.getInt((c.getColumnIndex("id"))));
            setcardCategory.setName(c.getString(c.getColumnIndex("name")));

            // adding to tags list
            setcardCategories.add(setcardCategory);
        } while (c.moveToNext());
    }
    return setcardCategories;
}

Then on Activity I call it like this:

List<SetcardCategory> setcardCategories = db.getAllSetcardCategory();
    ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
            this, android.R.layout.simple_spinner_item, setcardCategories);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Spinner sItems = (Spinner) findViewById(R.id.setcardCategory);
    sItems.setAdapter(arrayAdapter);

when I run it, it loads string like this: "schema.SetcardCategory@22293c98"  and many others values similar to that.

How can I populate the spinner to show the name field as a label, and id field as the value that we fetch to save into DB?

Body:
class Pojo{
 private String name;
  @Override
    public String toString() {
        return name;
    }
}

do it like this in the pojo class, so this will return a value for the object when it uses the to string method in the adapter, to load the data


问:
ng serve and ng build is not working
I downloaded this github project . this is working fine when I am using NPM START. but when I am using ng serve or ng build this is not working.  this is giving the error:

error log

```<code>Versions of @angular/compiler-cli and typescript could not be
determined.The most common reason for this is a broken npm install.
Please make sure your package.json contains both
@angular/compiler-cli and typescript in devDependencies, then
delete node_modules and package-lock.json (if you have one)
and run npm install again.
</code>```

I tried npm install @angular/cli inside the project. ng serve still not working. what I am missing or doing wrong. here is my package.json

package.json

```<code>{
"name": "angular-seed",
"description": "An Angular2+PrimeNG+SystemJS seed project",
"private": true,
"scripts": {
  "start": "live-server"
},
"dependencies": {
  "@angular/common": "^2.0.0",
  "@angular/compiler": "^2.0.0",
  "@angular/core": "^2.0.0",
  "@angular/forms": "^2.0.0",
  "@angular/http": "^2.0.0",
  "@angular/platform-browser": "^2.0.0",
  "@angular/platform-browser-dynamic": "^2.0.0",
  "@angular/router": "^3.0.0",
  "core-js": "^2.4.0",
  "font-awesome": "^4.6.3",
  "ngx-bootstrap": "^1.7.1",
  "primeng": "^1.0.0-beta.17",
  "rxjs": "5.0.0-beta.12",
  "systemjs": "0.19.37",
  "zone.js": "0.6.21"
},
"devDependencies": {
  "@angular/cli": "^1.5.0",
  "live-server": "1.1.0",
  "typescript": "^2.0.0"
}
}
</code>```

答:
I thinks this is because you are using systemJs and not Angular CLI app

take a look here on how to use angular CLI https://github.com/angular/angular-cli

@angular/cli is not the only needed when you need to run in ng serve theres a lot more. :D happy coding :-)

Title: ng serve and ng build is not working

Body:
I downloaded this github project . this is working fine when I am using NPM START. but when I am using ng serve or ng build this is not working.  this is giving the error:

error log

Versions of @angular/compiler-cli and typescript could not be
determined.The most common reason for this is a broken npm install.
Please make sure your package.json contains both
@angular/compiler-cli and typescript in devDependencies, then
delete node_modules and package-lock.json (if you have one)
and run npm install again.

I tried npm install @angular/cli inside the project. ng serve still not working. what I am missing or doing wrong. here is my package.json

package.json

{
"name": "angular-seed",
"description": "An Angular2+PrimeNG+SystemJS seed project",
"private": true,
"scripts": {
  "start": "live-server"
},
"dependencies": {
  "@angular/common": "^2.0.0",
  "@angular/compiler": "^2.0.0",
  "@angular/core": "^2.0.0",
  "@angular/forms": "^2.0.0",
  "@angular/http": "^2.0.0",
  "@angular/platform-browser": "^2.0.0",
  "@angular/platform-browser-dynamic": "^2.0.0",
  "@angular/router": "^3.0.0",
  "core-js": "^2.4.0",
  "font-awesome": "^4.6.3",
  "ngx-bootstrap": "^1.7.1",
  "primeng": "^1.0.0-beta.17",
  "rxjs": "5.0.0-beta.12",
  "systemjs": "0.19.37",
  "zone.js": "0.6.21"
},
"devDependencies": {
  "@angular/cli": "^1.5.0",
  "live-server": "1.1.0",
  "typescript": "^2.0.0"
}
}


问:
Multiple definition error when using extern variables
I'm having a strange multiple definition error and I'm hoping someone can help.

I have a file structure similar to the following:

```<code>-Folder
---data.cpp
---interface.cpp
---initialize.cpp
---internal.hpp
---maincode.cpp
</code>```

internal.hpp is included in all source code files in this folder. It has 3 extern variables to be used as forward declarations for variables defined in data.cpp, like so:

internal.hpp:

```<code>namespace montecarlo{

   namespace internal{

      extern std::vector<std::vector<int> > c_octants;
      extern std::vector<std::vector<int> > b_octants;
      extern bool mc_parallel_initialized;

   } // end of internal namespace

} // end of montecarlo namespace
</code>```

data.cpp:

```<code>#include "internal.hpp"

namespace montecarlo{

   namespace internal{

      std::vector<std::vector<int> > c_octants;
      std::vector<std::vector<int> > b_octants;
      bool mc_parallel_initialized;

   } // end of internal namespace

} // end of montecarlo namespace
</code>```

For some reason this gives a multiple definition error between every file internal.hpp is included in and data.cpp, as if the compiler is treating these extern variables as definitions rather than declarations.

```<code>obj/montecarlo/interface.o:(.bss+0x30): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/interface.o:(.bss+0x10): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/interface.o:(.bss+0x0): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
obj/montecarlo/mc.o:(.bss+0x30): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/mc.o:(.bss+0x10): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/mc.o:(.bss+0x0): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
obj/montecarlo/mc_moves.o:(.bss+0x30): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/mc_moves.o:(.bss+0x10): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/mc_moves.o:(.bss+0x0): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
obj/montecarlo/cmc.o:(.bss+0xb0): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/cmc.o:(.bss+0x90): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/cmc.o:(.bss+0x80): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
obj/montecarlo/cmc_mc.o:(.bss+0x70): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/cmc_mc.o:(.bss+0x50): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/cmc_mc.o:(.bss+0x48): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
obj/montecarlo/monte_carlo_preconditioning.o:(.bss+0x30): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/monte_carlo_preconditioning.o:(.bss+0x10): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/monte_carlo_preconditioning.o:(.bss+0x0): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
makefile:177: recipe for target 'serial' failed
make: *** [serial] Error 1
</code>```

I find this truly bizarre as this seems to comply with correct usage of extern and this code builds just fine on 2 other computers, only giving this error on my home desktop.

答:
Clean up your output directory and build again. Maybe some old object files are lying around.

Sometimes if not files affected by a change are compiled or your build system fails to do it for all dependent files it could happen that some object files still have references and linking fails.

This happens often on some compiles if you use pre-compiled headers.

Body:
I'm having a strange multiple definition error and I'm hoping someone can help.

I have a file structure similar to the following:

-Folder
---data.cpp
---interface.cpp
---initialize.cpp
---internal.hpp
---maincode.cpp

internal.hpp is included in all source code files in this folder. It has 3 extern variables to be used as forward declarations for variables defined in data.cpp, like so:

internal.hpp:

namespace montecarlo{

   namespace internal{

      extern std::vector<std::vector<int> > c_octants;
      extern std::vector<std::vector<int> > b_octants;
      extern bool mc_parallel_initialized;

   } // end of internal namespace

} // end of montecarlo namespace

data.cpp:

#include "internal.hpp"

namespace montecarlo{

   namespace internal{

      std::vector<std::vector<int> > c_octants;
      std::vector<std::vector<int> > b_octants;
      bool mc_parallel_initialized;

   } // end of internal namespace

} // end of montecarlo namespace

For some reason this gives a multiple definition error between every file internal.hpp is included in and data.cpp, as if the compiler is treating these extern variables as definitions rather than declarations.

obj/montecarlo/interface.o:(.bss+0x30): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/interface.o:(.bss+0x10): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/interface.o:(.bss+0x0): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
obj/montecarlo/mc.o:(.bss+0x30): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/mc.o:(.bss+0x10): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/mc.o:(.bss+0x0): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
obj/montecarlo/mc_moves.o:(.bss+0x30): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/mc_moves.o:(.bss+0x10): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/mc_moves.o:(.bss+0x0): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
obj/montecarlo/cmc.o:(.bss+0xb0): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/cmc.o:(.bss+0x90): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/cmc.o:(.bss+0x80): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
obj/montecarlo/cmc_mc.o:(.bss+0x70): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/cmc_mc.o:(.bss+0x50): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/cmc_mc.o:(.bss+0x48): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
obj/montecarlo/monte_carlo_preconditioning.o:(.bss+0x30): multiple definition of `montecarlo::internal::c_octants'
obj/montecarlo/data.o:(.bss+0x30): first defined here
obj/montecarlo/monte_carlo_preconditioning.o:(.bss+0x10): multiple definition of `montecarlo::internal::b_octants'
obj/montecarlo/data.o:(.bss+0x10): first defined here
obj/montecarlo/monte_carlo_preconditioning.o:(.bss+0x0): multiple definition of `montecarlo::internal::mc_parallel_initialized'
obj/montecarlo/data.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
makefile:177: recipe for target 'serial' failed
make: *** [serial] Error 1

I find this truly bizarre as this seems to comply with correct usage of extern and this code builds just fine on 2 other computers, only giving this error on my home desktop.


问:
Expandable Tableview with last row of every section has Add Button - Swift
I struck in tableview. I need tableview of collapse and Expand looks like Below,

]2

I need to add 2 buttons for last row of every section.
Could you guide me how to design the below design in ios swift?

答:
Add your buttons in custom view and feed it in UITableViewDataSource method below:

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView?


问:
Gradle sync failed: Unable to find method
I try to import a project in Android studio. When importing it, i've got an Error with Gradle :

```<code>Gradle sync failed: Unable to find method

'org.gradle.api.artifacts.Configuration.setExtendsFrom(Ljava/lang/Iterable;)Lorg/gradle/api/artifacts/Configuration;'.
</code>```

I have tried :

Re-download dependencies and sync project: Fail (same error).

Stop Gradle build processes: Fail (same error).

Delete the .graddle in the home directory: Fail (same error).

Invalidate cache and restart Fail (same error).

Uninstall and reinstall Android studio and SDK: Fail (same error).

/build.gradle :

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

/app/build.gradle

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

android {
    compileSdkVersion 17
    buildToolsVersion '20.0.0'
    defaultConfig {
        applicationId 'xxx.xxx.xxx'
        minSdkVersion 17
        targetSdkVersion 17
        versionCode 1
        versionName '1.0'
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        buildPB {
            debuggable false
            jniDebuggable false
            renderscriptDebuggable false

            zipAlignEnabled true
        }
    }
    productFlavors {
    }
//    lintOptions {
//        abortOnError false
//    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    // You must install or update the Support Repository through the SDK manager to use this dependency.
    compile ('org.simpleframework:simple-xml:2.7.1') {
        exclude module: 'stax'
        exclude module: 'stax-api'
        exclude module: 'xpp3'
    }
    compile 'net.sf.opencsv:opencsv:2.3'
    compile 'de.greenrobot:greendao:1.3.7'
    // You must install or update the Support Repository through the SDK manager to use this dependency.
//    compile 'com.android.support:support-v4:19.+'
}
</code>```

答:
```<code>Project >> App >> gradle >> wrapper >> gradle-wrapper.properties

https\://services.gradle.org/distributions/gradle-4.1-all.zip
</code>```

This will surely work. I was having same issue. Solved by this.

ContentLicense: CC BY-SA 4.0

Body:
I try to import a project in Android studio. When importing it, i've got an Error with Gradle :

Gradle sync failed: Unable to find method

'org.gradle.api.artifacts.Configuration.setExtendsFrom(Ljava/lang/Iterable;)Lorg/gradle/api/artifacts/Configuration;'.

I have tried :

Re-download dependencies and sync project: Fail (same error).

Stop Gradle build processes: Fail (same error).

Delete the .graddle in the home directory: Fail (same error).

Invalidate cache and restart Fail (same error).

Uninstall and reinstall Android studio and SDK: Fail (same error).

/build.gradle :

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

/app/build.gradle

apply plugin: 'com.android.application'
//apply plugin: 'android'

android {
    compileSdkVersion 17
    buildToolsVersion '20.0.0'
    defaultConfig {
        applicationId 'xxx.xxx.xxx'
        minSdkVersion 17
        targetSdkVersion 17
        versionCode 1
        versionName '1.0'
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        buildPB {
            debuggable false
            jniDebuggable false
            renderscriptDebuggable false

            zipAlignEnabled true
        }
    }
    productFlavors {
    }
//    lintOptions {
//        abortOnError false
//    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    // You must install or update the Support Repository through the SDK manager to use this dependency.
    compile ('org.simpleframework:simple-xml:2.7.1') {
        exclude module: 'stax'
        exclude module: 'stax-api'
        exclude module: 'xpp3'
    }
    compile 'net.sf.opencsv:opencsv:2.3'
    compile 'de.greenrobot:greendao:1.3.7'
    // You must install or update the Support Repository through the SDK manager to use this dependency.
//    compile 'com.android.support:support-v4:19.+'
}

Body:
Project >> App >> gradle >> wrapper >> gradle-wrapper.properties

https\://services.gradle.org/distributions/gradle-4.1-all.zip

This will surely work. I was having same issue. Solved by this.


问:
convert os.system to subprocess.Popen
I am writing a script to open a new command prompt, and run an executable. I got a working code using os.system. Can you help me transform it to subprocess.Popen?

```<code>hello_exe = r'c:\hello.exe'
os.system("start cmd /k {}".format(hello_exe))
</code>```

I cannot run hello_exe as a background process because I want the user to see the command prompt and be able to scroll through the logs. Any help is appreciated. Thanks.

My environment: Windows8 and python 2.7.12

答:
Conversion to subprocess.Popen is like this:

```<code>import subprocess

process = subprocess.Popen(r'c:\hello.exe', shell = True)
process.communicate()
</code>```

Title: convert os.system to subprocess.Popen

Body:
I am writing a script to open a new command prompt, and run an executable. I got a working code using os.system. Can you help me transform it to subprocess.Popen?

hello_exe = r'c:\hello.exe'
os.system("start cmd /k {}".format(hello_exe))

I cannot run hello_exe as a background process because I want the user to see the command prompt and be able to scroll through the logs. Any help is appreciated. Thanks.

My environment: Windows8 and python 2.7.12

Body:
Conversion to subprocess.Popen is like this:

import subprocess

process = subprocess.Popen(r'c:\hello.exe', shell = True)
process.communicate()


答:
Conversion to Popen

```<code>from subprocess import Popen, PIPE

hello_exe = r'c:\hello.exe'

proc = Popen(hello_exe, stdout=PIPE, shell = True)
proc.communicate()
</code>```

Here are few links which you can refer to understand subprocess.Popen

Link to understand Popen

Another link to understand Popen

Link to 50+ examples of Popen

Title: convert os.system to subprocess.Popen

Body:
Conversion to Popen

from subprocess import Popen, PIPE

hello_exe = r'c:\hello.exe'

proc = Popen(hello_exe, stdout=PIPE, shell = True)
proc.communicate()

Here are few links which you can refer to understand subprocess.Popen

Link to understand Popen

Another link to understand Popen

Link to 50+ examples of Popen


答:
You need to pass the correct object name. The second argument of callback inside each points to the object, using that you can access the value of input tags.

$('.tt').each(function(i, o) {
    console.log($(o).val());
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25"></code>```

Title: Adding all the values that has same class using jQuery

Body:
Here is my html

<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">

I am trying to add all the values that has the same class name tt

So i am doing like this

$('.tt').each(function(i, obj) {
    var oo = obj;
    console.log(oo)
});

When i do console.log(00)

It prints

<input type="hidden" class="tt to_5" value="35">

But when I try to do

console.log(oo.val())

It is showing undefined How can I get the value ?

Am using jQuery

Body:
You need to pass the correct object name. The second argument of callback inside each points to the object, using that you can access the value of input tags.

$('.tt').each(function(i, o) {
    console.log($(o).val());
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">


问:
Mailing system in GoogleSheets, resume of crypto-transactions. I'm notified only about 1 of 7 operations, and more than once. How to edit the script?
Actually the code is as follows, there are 7 active operations plus one of the required two sendEmail functions.

Most of this code has been copied from another discussion so not mine, tried to adjust it up to my purpose.

The goal is:
1. get the script to check if a cell on the sheet called AutoMail is empty or filled with either "gain position" or "purchase position" (it's not one cell, there are two, the one on the left is eventually filled with the first expression and on the right with the latter);
2. in case of gain/purchase position, get the relative coin abbreviation and amount from two cells located on another sheet (YourData) and to paste them in a personalized text used as subject and then in the body of my message, and of course let this email reach my inbox, possibly ONCE the cell is filled up with the above mentioned expressions, not every minute.

I'd like the script to check the sheets once every minute, I think I mistake in the trigger setting as well. The repetition of var ss1 and var sheet1 might be useless here.

```<code>    function readCell() {
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain1 = sheet1.getRange("C2:C46").getValue();
      var operationpurchase1 = sheet1.getRange("D2:D46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin1 = sheet2.getRange("B3");
      var amount1 = sheet2.getRange("B4");
      if(operationgain1="gain position") sendEmail(operationgain1);
        function sendEmail(operationgain1) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount1+" "+coin1+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin1+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain2 = sheet1.getRange("E2:E46").getValue();
      var operationpurchase2 = sheet1.getRange("F2:F46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin2 = sheet2.getRange("C3");
      var amount2 = sheet2.getRange("C4");
      if(operationgain2="gain position") sendEmail(operationgain2);
        function sendEmail(operationgain2) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount2+" "+coin2+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin2+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain3 = sheet1.getRange("G2:G46").getValue();
      var operationpurchase3 = sheet1.getRange("H2:H46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin3 = sheet2.getRange("D3");
      var amount3 = sheet2.getRange("D4");
      if(operationgain3="gain position") sendEmail(operationgain3);
        function sendEmail(operationgain3) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount3+" "+coin3+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin3+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain4 = sheet1.getRange("I2:I46").getValue();
      var operationpurchase4 = sheet1.getRange("J2:J46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin4 = sheet2.getRange("E3");
      var amount4 = sheet2.getRange("E4");
      if(operationgain4="gain position") sendEmail(operationgain4);
        function sendEmail(operationgain4) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount4+" "+coin4+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin4+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain5 = sheet1.getRange("K2:K46").getValue();
      var operationpurchase5 = sheet1.getRange("L2:L46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin5 = sheet2.getRange("F3");
      var amount5 = sheet2.getRange("F4");
      if(operationgain5="gain position") sendEmail(operationgain5);
        function sendEmail(operationgain5) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount5+" "+coin5+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin5+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain6 = sheet1.getRange("M2:M46").getValue();
      var operationpurchase6 = sheet1.getRange("N2:N46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin6 = sheet2.getRange("G3");
      var amount6 = sheet2.getRange("G4");
      if(operationgain6="gain position") sendEmail(operationgain6);
        function sendEmail(operationgain6) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount6+" "+coin6+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin6+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain7 = sheet1.getRange("O2:O46").getValue();
      var operationpurchase7 = sheet1.getRange("P2:P46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin7 = sheet2.getRange("H3").getValue();
      var amount7 = sheet2.getRange("H4").getValue();
      if(operationgain7="gain position") sendEmail(operationgain7);
        function sendEmail(operationgain7) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount7+" "+coin7+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin7+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
    };
</code>```

答:
So just to resume from my previous comments:
1. I received an email each minute, so the script checks the cell each minute and if in gain or purchase sends an email, would like it to check it once of course;
2. mailing regarded only the last operation, that one which variables have a 7 at the end;
3. I think ss1 and sheet1 don't need to be repeated for every operation, of course if all 7 remain integrated in one function... I still can make 7 different functions as for the first edition of the code and as for your previous reply.</p>

```<code>function readCell() {
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain1 = sheet1.getRange("C2:C46").getValue();
  var operationpurchase1 = sheet1.getRange("D2:D46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin1 = sheet2.getRange("B3");
  var amount1 = sheet2.getRange("B4");
  if(operationgain1="gain position") sendEmail(operationgain1);
    function sendEmail(operationgain1) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount1+" "+coin1+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin1+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain2 = sheet1.getRange("E2:E46").getValue();
  var operationpurchase2 = sheet1.getRange("F2:F46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin2 = sheet2.getRange("C3");
  var amount2 = sheet2.getRange("C4");
  if(operationgain2="gain position") sendEmail(operationgain2);
    function sendEmail(operationgain2) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount2+" "+coin2+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin2+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain3 = sheet1.getRange("G2:G46").getValue();
  var operationpurchase3 = sheet1.getRange("H2:H46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin3 = sheet2.getRange("D3");
  var amount3 = sheet2.getRange("D4");
  if(operationgain3="gain position") sendEmail(operationgain3);
    function sendEmail(operationgain3) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount3+" "+coin3+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin3+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain4 = sheet1.getRange("I2:I46").getValue();
  var operationpurchase4 = sheet1.getRange("J2:J46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin4 = sheet2.getRange("E3");
  var amount4 = sheet2.getRange("E4");
  if(operationgain4="gain position") sendEmail(operationgain4);
    function sendEmail(operationgain4) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount4+" "+coin4+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin4+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain5 = sheet1.getRange("K2:K46").getValue();
  var operationpurchase5 = sheet1.getRange("L2:L46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin5 = sheet2.getRange("F3");
  var amount5 = sheet2.getRange("F4");
  if(operationgain5="gain position") sendEmail(operationgain5);
    function sendEmail(operationgain5) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount5+" "+coin5+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin5+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain6 = sheet1.getRange("M2:M46").getValue();
  var operationpurchase6 = sheet1.getRange("N2:N46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin6 = sheet2.getRange("G3");
  var amount6 = sheet2.getRange("G4");
  if(operationgain6="gain position") sendEmail(operationgain6);
    function sendEmail(operationgain6) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount6+" "+coin6+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin6+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain7 = sheet1.getRange("O2:O46").getValue();
  var operationpurchase7 = sheet1.getRange("P2:P46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin7 = sheet2.getRange("H3").getValue();
  var amount7 = sheet2.getRange("H4").getValue();
  if(operationgain7="gain position") sendEmail(operationgain7);
    function sendEmail(operationgain7) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount7+" "+coin7+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin7+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
};
</code>```

Body:
Actually the code is as follows, there are 7 active operations plus one of the required two sendEmail functions.

Most of this code has been copied from another discussion so not mine, tried to adjust it up to my purpose.

The goal is:
1. get the script to check if a cell on the sheet called AutoMail is empty or filled with either "gain position" or "purchase position" (it's not one cell, there are two, the one on the left is eventually filled with the first expression and on the right with the latter);
2. in case of gain/purchase position, get the relative coin abbreviation and amount from two cells located on another sheet (YourData) and to paste them in a personalized text used as subject and then in the body of my message, and of course let this email reach my inbox, possibly ONCE the cell is filled up with the above mentioned expressions, not every minute.

I'd like the script to check the sheets once every minute, I think I mistake in the trigger setting as well. The repetition of var ss1 and var sheet1 might be useless here.

    function readCell() {
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain1 = sheet1.getRange("C2:C46").getValue();
      var operationpurchase1 = sheet1.getRange("D2:D46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin1 = sheet2.getRange("B3");
      var amount1 = sheet2.getRange("B4");
      if(operationgain1="gain position") sendEmail(operationgain1);
        function sendEmail(operationgain1) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount1+" "+coin1+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin1+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain2 = sheet1.getRange("E2:E46").getValue();
      var operationpurchase2 = sheet1.getRange("F2:F46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin2 = sheet2.getRange("C3");
      var amount2 = sheet2.getRange("C4");
      if(operationgain2="gain position") sendEmail(operationgain2);
        function sendEmail(operationgain2) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount2+" "+coin2+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin2+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain3 = sheet1.getRange("G2:G46").getValue();
      var operationpurchase3 = sheet1.getRange("H2:H46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin3 = sheet2.getRange("D3");
      var amount3 = sheet2.getRange("D4");
      if(operationgain3="gain position") sendEmail(operationgain3);
        function sendEmail(operationgain3) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount3+" "+coin3+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin3+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain4 = sheet1.getRange("I2:I46").getValue();
      var operationpurchase4 = sheet1.getRange("J2:J46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin4 = sheet2.getRange("E3");
      var amount4 = sheet2.getRange("E4");
      if(operationgain4="gain position") sendEmail(operationgain4);
        function sendEmail(operationgain4) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount4+" "+coin4+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin4+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain5 = sheet1.getRange("K2:K46").getValue();
      var operationpurchase5 = sheet1.getRange("L2:L46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin5 = sheet2.getRange("F3");
      var amount5 = sheet2.getRange("F4");
      if(operationgain5="gain position") sendEmail(operationgain5);
        function sendEmail(operationgain5) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount5+" "+coin5+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin5+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain6 = sheet1.getRange("M2:M46").getValue();
      var operationpurchase6 = sheet1.getRange("N2:N46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin6 = sheet2.getRange("G3");
      var amount6 = sheet2.getRange("G4");
      if(operationgain6="gain position") sendEmail(operationgain6);
        function sendEmail(operationgain6) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount6+" "+coin6+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin6+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain7 = sheet1.getRange("O2:O46").getValue();
      var operationpurchase7 = sheet1.getRange("P2:P46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin7 = sheet2.getRange("H3").getValue();
      var amount7 = sheet2.getRange("H4").getValue();
      if(operationgain7="gain position") sendEmail(operationgain7);
        function sendEmail(operationgain7) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount7+" "+coin7+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin7+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
    };

Body:
So just to resume from my previous comments:
1. I received an email each minute, so the script checks the cell each minute and if in gain or purchase sends an email, would like it to check it once of course;
2. mailing regarded only the last operation, that one which variables have a 7 at the end;
3. I think ss1 and sheet1 don't need to be repeated for every operation, of course if all 7 remain integrated in one function... I still can make 7 different functions as for the first edition of the code and as for your previous reply.

function readCell() {
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain1 = sheet1.getRange("C2:C46").getValue();
  var operationpurchase1 = sheet1.getRange("D2:D46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin1 = sheet2.getRange("B3");
  var amount1 = sheet2.getRange("B4");
  if(operationgain1="gain position") sendEmail(operationgain1);
    function sendEmail(operationgain1) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount1+" "+coin1+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin1+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain2 = sheet1.getRange("E2:E46").getValue();
  var operationpurchase2 = sheet1.getRange("F2:F46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin2 = sheet2.getRange("C3");
  var amount2 = sheet2.getRange("C4");
  if(operationgain2="gain position") sendEmail(operationgain2);
    function sendEmail(operationgain2) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount2+" "+coin2+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin2+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain3 = sheet1.getRange("G2:G46").getValue();
  var operationpurchase3 = sheet1.getRange("H2:H46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin3 = sheet2.getRange("D3");
  var amount3 = sheet2.getRange("D4");
  if(operationgain3="gain position") sendEmail(operationgain3);
    function sendEmail(operationgain3) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount3+" "+coin3+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin3+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain4 = sheet1.getRange("I2:I46").getValue();
  var operationpurchase4 = sheet1.getRange("J2:J46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin4 = sheet2.getRange("E3");
  var amount4 = sheet2.getRange("E4");
  if(operationgain4="gain position") sendEmail(operationgain4);
    function sendEmail(operationgain4) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount4+" "+coin4+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin4+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain5 = sheet1.getRange("K2:K46").getValue();
  var operationpurchase5 = sheet1.getRange("L2:L46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin5 = sheet2.getRange("F3");
  var amount5 = sheet2.getRange("F4");
  if(operationgain5="gain position") sendEmail(operationgain5);
    function sendEmail(operationgain5) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount5+" "+coin5+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin5+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain6 = sheet1.getRange("M2:M46").getValue();
  var operationpurchase6 = sheet1.getRange("N2:N46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin6 = sheet2.getRange("G3");
  var amount6 = sheet2.getRange("G4");
  if(operationgain6="gain position") sendEmail(operationgain6);
    function sendEmail(operationgain6) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount6+" "+coin6+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin6+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain7 = sheet1.getRange("O2:O46").getValue();
  var operationpurchase7 = sheet1.getRange("P2:P46").getValue();
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin7 = sheet2.getRange("H3").getValue();
  var amount7 = sheet2.getRange("H4").getValue();
  if(operationgain7="gain position") sendEmail(operationgain7);
    function sendEmail(operationgain7) {
      var email = "adrian@semeniuk.biz";
      var subject = "Your "+amount7+" "+coin7+" are somewhere in gain position.";
      var body = "Keep an eye on your "+coin7+"s, they're goin' up.";
      MailApp.sendEmail(email,subject,body);}
};


问:
Implement PHP's static array in angular 2
I want to implement a static array in angular 2 equivalent to this one in PHP. How can I do that?</p>

```<code> <?php
 class Services
 {
     const TaskPoll         =   "TaskPoll";
     const ModuleList       =   "ModuleList";

     public static $services = array
     (
        Services::TaskPoll              =>array("APIURL"=>"task/poll","APIRequestType"=>"PostAPI","RestService"=>["WarName"=>"abc","ServiceUrl"=>"http://localhost:8080"]),
        Services::ModuleList            =>array("APIURL"=>"task/modulelist","APIRequestType"=>"GetAPI","RestService"=>["WarName"=>"abc","ServiceUrl"=>"http://localhost:8080"]),
     );
 }
</code>```

答:
```<code>class Services {
  public static readonly TaskPoll = 'TaskPoll';
  public static readonly ModuleList = 'ModuleList';

  public static readonly $services = {
    TaskPoll: {'APIURL': 'task/poll', 'APIRequestType': 'PostAPI', 'RestService': {'WarName': 'abc', 'ServiceUrl': 'http://localhost:8080'}},
    ModuleList: {'APIURL': 'task/modulelist', 'APIRequestType': 'GetAPI', 'RestService': {'WarName': 'abc', 'ServiceUrl': 'http://localhost:8080'}}
  };
}

console.log(Services.$services.TaskPoll);
</code>```

Body:
I want to implement a static array in angular 2 equivalent to this one in PHP. How can I do that?

 <?php
 class Services
 {
     const TaskPoll         =   "TaskPoll";
     const ModuleList       =   "ModuleList";

     public static $services = array
     (
        Services::TaskPoll              =>array("APIURL"=>"task/poll","APIRequestType"=>"PostAPI","RestService"=>["WarName"=>"abc","ServiceUrl"=>"http://localhost:8080"]),
        Services::ModuleList            =>array("APIURL"=>"task/modulelist","APIRequestType"=>"GetAPI","RestService"=>["WarName"=>"abc","ServiceUrl"=>"http://localhost:8080"]),
     );
 }