问:
Passing Id from CreateView to another function after creating the object
I am creating a Payment object using Django CreateView then I want to pass the id of this object to another view function to make and display some calculations on another template. how can i do that?

views.py:

```<code>class CreatePayment(CreateView):
    template_name = "inventory/new_payment.html"
    success_url = reverse_lazy('inventory:payments_page')
    model = Payments
    fields = ('payment_number', 'customer','agent', 'amount')
</code>```

html:

```<code><body>

<form action="{% url 'inventory:new_payment'%}" method="post">
    {% csrf_token %}
    {{form}}

    <button type="submit", value="Add">Add</button>
</form>

</body>
</code>```

urls:

```<code>url(r'newpayment/$', CreatePayment.as_view(), name='new_payment')
</code>```

答:
Add a parameter to your other view and url and use get_success_url:

```<code>def get_success_url(self):
    success_url = reverse_lazy('inventory:payments_page', {'id': self.object.pk})
    return success_url
</code>```

Body:
I am creating a Payment object using Django CreateView then I want to pass the id of this object to another view function to make and display some calculations on another template. how can i do that?

views.py:

class CreatePayment(CreateView):
    template_name = "inventory/new_payment.html"
    success_url = reverse_lazy('inventory:payments_page')
    model = Payments
    fields = ('payment_number', 'customer','agent', 'amount')

html:

<form action="{% url 'inventory:new_payment'%}" method="post">
    {% csrf_token %}
    {{form}}

    <button type="submit", value="Add">Add</button>
</form>

urls:

url(r'newpayment/$', CreatePayment.as_view(), name='new_payment')

Body:
Add a parameter to your other view and url and use get_success_url:

def get_success_url(self):
    success_url = reverse_lazy('inventory:payments_page', {'id': self.object.pk})
    return success_url


来源: stackexchange

问:
No rows found, C# using OleDB
I have been rewriting a C# program to better encapsulate accessing an Access database, using OleDb.  It runs, but doesn't find the row that exists, but running the SQL query in Access does find it.

The question is: what is wrong with my code?  Why don't I get any rows returned?

I'm using VS 2017 and Access 2013.  The PC is an up-to-date windows 10 x64 machine.

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;

namespace OleDbTest
{
    class Program
    {
        static void Main( string[] args )
        {
            // Create Profile File object
            ProcessEJFile EJP = new ProcessEJFile(
                "Provider=Microsoft.ACE.OLEDB.12.0;" +
                @"Data Source=E:\Users\sallyw\Documents\Bar.accdb;" +
                "Persist Security Info=False;");

            // Get details of last header - this should return just one row
            string query =
            //      @"select * from stock_head where sh_ref in ( select max( stock_head.[ sh_ref ] ) FROM stock_head WHERE sh_ref like ""[#]%"")";

                    "select sh_id, sh_ref, sh_lineno, sh_type, sh_supplier, sh_datetime from stock_head where sh_id = 19;";

            //      "select * from stock_head where sh_ref = 19;"

            List<StockHead> shlist = EJP.GetStockHead(query, null );
            if ( shlist == null )
            {
                Console.WriteLine( "shlist is null" );
            }
            else
            {
                Console.WriteLine( "shlist contains {0} entries", shlist.Count );
            }
            Console.ReadLine();
        }
    }

    class ProcessEJFile
    {
        AccessDatabase Accdb = null;

        public ProcessEJFile( string connectionString )
        {
            Accdb = new AccessDatabase( connectionString );
            Console.WriteLine( "ProfessEJFile #1 - connection string = {0}", connectionString );
        }

        public List<StockHead> GetStockHead( string sql, params object[] args )
        {
            DataTable t;
            if ( args == null )
            {
                Console.WriteLine( "GetStockHead #1 - args are NULL " );
            }
            else
            {
                Console.WriteLine( "GetStockHead #2 - {0} arguments passed", args.Count() );
            }

            Accdb.ExecuteQuery( out t, sql, args );

            if ( t != null )
            {
                List<StockHead> shlist = new List<StockHead>();

                foreach ( DataRow r in t.Rows )
                {
                    Console.WriteLine( t.ToString() );
                    //StockHead sh = new StockHead(
                    //    (int)r["sh_id"],
                    //    (string)r["sh_ref"],
                    //    (int)r["sh_lineno"],
                    //    (string)r["sh_type"],
                    //    (string)r["sh_supplier"],
                    //    (DateTime)r["sh_datetime"]);
                    //shlist.Add( sh );
                }
                return shlist;
            }
            else
            {
                Console.WriteLine( "GetStockHead #3 - t is null" );
                return null;
            }
        }
    }
    class AccessDatabase
    {
        public OleDbConnection conn = new OleDbConnection();

        public AccessDatabase( string connection )
        {
            conn.ConnectionString = connection;
        }

        public bool OpenDatabase()
        {
            try
            {
                conn.Open();
            }
            catch ( Exception ex )
            {
                Console.WriteLine( "OpenDatabase()\n" + ex.Message );
                return false;
            }
            return true;
        }

        public void CloseDatabase()
        {
            if ( conn == null )
                return;

            conn.Close();
        }

        public void ExecuteQuery( out DataTable dataTable, string sql, params object[] args )
        {
            dataTable = new DataTable();
            string query;

            // Simplified version not validating or cleaning arguments in any way
            if (args == null )
            {
                query = sql;
            }
            else
            {
                query = string.Format( sql, args );
            }
            Console.WriteLine( "ExecuteQuery #3 - query = '{0}'", query );

            if ( OpenDatabase() )
            {
                OleDbCommand command = new OleDbCommand( query, conn );
                OleDbDataAdapter adapter = new OleDbDataAdapter( command );
                adapter.Fill( dataTable );
            }
            else
            {
                Console.WriteLine( "ExecuteQuery #9 - cannot open database" );
            }
        }
    }

    class StockHead
    {
        public int sh_id;              // autonumber
        public string sh_ref;          // short text
        public int sh_lineno;          // Number
        public string sh_type;         // short text
        public string sh_supplier;     // short text
        public DateTime sh_datetime;   // date/time

        public StockHead( int id, string refno, int lineno, string type, string supplier, DateTime datetime )
        {
            sh_id = id;
            sh_ref = refno;
            sh_lineno = lineno;
            sh_type = type;
            sh_supplier = supplier;
            sh_datetime = datetime;
        }
    }
}
</code>```

Data in CSV format, class stock_head shows the Access column types:

```<code>1,"#000001",,"IR","INITIAL RESET",20/8/2013 08:33:00
2,"#000002",,"SD","FORMATTING",20/8/2013 08:34:00
3,"#000003",,"SD","FOLDER CREATE",20/8/2013 08:35:00
4,"#000004",,"SD","FOLDER SELECT",20/8/2013 08:35:00
5,"#000005",,"NS","NO SALE",20/8/2013 11:14:00
6,"#000006",,"NS","NO SALE",20/8/2013 11:46:00
7,"#000007",,"NS","NO SALE",20/8/2013 12:16:00
8,"#000008",,"SALE",,20/8/2013 15:11:00
9,"#000009",,"SALE",,20/8/2013 15:30:00
10,"#000010",,"Z1",,20/8/2013 15:32:00
11,"#000011",,"NS","NO SALE",20/8/2013 15:32:00
12,"#000012",,"SALE",,20/8/2013 16:46:00
13,"#000013",,"SALE",,20/8/2013 16:47:00
14,"#000014",,"SALE",,20/8/2013 17:32:00
15,"#000015",,"Z1",,20/8/2013 19:25:00
16,"#000016",,"NS","NO SALE",20/8/2013 19:25:00
17,"#000017",,"Z1",,20/8/2013 21:52:00
18,"#000018",,"NS","NO SALE",20/8/2013 21:52:00
19,"#000019",,"SALE",,23/8/2013 18:27:00
20,"#000020",,"SALE",,23/8/2013 19:06:00
21,"#000021",,"SALE",,23/8/2013 20:24:00
22,"#000022",,"SALE",,23/8/2013 20:36:00
23,"#000023",,"SALE",,23/8/2013 21:21:00
24,"#000024",,"SALE",,23/8/2013 21:57:00
25,"#000025",,"SALE",,23/8/2013 22:38:00
26,"#000026",,"Z1",,23/8/2013 22:40:00
27,"#000027",,"NS","NO SALE",23/8/2013 22:40:00
28,"#000028",,"SALE",,24/8/2013 16:09:00
29,"#000029",,"SALE",,24/8/2013 16:28:00
30,"#000030",,"SALE",,24/8/2013 16:58:00
</code>```

答:
If I alter the code creating a StockHead object to use literals instead of the correct values it works.  There must be an elegant way of resolving this!</p>

```<code>                StockHead sh = new StockHead(
                    (int)r[ "sh_id" ],
                    (string)r[ "sh_ref" ],
                    0,                          //(int)r[ "sh_lineno" ],
                    (string)r[ "sh_type" ],
                    "",                         //(string)r[ "sh_supplier" ],
                    (DateTime)r[ "sh_datetime" ]);
</code>```

ContentLicense: CC BY-SA 3.0

Title: No rows found, C# using OleDB

Body:
I have been rewriting a C# program to better encapsulate accessing an Access database, using OleDb.  It runs, but doesn't find the row that exists, but running the SQL query in Access does find it.

The question is: what is wrong with my code?  Why don't I get any rows returned?

I'm using VS 2017 and Access 2013.  The PC is an up-to-date windows 10 x64 machine.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;

namespace OleDbTest
{
    class Program
    {
        static void Main( string[] args )
        {
            // Create Profile File object
            ProcessEJFile EJP = new ProcessEJFile(
                "Provider=Microsoft.ACE.OLEDB.12.0;" +
                @"Data Source=E:\Users\sallyw\Documents\Bar.accdb;" +
                "Persist Security Info=False;");

            // Get details of last header - this should return just one row
            string query =
            //      @"select * from stock_head where sh_ref in ( select max( stock_head.[ sh_ref ] ) FROM stock_head WHERE sh_ref like ""[#]%"")";

                    "select sh_id, sh_ref, sh_lineno, sh_type, sh_supplier, sh_datetime from stock_head where sh_id = 19;";

            //      "select * from stock_head where sh_ref = 19;"

            List<StockHead> shlist = EJP.GetStockHead(query, null );
            if ( shlist == null )
            {
                Console.WriteLine( "shlist is null" );
            }
            else
            {
                Console.WriteLine( "shlist contains {0} entries", shlist.Count );
            }
            Console.ReadLine();
        }
    }

    class ProcessEJFile
    {
        AccessDatabase Accdb = null;

        public ProcessEJFile( string connectionString )
        {
            Accdb = new AccessDatabase( connectionString );
            Console.WriteLine( "ProfessEJFile #1 - connection string = {0}", connectionString );
        }

        public List<StockHead> GetStockHead( string sql, params object[] args )
        {
            DataTable t;
            if ( args == null )
            {
                Console.WriteLine( "GetStockHead #1 - args are NULL " );
            }
            else
            {
                Console.WriteLine( "GetStockHead #2 - {0} arguments passed", args.Count() );
            }

            Accdb.ExecuteQuery( out t, sql, args );

            if ( t != null )
            {
                List<StockHead> shlist = new List<StockHead>();

                foreach ( DataRow r in t.Rows )
                {
                    Console.WriteLine( t.ToString() );
                    //StockHead sh = new StockHead(
                    //    (int)r["sh_id"],
                    //    (string)r["sh_ref"],
                    //    (int)r["sh_lineno"],
                    //    (string)r["sh_type"],
                    //    (string)r["sh_supplier"],
                    //    (DateTime)r["sh_datetime"]);
                    //shlist.Add( sh );
                }
                return shlist;
            }
            else
            {
                Console.WriteLine( "GetStockHead #3 - t is null" );
                return null;
            }
        }
    }
    class AccessDatabase
    {
        public OleDbConnection conn = new OleDbConnection();

        public AccessDatabase( string connection )
        {
            conn.ConnectionString = connection;
        }

        public bool OpenDatabase()
        {
            try
            {
                conn.Open();
            }
            catch ( Exception ex )
            {
                Console.WriteLine( "OpenDatabase()\n" + ex.Message );
                return false;
            }
            return true;
        }

        public void CloseDatabase()
        {
            if ( conn == null )
                return;

            conn.Close();
        }

        public void ExecuteQuery( out DataTable dataTable, string sql, params object[] args )
        {
            dataTable = new DataTable();
            string query;

            // Simplified version not validating or cleaning arguments in any way
            if (args == null )
            {
                query = sql;
            }
            else
            {
                query = string.Format( sql, args );
            }
            Console.WriteLine( "ExecuteQuery #3 - query = '{0}'", query );

            if ( OpenDatabase() )
            {
                OleDbCommand command = new OleDbCommand( query, conn );
                OleDbDataAdapter adapter = new OleDbDataAdapter( command );
                adapter.Fill( dataTable );
            }
            else
            {
                Console.WriteLine( "ExecuteQuery #9 - cannot open database" );
            }
        }
    }

    class StockHead
    {
        public int sh_id;              // autonumber
        public string sh_ref;          // short text
        public int sh_lineno;          // Number
        public string sh_type;         // short text
        public string sh_supplier;     // short text
        public DateTime sh_datetime;   // date/time

        public StockHead( int id, string refno, int lineno, string type, string supplier, DateTime datetime )
        {
            sh_id = id;
            sh_ref = refno;
            sh_lineno = lineno;
            sh_type = type;
            sh_supplier = supplier;
            sh_datetime = datetime;
        }
    }
}

Data in CSV format, class stock_head shows the Access column types:

1,"#000001",,"IR","INITIAL RESET",20/8/2013 08:33:00
2,"#000002",,"SD","FORMATTING",20/8/2013 08:34:00
3,"#000003",,"SD","FOLDER CREATE",20/8/2013 08:35:00
4,"#000004",,"SD","FOLDER SELECT",20/8/2013 08:35:00
5,"#000005",,"NS","NO SALE",20/8/2013 11:14:00
6,"#000006",,"NS","NO SALE",20/8/2013 11:46:00
7,"#000007",,"NS","NO SALE",20/8/2013 12:16:00
8,"#000008",,"SALE",,20/8/2013 15:11:00
9,"#000009",,"SALE",,20/8/2013 15:30:00
10,"#000010",,"Z1",,20/8/2013 15:32:00
11,"#000011",,"NS","NO SALE",20/8/2013 15:32:00
12,"#000012",,"SALE",,20/8/2013 16:46:00
13,"#000013",,"SALE",,20/8/2013 16:47:00
14,"#000014",,"SALE",,20/8/2013 17:32:00
15,"#000015",,"Z1",,20/8/2013 19:25:00
16,"#000016",,"NS","NO SALE",20/8/2013 19:25:00
17,"#000017",,"Z1",,20/8/2013 21:52:00
18,"#000018",,"NS","NO SALE",20/8/2013 21:52:00
19,"#000019",,"SALE",,23/8/2013 18:27:00
20,"#000020",,"SALE",,23/8/2013 19:06:00
21,"#000021",,"SALE",,23/8/2013 20:24:00
22,"#000022",,"SALE",,23/8/2013 20:36:00
23,"#000023",,"SALE",,23/8/2013 21:21:00
24,"#000024",,"SALE",,23/8/2013 21:57:00
25,"#000025",,"SALE",,23/8/2013 22:38:00
26,"#000026",,"Z1",,23/8/2013 22:40:00
27,"#000027",,"NS","NO SALE",23/8/2013 22:40:00
28,"#000028",,"SALE",,24/8/2013 16:09:00
29,"#000029",,"SALE",,24/8/2013 16:28:00
30,"#000030",,"SALE",,24/8/2013 16:58:00

Body:
If I alter the code creating a StockHead object to use literals instead of the correct values it works.  There must be an elegant way of resolving this!

                StockHead sh = new StockHead(
                    (int)r[ "sh_id" ],
                    (string)r[ "sh_ref" ],
                    0,                          //(int)r[ "sh_lineno" ],
                    (string)r[ "sh_type" ],
                    "",                         //(string)r[ "sh_supplier" ],
                    (DateTime)r[ "sh_datetime" ]);


问:
MYSQL count number of times value is in 3 columns
I have a query that gets some data about customers. This customers can have three phone numbers and these can be repeated.

To count the number of times that these phones are repeated a partner have create a subselect:

```<code>(select count(*)
from TABLE_A as k
where (k.phone=a.phone or k.phone2=a.phone or k.phone3=a.phone)
and k.id!=a.id) as repetitionsPhone1
</code>```

This is inside a bigger select like this:

```<code>    SELECT a.*,c.*,b.*,
    (
        select count(*)
        from TABLE_A as k
        where (k.phone=a.phone or k.phone2=a.phone or k.phone3=a.phone)
        and k.id!=a.id
    ) as repetitionsPhone1
    FROM a
    left join c on a.id=c.id
    left join b on a.id=b.id
</code>```

This query takes for 50 rows about 30 seconds, and it should return about 2000 rows every single day.

To optimize this I use explain and I see that this subquery was the problem so I searched and I tried this:

```<code>SELECT phn,sum(count) as phoneRepetitions
from (
    select k.phone1 as phn, count(*) as count
    from k
    group by k.phone1
        UNION
    select k.phone2 as phn,count(*) as count
    from k
    group by k.phone2
        UNION
    select k.phone3 as phn,count(*) as count
    from k
    group by k.phone3
) as aux
    group by phn
</code>```

And this returns #1062 MYSQL error: Duplicate entry for key 'distinct key'

First of all I would like to solve this problem. Anyone knows what is happening? This error seems logic in an insert statement, but in select?

And later, this will help to improve the big select that I must optimize? I will have to do this for the three columns.

Thank you.

答:
```<code>SELECT
COUNT(*) AS CountOf FROM
  table1
    INNER JOIN
table2
GROUP BY phone1 , phone2 , phone3
HAVING COUNT(*) > 1
</code>```

Body:
I have a query that gets some data about customers. This customers can have three phone numbers and these can be repeated.

To count the number of times that these phones are repeated a partner have create a subselect:

(select count(*)
from TABLE_A as k
where (k.phone=a.phone or k.phone2=a.phone or k.phone3=a.phone)
and k.id!=a.id) as repetitionsPhone1

This is inside a bigger select like this:

    SELECT a.*,c.*,b.*,
    (
        select count(*)
        from TABLE_A as k
        where (k.phone=a.phone or k.phone2=a.phone or k.phone3=a.phone)
        and k.id!=a.id
    ) as repetitionsPhone1
    FROM a
    left join c on a.id=c.id
    left join b on a.id=b.id

This query takes for 50 rows about 30 seconds, and it should return about 2000 rows every single day.

To optimize this I use explain and I see that this subquery was the problem so I searched and I tried this:

SELECT phn,sum(count) as phoneRepetitions
from (
    select k.phone1 as phn, count(*) as count
    from k
    group by k.phone1
        UNION
    select k.phone2 as phn,count(*) as count
    from k
    group by k.phone2
        UNION
    select k.phone3 as phn,count(*) as count
    from k
    group by k.phone3
) as aux
    group by phn

And this returns #1062 MYSQL error: Duplicate entry for key 'distinct key'

First of all I would like to solve this problem. Anyone knows what is happening? This error seems logic in an insert statement, but in select?

And later, this will help to improve the big select that I must optimize? I will have to do this for the three columns.

Thank you.


问:
Group by with average function in scala
Hi I am totally new to spark scala.I need an idea or any sample solution.I have a data like this

```<code>tagid,timestamp,listner,orgid,suborgid,rssi
[4,1496745915,718,4,3,0.30]
[2,1496745915,3878,4,3,0.20]
[4,1496745918,362,4,3,0.60]
[4,1496745913,362,4,3,0.60]
[2,1496745918,362,4,3,0.10]
[3,1496745912,718,4,3,0.05]
[2,1496745918,718,4,3,0.30]
[4,1496745911,1901,4,3,0.60]
[4,1496745912,718,4,3,0.60]
[2,1496745915,362,4,3,0.30]
[2,1496745912,3878,4,3,0.20]
[2,1496745915,1901,4,3,0.30]
[2,1496745910,1901,4,3,0.30]
</code>```

I want to find for each tag and for each listner last 10 seconds timestamp data. Then For the 10 seconds data I need to find average for rssi values.Like this.

```<code>2,1496745918,718,4,3,0.60
2,1496745917,718,4,3,1.30
2,1496745916,718,4,1,2.20
2,1496745914,718,1,2,3.10
2,1496745911,718,1,2,6.10
4,1496745910,1901,1,2,0.30
4,1496745908,1901,1,2,1.30
..........................
..........................
</code>```

Like this I need to find it. Any solution or suggestions is appreciated.
NOTE: I am doing with spark scala.

I tried through spark sql query .But not works properly.

```<code>val filteravg = avg.registerTempTable("avg")
val avgfinal = sqlContext.sql("SELECT tagid,timestamp,listner FROM (SELECT tagid,timestamp,listner,dense_rank() OVER (PARTITION BY _c6 ORDER BY _c5 ASC) as rank FROM avg) tmp WHERE rank <= 10")
avgfinal.collect.foreach(println)
</code>```

I am trying through array also.Any help will be appreciated.

Title: Group by with average function in scala

Body:
Hi I am totally new to spark scala.I need an idea or any sample solution.I have a data like this

tagid,timestamp,listner,orgid,suborgid,rssi
[4,1496745915,718,4,3,0.30]
[2,1496745915,3878,4,3,0.20]
[4,1496745918,362,4,3,0.60]
[4,1496745913,362,4,3,0.60]
[2,1496745918,362,4,3,0.10]
[3,1496745912,718,4,3,0.05]
[2,1496745918,718,4,3,0.30]
[4,1496745911,1901,4,3,0.60]
[4,1496745912,718,4,3,0.60]
[2,1496745915,362,4,3,0.30]
[2,1496745912,3878,4,3,0.20]
[2,1496745915,1901,4,3,0.30]
[2,1496745910,1901,4,3,0.30]

I want to find for each tag and for each listner last 10 seconds timestamp data. Then For the 10 seconds data I need to find average for rssi values.Like this.

2,1496745918,718,4,3,0.60
2,1496745917,718,4,3,1.30
2,1496745916,718,4,1,2.20
2,1496745914,718,1,2,3.10
2,1496745911,718,1,2,6.10
4,1496745910,1901,1,2,0.30
4,1496745908,1901,1,2,1.30
..........................
..........................

Like this I need to find it. Any solution or suggestions is appreciated.
NOTE: I am doing with spark scala.

I tried through spark sql query .But not works properly.

val filteravg = avg.registerTempTable("avg")
val avgfinal = sqlContext.sql("SELECT tagid,timestamp,listner FROM (SELECT tagid,timestamp,listner,dense_rank() OVER (PARTITION BY _c6 ORDER BY _c5 ASC) as rank FROM avg) tmp WHERE rank <= 10")
avgfinal.collect.foreach(println)

I am trying through array also.Any help will be appreciated.

Body:
If you already have a dataframe as

+-----+----------+-------+-----+--------+----+
|tagid|timestamp |listner|orgid|suborgid|rssi|
+-----+----------+-------+-----+--------+----+
|4    |1496745915|718    |4    |3       |0.30|
|2    |1496745915|3878   |4    |3       |0.20|
|4    |1496745918|362    |4    |3       |0.60|
|4    |1496745913|362    |4    |3       |0.60|
|2    |1496745918|362    |4    |3       |0.10|
|3    |1496745912|718    |4    |3       |0.05|
|2    |1496745918|718    |4    |3       |0.30|
|4    |1496745911|1901   |4    |3       |0.60|
|4    |1496745912|718    |4    |3       |0.60|
|2    |1496745915|362    |4    |3       |0.30|
|2    |1496745912|3878   |4    |3       |0.20|
|2    |1496745915|1901   |4    |3       |0.30|
|2    |1496745910|1901   |4    |3       |0.30|
+-----+----------+-------+-----+--------+----+

Doing the following should work for you

  df.withColumn("firstValue", first("timestamp") over Window.orderBy($"timestamp".desc).partitionBy("tagid"))
  .filter($"firstValue".cast("long")-$"timestamp".cast("long") < 10)
  .withColumn("average", avg("rssi") over Window.partitionBy("tagid"))
  .drop("firstValue")
  .show(false)

you should have output as

+-----+----------+-------+-----+--------+----+-------------------+
|tagid|timestamp |listner|orgid|suborgid|rssi|average            |
+-----+----------+-------+-----+--------+----+-------------------+
|3    |1496745912|718    |4    |3       |0.05|0.05               |
|4    |1496745918|362    |4    |3       |0.60|0.54               |
|4    |1496745915|718    |4    |3       |0.30|0.54               |
|4    |1496745913|362    |4    |3       |0.60|0.54               |
|4    |1496745912|718    |4    |3       |0.60|0.54               |
|4    |1496745911|1901   |4    |3       |0.60|0.54               |
|2    |1496745918|362    |4    |3       |0.10|0.24285714285714288|
|2    |1496745918|718    |4    |3       |0.30|0.24285714285714288|
|2    |1496745915|3878   |4    |3       |0.20|0.24285714285714288|
|2    |1496745915|362    |4    |3       |0.30|0.24285714285714288|
|2    |1496745915|1901   |4    |3       |0.30|0.24285714285714288|
|2    |1496745912|3878   |4    |3       |0.20|0.24285714285714288|
|2    |1496745910|1901   |4    |3       |0.30|0.24285714285714288|
+-----+----------+-------+-----+--------+----+-------------------+


问:
Can't assign a specific class name to a collection of div's using JavaScript/jQuery
Hi ) I have a task and have done only a half of it, need some help:

need to make a board of 10/10 div's;

need to assign to each div a common class "box" and a specific one "box-x-y", where x and y are coordinates of the div;

I can't do the second task (the last half), for example for first div the class should be "box-1-1", and so on, like in the picture I have attached.
Image

  for(var i = 0; i < 10; i++) {
      for (var j = 0; j < 10; j++){
          $("

").addClass("box").appendTo("#carousel");
      }
      $("

").css("clear", "both").appendTo("#carousel");
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
    float:left;
    width:50px;
    height:50px;
    margin-right:2px;
    margin-bottom:2px;
    border: 1px solid black;
}</code>```

```

答:
As i said in the comment you can do that by adding for loop variable in the addclass function addClass("box box-"+i+"-"+j). Now we are adding two classes into div .box and .box-dynamic-number, the first one while apply the css on the div and second is your requirement.

  for(var i = 0; i < 10; i++) {
      for (var j = 0; j < 10; j++){

          $("
box-"+i+"-"+j+"
").addClass("box box-"+i+"-"+j).appendTo("#carousel");
      }
      $("

").css("clear", "both").appendTo("#carousel");
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
    float:left;
    width:50px;
    height:50px;
    margin-right:2px;
    margin-bottom:2px;
    border: 1px solid black;
}</code>```

```

Body:
Hi ) I have a task and have done only a half of it, need some help:

need to make a board of 10/10 div's;

need to assign to each div a common class "box" and a specific one "box-x-y", where x and y are coordinates of the div;

I can't do the second task (the last half), for example for first div the class should be "box-1-1", and so on, like in the picture I have attached.
Image

  for(var i = 0; i < 10; i++) {
      for (var j = 0; j < 10; j++){
          $("

").addClass("box").appendTo("#carousel");
      }
      $("

").css("clear", "both").appendTo("#carousel");
  }

.box {
    float:left;
    width:50px;
    height:50px;
    margin-right:2px;
    margin-bottom:2px;
    border: 1px solid black;
}

Body:
As i said in the comment you can do that by adding for loop variable in the addclass function addClass("box box-"+i+"-"+j). Now we are adding two classes into div .box and .box-dynamic-number, the first one while apply the css on the div and second is your requirement.

  for(var i = 0; i < 10; i++) {
      for (var j = 0; j < 10; j++){

          $("<div>box-"+i+"-"+j+"</div>").addClass("box box-"+i+"-"+j).appendTo("#carousel");
      }
      $("<div></div>").css("clear", "both").appendTo("#carousel");
  }

.box {
    float:left;
    width:50px;
    height:50px;
    margin-right:2px;
    margin-bottom:2px;
    border: 1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div id="carousel">

  </div>


问:
Google Maps API: Get url for current view
I have a form where users can introduce google maps urls to specify the address of some stuff.
I've been thinking in showing a map through Google Map API v3, letting user move to desired location and through a button or something automatically get the url of the place and copy it to an input.

I've been able to display the map using the tutorial, but I haven't been able to find in the documentation how I could get the url...

I think you will not need it, but this is the simple code I'm using:

```<code>var latlng = new google.maps.LatLng(-34.397, 150.644);
var options = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById('map-box'), options );
</code>```

答: I'd suggest using map.getCenter().toUrlValue() and map.getZoom() to obtain the centre and zoom state of the current map view. That information should let you build a URI that you can then use, bare in mind that you'll need to write some code to take the values off the URI and pass them to the map API.

ContentLicense: CC BY-SA 2.5

Body:
I have a form where users can introduce google maps urls to specify the address of some stuff.
I've been thinking in showing a map through Google Map API v3, letting user move to desired location and through a button or something automatically get the url of the place and copy it to an input.

I've been able to display the map using the tutorial, but I haven't been able to find in the documentation how I could get the url...

I think you will not need it, but this is the simple code I'm using:

var latlng = new google.maps.LatLng(-34.397, 150.644);
var options = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById('map-box'), options );


问:
Python: Turn a 2D numpy array into a dictionary
consider I have an array like:

```<code>c = [["a","b","a"],[1,2,3]]
</code>```

Now I need to combine those two parts and I want to turn this into a dictionary, which counts how often a combination occurs(the values are the number of occurances).
It should look something like this:

```<code>combinations = {("a",1):1, ("b",2):1, ("a",3):1)}
</code>```

I am a total beginner and have some approaches like:

```<code>(c[0][0],[-1][0]),(c[0][1],[-1][1]),...
</code>```

etc. for creating the pairs I need, but this is not very useful in case my array is of different size(both parts should stay the same size though). Plus I don't know how to put the number of occurances as values.

Any help is highly appreciated!

答:
You can use zip to combine the 2 sublists and count to count specific elements in the list.

```<code>    >>> c = [['a','b','a','a'],[1,2,3,1]]
    >>> pairs = zip(c[0],c[1])
    >>> pairs
    [('a', 1), ('b', 2), ('a', 3), ('a', 1)]

    >>> result = {i: pairs.count(i) for i in pairs}
    >>> result
    {('a', 1): 2, ('b', 2): 1, ('a', 3): 1}
</code>```

The last command uses Dict Comprehension.

Body:
consider I have an array like:

c = [["a","b","a"],[1,2,3]]

Now I need to combine those two parts and I want to turn this into a dictionary, which counts how often a combination occurs(the values are the number of occurances).
It should look something like this:

combinations = {("a",1):1, ("b",2):1, ("a",3):1)}

I am a total beginner and have some approaches like:

(c[0][0],[-1][0]),(c[0][1],[-1][1]),...

etc. for creating the pairs I need, but this is not very useful in case my array is of different size(both parts should stay the same size though). Plus I don't know how to put the number of occurances as values.

Any help is highly appreciated!

Body:
You can use zip to combine the 2 sublists and count to count specific elements in the list.

    >>> c = [['a','b','a','a'],[1,2,3,1]]
    >>> pairs = zip(c[0],c[1])
    >>> pairs
    [('a', 1), ('b', 2), ('a', 3), ('a', 1)]

    >>> result = {i: pairs.count(i) for i in pairs}
    >>> result
    {('a', 1): 2, ('b', 2): 1, ('a', 3): 1}

The last command uses Dict Comprehension.


问:
How can I return the matched value from env::var?
If the environment variable SOMEVALUE is found, it should be bound to k:

```<code>let k = match env::var(SOMEVALUE) {
    Ok(val) => {return val},
    Err(e) => println!("could not find {}: {}", SOMEVALUE, e),
};
</code>```

Compiling this code gives the following error

   |
11 |         Ok(val) => {return val},
   |                            ^^^ expected (), found struct `std::string::String`
   |
   = note: expected type `()`
              found type `std::string::String`
```

答:
What Victor wrote is correct, but you probably want to actually bind a value to k; in that case you should change your code to:

```<code>let k = match env::var(SOMEVALUE) {
    Ok(val) => val,
    Err(e) => panic!("could not find {}: {}", SOMEVALUE, e),
};
</code>```

Equivalently, you can use Result::unwrap_or_else:

```<code>let k = env::var(SOMEVALUE).unwrap_or_else(|e| {
    panic!("could not find {}: {}", SOMEVALUE, e)
});
</code>```

Body:
If the environment variable SOMEVALUE is found, it should be bound to k:

let k = match env::var(SOMEVALUE) {
    Ok(val) => {return val},
    Err(e) => println!("could not find {}: {}", SOMEVALUE, e),
};

Compiling this code gives the following error

   |
11 |         Ok(val) => {return val},
   |                            ^^^ expected (), found struct `std::string::String`
   |
   = note: expected type `()`
              found type `std::string::String`

Body:
What Victor wrote is correct, but you probably want to actually bind a value to k; in that case you should change your code to:

let k = match env::var(SOMEVALUE) {
    Ok(val) => val,
    Err(e) => panic!("could not find {}: {}", SOMEVALUE, e),
};

Equivalently, you can use Result::unwrap_or_else:

let k = env::var(SOMEVALUE).unwrap_or_else(|e| {
    panic!("could not find {}: {}", SOMEVALUE, e)
});

ContentLicense: CC BY-SA 4.0


问:
Wordpress woo-commerce merge price before create grand total of product
I have created some attributes like length, service, color, sizes and also created variation for length & services.

when i view product all things are showing perfectly but actually i want when select any product length  and select  any services than price will be meagre.

i.e.  let us suppose

```<code> select  length 10     = 1200

 select services  Recomb  = `35`
 $total= `1235`
</code>```

How could this possible in woo-commerce ?

Is woo-commerce providing any plugin for this ?

答:
you need to crate variable product and setup attributes then used that attributes for variation. create required variation and setup different price for each variation as per your requirement.

check below woocommerce docs for more info.
https://docs.woocommerce.com/document/variable-product/

Body:
I have created some attributes like length, service, color, sizes and also created variation for length & services.

when i view product all things are showing perfectly but actually i want when select any product length  and select  any services than price will be meagre.

i.e.  let us suppose

 select  length 10     = 1200

 select services  Recomb  = `35`
 $total= `1235`

How could this possible in woo-commerce ?

Is woo-commerce providing any plugin for this ?


问:
How can I check if an app running on Android?
I am an Android developer and I want to write an if statement in my application. In this statement I want to check if the default browser (browser in Android OS) is running. How can I do this programmatically?

答:
You can check it by the following method</p>

```<code>public static boolean isRunning(Context ctx) {
    ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);

    List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

    for (ActivityManager.RunningTaskInfo task : tasks) {
        if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName()))
            return true;
    }
    return false;
}
</code>```

Body:
You can check it by the following method

public static boolean isRunning(Context ctx) {
    ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);

    List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

    for (ActivityManager.RunningTaskInfo task : tasks) {
        if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName()))
            return true;
    }
    return false;
}


问:
Programaticly Limiting number of rows for mysql database using VB.net
Good day I have written a function that needs to limit the number of employees that can be added to the database.

```<code>    <WebMethod()>
Public Function EmployeeSubToken()
    Dim cmd As New SqlCommand("Select vchSubscriptionType FROM BillingInfo", con)
    Dim subtype = "vchSubscriptionType"
    Dim Token

    Select Case subtype
        Case subtype = "Bronze"
            Token = 1
        Case subtype = "Silver"
            Token = 2
        Case subtype = "Gold"
            Token = 3
        Case subtype = "Platinum"
            Token = 4
    End Select

    Dim cmd2

    Select Case Token
        Case Token = 1
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 5")
        Case Token = 2
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 10")
        Case Token = 3
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 25")
        Case Token = 4
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment")
    End Select

End Function
</code>```

Does anyone know how If this is the correct way of doing it? if it is not how would I accomplish this?

答:
if you want to limit the inserts, have a function that will query your database and return a count of rows,  SELECT COUNT(*) FROM dtEmployment ; then just use a simple if,

```<code>if(dtEmploymentCount < MydesiredCount) then
'Do My Insert

else
'Return your message (Maximum amount of entries reached)
end If
</code>```

Body:
Good day I have written a function that needs to limit the number of employees that can be added to the database.

    <WebMethod()>
Public Function EmployeeSubToken()
    Dim cmd As New SqlCommand("Select vchSubscriptionType FROM BillingInfo", con)
    Dim subtype = "vchSubscriptionType"
    Dim Token

    Select Case subtype
        Case subtype = "Bronze"
            Token = 1
        Case subtype = "Silver"
            Token = 2
        Case subtype = "Gold"
            Token = 3
        Case subtype = "Platinum"
            Token = 4
    End Select

    Dim cmd2

    Select Case Token
        Case Token = 1
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 5")
        Case Token = 2
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 10")
        Case Token = 3
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 25")
        Case Token = 4
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment")
    End Select

End Function

Does anyone know how If this is the correct way of doing it? if it is not how would I accomplish this?

Body:
if you want to limit the inserts, have a function that will query your database and return a count of rows,  SELECT COUNT(*) FROM dtEmployment ; then just use a simple if,

if(dtEmploymentCount < MydesiredCount) then
'Do My Insert

else
'Return your message (Maximum amount of entries reached)
end If


问:
How to configure RAD7.5 to use some predefined filters
I am using RAD7.5 for the project development. My web.xml file looks like this:

```<code> <context-param>
  <param-name>config.file</param-name>
  <param-value>@project.config.location@</param-value>
</context-param>
</code>```

So basically @project.config.location@ is retrieved from a properties file(config.properties) during the ant-build process using the filterset code as shown below:

```<code><copy todir="${project.build.dir}">
        <fileset dir="${web.project.webcontent.dir}" excludes="**/classes/**" />
        <filterset>
            <filtersfile file="${web.project.src.dir}/filters/${file.filter.name}" />
        </filterset>

    </copy>
</code>```

So my problem is how to configure RAD7.5 so that while deploying the app locally(right click on the project EAR -> run on server) will replace these filters. I have been trying to find the solution but could not find anything on the web yet.Any suggestions?

答:
This project was designed in the other IDE which dealt with ANT. Also I cannot change the process because ANT is the standard builder for the company, when it comes to deploy the project.All the configuration managers use Ant.I just want to make it compatible with both the options. I liked your first suggestion i.e. to have ant builder in properties->builders of your project. How do I do that. I did this so far... Right Click on the project->Properties->Builders. I wanted only to apply that filter while deploying the app.So since I want to keep @....@ filters in my web.xml. Is there a way to tell RAD when It is deploying the app to the server just apply that filter(shown below) process on it's way(I just want to modify the default deploy process in the RAD):</p>

```<code><filterset>
                <filtersfile file="${web.project.src.dir}/filters/${file.filter.name}" />
            </filterset>
</code>```

Body:
I am using RAD7.5 for the project development. My web.xml file looks like this:

 <context-param>
  <param-name>config.file</param-name>
  <param-value>@project.config.location@</param-value>
</context-param>

So basically @project.config.location@ is retrieved from a properties file(config.properties) during the ant-build process using the filterset code as shown below:

<copy todir="${project.build.dir}">
        <fileset dir="${web.project.webcontent.dir}" excludes="**/classes/**" />
        <filterset>
            <filtersfile file="${web.project.src.dir}/filters/${file.filter.name}" />
        </filterset>

    </copy>

So my problem is how to configure RAD7.5 so that while deploying the app locally(right click on the project EAR -> run on server) will replace these filters. I have been trying to find the solution but could not find anything on the web yet.Any suggestions?

Body:
This project was designed in the other IDE which dealt with ANT. Also I cannot change the process because ANT is the standard builder for the company, when it comes to deploy the project.All the configuration managers use Ant.I just want to make it compatible with both the options. I liked your first suggestion i.e. to have ant builder in properties->builders of your project. How do I do that. I did this so far... Right Click on the project->Properties->Builders. I wanted only to apply that filter while deploying the app.So since I want to keep @....@ filters in my web.xml. Is there a way to tell RAD when It is deploying the app to the server just apply that filter(shown below) process on it's way(I just want to modify the default deploy process in the RAD):

<filterset>
                <filtersfile file="${web.project.src.dir}/filters/${file.filter.name}" />
            </filterset>


问:
Exception in thread "main" java.lang.IllegalStateException: The driver executable does not exist: /Users/Golcha/Desktop/Automation/geckodriver.exe
Getting the following error

Exception in thread "main" java.lang.IllegalStateException: The driver
  executable does not exist:
  /Users/Golcha/Desktop/Automation/geckodriver.exe

Code:

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class selenium{

    private static WebDriver driver;

    public static void main(String[]args){

        System.setProperty("webdriver.gecko.driver","Users/Golcha/Desktop/Automation/geckodriver.exe");

        setDriver(new FirefoxDriver());
    }

    public static WebDriver getDriver() {
        return driver;
    }

    public static void setDriver(WebDriver driver) {
        selenium.driver = driver;
    }

}
</code>```

答:
Try below code but check the path of geckodriver properly before executing the below code or I ll suggest you to paste geckodriver in C drive or any other drives to make your path simple as below one :

```<code>System.setProperty("webdriver.firefox.marionette", "C:\\geckodriver.exe");
</code>```

It should work without any problem .  All the best !

Body:
Getting the following error

Exception in thread "main" java.lang.IllegalStateException: The driver
  executable does not exist:
  /Users/Golcha/Desktop/Automation/geckodriver.exe

Code:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class selenium{

    private static WebDriver driver;

    public static void main(String[]args){

        System.setProperty("webdriver.gecko.driver","Users/Golcha/Desktop/Automation/geckodriver.exe");

        setDriver(new FirefoxDriver());
    }

    public static WebDriver getDriver() {
        return driver;
    }

    public static void setDriver(WebDriver driver) {
        selenium.driver = driver;
    }

}

Body:
Try below code but check the path of geckodriver properly before executing the below code or I ll suggest you to paste geckodriver in C drive or any other drives to make your path simple as below one :

System.setProperty("webdriver.firefox.marionette", "C:\\geckodriver.exe");

It should work without any problem .  All the best !


问:
Regex in python to group files based on matching start and end of file name
I have a bunch of jpg files with names like these:

```<code>1_fileid1_1.jpg
2_fileid1_1.jpg
1_fileid1_2.jpg
2_fileid1_2.jpg
...
1_fileidn_m.jpg
2_fileidn_m+1.jpg
</code>```

The first number is from a sequence of 2 parts so part 1 of file with id fileid1 starts with 1_ and part 2 with 2_. The last number is the page because these are image files created from documents so the _1 is page 1, _2 is page 2 and so on. The pages could be any number but the parts are always just 2 for each page.

Now I want to read these files so that I can group them in a sequence maybe in a tuple or list so the sequences should look something like.

```<code>seq1 = (1_fileid1_1.jpg, 2_fileid1_1.jpg)
seq2 = (1_fileid1_2.jpg, 2_fileid1_2.jpg)
...
seqx = (1_fileidn_m.jpg, 2_fileidn_m.jpg)
</code>```

Each page of each file is a different sequence.

Is there a simple way to do this in python? maybe using re.match? But how can I make sure that the two files in one sequence have the same ending, i.e. _1.jpg (including the .jpg is useful because then I could avoid other types of files in case there are).

Edit:
Rizman's solution works fine if the files are on separate lines. What if the files's names are all together on a list and together with the files' paths? Like this:

```<code>../path/to/file1/1_file1_1.jpg/path/to_file2/2_file1_1.jpg...
</code>```

I tried modifying Rizwan's solution like this: https://regex101.com/r/HvzkwL/5/

But it doesn't work.

答:
Updated as per the change in the op's post:

use this:

```<code>(.*?/\d+(_.*?\.jpg))(.*?/)(\d+)\2
</code>```

and replace by this:

```<code>\($1,$3$4$2\)
</code>```

Updated Demo

You can try this approach:

```<code>(\d+(_[^\.]+\.jpg))\n(\d+)\2
</code>```

And replace by this:

```<code>($1,$3$2)
</code>```

Regex101Demo

Body:
I have a bunch of jpg files with names like these:

1_fileid1_1.jpg
2_fileid1_1.jpg
1_fileid1_2.jpg
2_fileid1_2.jpg
...
1_fileidn_m.jpg
2_fileidn_m+1.jpg

The first number is from a sequence of 2 parts so part 1 of file with id fileid1 starts with 1_ and part 2 with 2_. The last number is the page because these are image files created from documents so the _1 is page 1, _2 is page 2 and so on. The pages could be any number but the parts are always just 2 for each page.

Now I want to read these files so that I can group them in a sequence maybe in a tuple or list so the sequences should look something like.

seq1 = (1_fileid1_1.jpg, 2_fileid1_1.jpg)
seq2 = (1_fileid1_2.jpg, 2_fileid1_2.jpg)
...
seqx = (1_fileidn_m.jpg, 2_fileidn_m.jpg)

Each page of each file is a different sequence.

Is there a simple way to do this in python? maybe using re.match? But how can I make sure that the two files in one sequence have the same ending, i.e. _1.jpg (including the .jpg is useful because then I could avoid other types of files in case there are).

Edit:
Rizman's solution works fine if the files are on separate lines. What if the files's names are all together on a list and together with the files' paths? Like this:

../path/to/file1/1_file1_1.jpg/path/to_file2/2_file1_1.jpg...

I tried modifying Rizwan's solution like this: https://regex101.com/r/HvzkwL/5/

But it doesn't work.

Body:
Updated as per the change in the op's post:

use this:

(.*?/\d+(_.*?\.jpg))(.*?/)(\d+)\2

and replace by this:

\($1,$3$4$2\)

Updated Demo

You can try this approach:

(\d+(_[^\.]+\.jpg))\n(\d+)\2

And replace by this:

($1,$3$2)

Regex101Demo


问:
VueJS: Using A Loading Icon When Waiting For Results Of Asynchronous Database Calls
I wonder where and how to setup a loading icon in VueJS, when the data my site depends on, isn't ready.

Do you know how to do this?

Would be nice and helpful.

答:
Considering you are using axios which is currently the most used http client for vue.js you would do something like

```<code>data: function() {
  return { results: [], loading: true};
}
</code>```

And now let's say you load on create

```<code>created: function() {
  axios.get('/path/to/my/data/endpoint')
    .then(function(response) {
      this.result = response.data;
      this.loading = false;
    }.bind(this))
    .catch(function() {
      this.loading = false;
    }.bind(this));
}
</code>```

And in your template you have something like

```<code><img src="/path/to/my/loading/icon" v-if="loading" />

<ul v-else>
  <li v-for="result in results"> ... </li>
</ul>
</code>```

Body:
Considering you are using axios which is currently the most used http client for vue.js you would do something like

data: function() {
  return { results: [], loading: true};
}

And now let's say you load on create

created: function() {
  axios.get('/path/to/my/data/endpoint')
    .then(function(response) {
      this.result = response.data;
      this.loading = false;
    }.bind(this))
    .catch(function() {
      this.loading = false;
    }.bind(this));
}

And in your template you have something like

<img src="/path/to/my/loading/icon" v-if="loading" />

<ul v-else>
  <li v-for="result in results"> ... </li>
</ul>


问:
Configuring Jest to mimic webpack resolve root and resolve alias
I am working on setting up a project with Webpack & Jest. At the moment Webpack resolve configurations cause complications with Jest tests. In my webpack config I have the following options set:

```<code>  resolve: {
    root: [__dirname + "/src/" ],
    extensions: ['', '.js', '.coffee', '.jsx', '.css', '.scss', '.svg']
  }
</code>```

This lets me require assets and modules with:

```<code>import UnknownImg from 'assets/unknown';
</code>```

The above actually lives (relative to my project root) src/assets/unknown.svg.

However, when I run the test for files with lines like the above I get errors when resolving the path to that required module/asset.

Error: /Users/byronsm/dev/nerve-center/src/components/organisms/system_status.jsx: Cannot find module 'assets/unknown' from '/Users/byronsm/dev/nerve-center/src/components/organisms'

In this case it appears to  be doing a relative lookup of the imported module path. Is there a way for me to get Jest to behave the same as Webpack?

答:
You can use Jest 20+ resolver option and plug it with jest-webpack-resolver

This package does not seem mature (several days old) but does the job for me. Also, as of now, it requires Jest config to be in a separate jest.config.js file or provided via CLI (does not support package.json).

Body:
I am working on setting up a project with Webpack & Jest. At the moment Webpack resolve configurations cause complications with Jest tests. In my webpack config I have the following options set:

  resolve: {
    root: [__dirname + "/src/" ],
    extensions: ['', '.js', '.coffee', '.jsx', '.css', '.scss', '.svg']
  }

This lets me require assets and modules with:

import UnknownImg from 'assets/unknown';

The above actually lives (relative to my project root) src/assets/unknown.svg.

However, when I run the test for files with lines like the above I get errors when resolving the path to that required module/asset.

Error: /Users/byronsm/dev/nerve-center/src/components/organisms/system_status.jsx: Cannot find module 'assets/unknown' from '/Users/byronsm/dev/nerve-center/src/components/organisms'

In this case it appears to  be doing a relative lookup of the imported module path. Is there a way for me to get Jest to behave the same as Webpack?


问:
Is there a way to simulate the 2016 MacBook Pro's TouchBar in Xcode 8.1?
I'm looking to write a program tailored to the announced, but not-yet-released MacBook Pro with Touch Bar. Is there a way to simulate the Touch Bar similar to the way iPhone/Apple Watch apps can be simulated from Xcode?</p>

答: Command + Shift + 8 is the shortcut for same</p>


问:
Python regex matching problem
I have been parsing a GraphViz file for a specific identifer using Regex. Here is the typical content from this file:

```<code>node10 [label="second-messenger-mediated signaling\nGO:0019932", fontname=Courier, ...];

node11 [label="inositol phosphate-mediated signaling\nGO:0048016", fontname=Courier, ...];

node12 [label="activation of phospholipase C activity by G-protein coupled receptor protein signaling pathway coupled to IP3 second messenger\n\

GO:0007200", fontname=Courier, ...];

node13 [label="G-protein coupled receptor protein signaling pathway\nGO:0007186", fontname=Courier, ...];

node14 [label="activation of phospholipase C activity\nGO:0007202", fontname=Courier, ...];

node15 [label="elevation of cytosolic calcium ion concentration involved in G-protein signaling coupled to IP3 second messenger\nGO:0051482", fontname=Courier, pos="798,1162", width="9.56", height="0.50"];
</code>```

Since I am only interested in the nodeid, label and the GO identifier I have used the following regex to match each line:

```<code>(node\d*)\s\[label=\"([\w\s-]*).*(GO:\d*)
</code>```

I know that it's neither terribly elegant nor very efficient but it got the job done except for the line with node12. I have tried using re.DOTALL and re.MULTILINE but to no avail.

Can anyone help me spot the missing piece of the puzzle to make the regex also work with node12 ?

**EDIT:

Here [1] is a link to the file that contains one of those lines.

[1] http://amigo.geneontology.org/cgi-bin/amigo/term-details.cgi?session_id=7924amigo1292519756&term=GO:0051482&format=dot

答:
Don't reinvent the wheel.

pydot is a library which parses dot files using pyparsing.

Title: Python regex matching problem

Body:
I have been parsing a GraphViz file for a specific identifer using Regex. Here is the typical content from this file:

node10 [label="second-messenger-mediated signaling\nGO:0019932", fontname=Courier, ...];

node11 [label="inositol phosphate-mediated signaling\nGO:0048016", fontname=Courier, ...];

node12 [label="activation of phospholipase C activity by G-protein coupled receptor protein signaling pathway coupled to IP3 second messenger\n\

GO:0007200", fontname=Courier, ...];

node13 [label="G-protein coupled receptor protein signaling pathway\nGO:0007186", fontname=Courier, ...];

node14 [label="activation of phospholipase C activity\nGO:0007202", fontname=Courier, ...];

node15 [label="elevation of cytosolic calcium ion concentration involved in G-protein signaling coupled to IP3 second messenger\nGO:0051482", fontname=Courier, pos="798,1162", width="9.56", height="0.50"];

Since I am only interested in the nodeid, label and the GO identifier I have used the following regex to match each line:

(node\d*)\s\[label=\"([\w\s-]*).*(GO:\d*)

I know that it's neither terribly elegant nor very efficient but it got the job done except for the line with node12. I have tried using re.DOTALL and re.MULTILINE but to no avail.

Can anyone help me spot the missing piece of the puzzle to make the regex also work with node12 ?

**EDIT:

Here [1] is a link to the file that contains one of those lines.

[1] http://amigo.geneontology.org/cgi-bin/amigo/term-details.cgi?session_id=7924amigo1292519756&term=GO:0051482&format=dot


问:
Getting Error when try to get the ZoneName from DNS
Getting Error when try to get the ZoneName from DNS.

```<code>$zoneNames = (Get-DnsServerZone | Where-Object {
    $_.IsReverseLookupZone -eq $true
}).ZoneName
</code>```

Error Message:

The term 'Get-DnsServerZone' is not recognized as the name of a cmdlet, function, script file, or operable program.

答:
As mentioned in the comments, the DnsServer module that contains the Get-DnsServerZone cmdlet ships with Windows Server 2012 and newer.

On 2008 R2, you'll have to use either dnscmd or query the MicrosoftDNS WMI namespace on the target DNS server:

```<code>$ZoneNames = (Get-WmiObject -Namespace root\MicrosoftDNS -Class MicrosoftDNS_Zone -Filter 'Reverse = true' -ComputerName targetdnsserver.domain.tld).Name
</code>```

Body:
Getting Error when try to get the ZoneName from DNS.

$zoneNames = (Get-DnsServerZone | Where-Object {
    $_.IsReverseLookupZone -eq $true
}).ZoneName

Error Message:

The term 'Get-DnsServerZone' is not recognized as the name of a cmdlet, function, script file, or operable program.

Body:
As mentioned in the comments, the DnsServer module that contains the Get-DnsServerZone cmdlet ships with Windows Server 2012 and newer.

On 2008 R2, you'll have to use either dnscmd or query the MicrosoftDNS WMI namespace on the target DNS server:

$ZoneNames = (Get-WmiObject -Namespace root\MicrosoftDNS -Class MicrosoftDNS_Zone -Filter 'Reverse = true' -ComputerName targetdnsserver.domain.tld).Name


问:
Equivalent of Angular 2's service in Vue 2
I am getting my hands dirty at Vue 2 and trying to relate how it compares with Vue 2.

In Angular 2 I would have service and inject it inside Providers so service would have a single instance. I would write API calls inside my service calls.

Where would I write the service calls in Vue 2 project so I don't have to copy paste my API calls everywhere?

Thank you.

答:
There are 3 ways:

Stateless service: then you should use mixins

Statefull service: use Vuex

Export service and import from a vue code

any javascript global object


问:
how to display middle name as middle initial if middle name have two words
so i created a form which have middle name field and display the middle name as initial.

preg_split("/[\s,_-]+/",$data["s_mname"])

this code works IF the middle name is only one word.. like Snow it will display as S but my problem is if the middle name is 2 words like De Leon, Delos Santos the initial that will be displayed is DL,DS.. but it should display as D... any idea how to do this..

SUBSTR($data["s_mname"],strrchr($data["s_mname"], ' '), 1)

i tried this code but nothing works i just got this from other site..

答:
Use explode() like this:-

```<code>preg_split("/[\s,_-]+/",explode(' ',$data["s_mname"])[0])
</code>```

Output:- https://eval.in/828658

Body:
Use explode() like this:-

preg_split("/[\s,_-]+/",explode(' ',$data["s_mname"])[0])

Output:- https://eval.in/828658


问:
onClick not triggered on LinearLayout with child
I've got a custom LinearLayout with a smaller TextView child. I'd like to be able to click the area not covered by the TextView, so I set clickable=true and an onclicklistener to the LinearLayout, but onClick is not triggered. If I set the onclick listener on the TextView it works as expected...

Anybody can help?

ar_item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ar_item" android:layout_width="202dp"
    android:layout_height="62dp" android:background="@drawable/bg_item_ar"
    android:clickable="true">

    <TextView android:id="@+id/ar_item_txt"
        android:layout_width="164dp" android:layout_height="fill_parent"
        android:paddingBottom="8dp" android:paddingLeft="8dp"
        android:paddingTop="8dp" android:paddingRight="6dp" android:gravity="center"
        android:background="#50000000" />

</LinearLayout>
</code>```

My custom LinearLayout

```<code>public class ARView extends LinearLayout
{

    public ARView(final Context context, String name, String id)
    {
        super(context);
        getLayoutInflater().inflate(R.layout.ar_item, this ,true);
        LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.ar_item, null);

        TextView textView = (TextView) findViewById(R.id.ar_item_txt);
        textView.setText(name);

        setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Toast t = Toast.makeText(context, "hey!", Toast.LENGTH_SHORT);
                t.show();
            }
        });
    }
}
</code>```

答:
Add the following attributes to the linearlayout
Any Click events not handled by the child views will be automatically passed over to the LinearLayout.</p>

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    android:focusable="true"
    android:clickable="true">

<child/>
<child/>

</LinearLayout>
</code>```

Body:
I've got a custom LinearLayout with a smaller TextView child. I'd like to be able to click the area not covered by the TextView, so I set clickable=true and an onclicklistener to the LinearLayout, but onClick is not triggered. If I set the onclick listener on the TextView it works as expected...

Anybody can help?

ar_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ar_item" android:layout_width="202dp"
    android:layout_height="62dp" android:background="@drawable/bg_item_ar"
    android:clickable="true">

    <TextView android:id="@+id/ar_item_txt"
        android:layout_width="164dp" android:layout_height="fill_parent"
        android:paddingBottom="8dp" android:paddingLeft="8dp"
        android:paddingTop="8dp" android:paddingRight="6dp" android:gravity="center"
        android:background="#50000000" />

</LinearLayout>

My custom LinearLayout

public class ARView extends LinearLayout
{

    public ARView(final Context context, String name, String id)
    {
        super(context);
        getLayoutInflater().inflate(R.layout.ar_item, this ,true);
        LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.ar_item, null);

        TextView textView = (TextView) findViewById(R.id.ar_item_txt);
        textView.setText(name);

        setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Toast t = Toast.makeText(context, "hey!", Toast.LENGTH_SHORT);
                t.show();
            }
        });
    }
}

Body:
Add the following attributes to the linearlayout
Any Click events not handled by the child views will be automatically passed over to the LinearLayout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    android:focusable="true"
    android:clickable="true">

<child/>
<child/>

</LinearLayout>


问:
Detect if cookies are enabled in the browser
The code below works in all current browser except for IE.  In IE the message doesn't display.

```<code>  if (navigator.cookieEnabled == 0) {
    document.write("Cookies are not enabled.");
    }
</code>```

Can someone tell me what I can do to make the above code work in IE 10 & 11?

I've tried code that works in IE but then it works in most browser except for Safari.   Here's the code.

```<code>   <script type="text/javascript">
    if(/MSIE \d|Trident.*rv:/.test(navigator.userAgent))
        var cookies = ("cookie" in document && (document.cookie.length > 0 ||
        (document.cookie = "test").indexOf.call(document.cookie, "test") > -1));
    document.write(cookies ? "" : "Cookies are not enabled.");
</script>
</code>```

But this still displays for FF, Safari, and Chrome.  So then I have two messages displaying....

答:
This will do it:

```<code>$(document).ready(function () {
 var event = window.attachEvent || window.addEventListener;
 if (!trySetCookie()) {
  // cookies are disabled
 }
 else{
 // cookies are enabled
 }
}
function trySetCookie() {
 setCookie("testCookie", "testValue", 1);
 var cookieValue = getCookie("testCookie");
 if (cookieValue == "" || cookieValue == null)
    return false;
 return true;
}
// set a test cookie in the user's browser
function setCookie(cname, cvalue, exdays) {
 var d = new Date();
 d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
 var expires = "expires=" + d.toGMTString();
 document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// read the test cookie
function getCookie(cname) {
 var name = cname + "=";
 var decodedCookie = decodeURIComponent(document.cookie);
 var ca = decodedCookie.split(';');
 for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
    }
 }
 return "";
}
</code>```

"$(document).ready()" in JavaScript

Body:
The code below works in all current browser except for IE.  In IE the message doesn't display.

  if (navigator.cookieEnabled == 0) {
    document.write("Cookies are not enabled.");
    }

Can someone tell me what I can do to make the above code work in IE 10 & 11?

I've tried code that works in IE but then it works in most browser except for Safari.   Here's the code.

But this still displays for FF, Safari, and Chrome.  So then I have two messages displaying....

Body:
This will do it:

$(document).ready(function () {
 var event = window.attachEvent || window.addEventListener;
 if (!trySetCookie()) {
  // cookies are disabled
 }
 else{
 // cookies are enabled
 }
}
function trySetCookie() {
 setCookie("testCookie", "testValue", 1);
 var cookieValue = getCookie("testCookie");
 if (cookieValue == "" || cookieValue == null)
    return false;
 return true;
}
// set a test cookie in the user's browser
function setCookie(cname, cvalue, exdays) {
 var d = new Date();
 d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
 var expires = "expires=" + d.toGMTString();
 document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// read the test cookie
function getCookie(cname) {
 var name = cname + "=";
 var decodedCookie = decodeURIComponent(document.cookie);
 var ca = decodedCookie.split(';');
 for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
    }
 }
 return "";
}

"$(document).ready()" in JavaScript


问:
Splitting a project VB/C#, and References
I've inherited a project written mostly in VB. I'd like to maintain what I have in VB while slowly converting to C# when I can. The only way I've found to do this is to create a separate C# project. However, this causes problems because of dependencies and references. I can't have VBProject reference CSharpProject and vice versa because it creates a circular reference. This is a problem because I need both projects to be able to reference the other. Is there a better way to do this, or am I stuck writing in VB (or completely translating to C#)?

Also, these projects are in the same solution. Shouldn't I be able to import/use them without creating a reference or some other easier way?

答: If you can't extract out specific items into the new C# project to reference, then you'll have to rewrite it all. If it's a web application project or a windows forms project you can't maintain any kind of hybrid in the same project. If you have a website project, you can specify the language for each individual page which would allow you to have a hybrid. This is extremely messy, though, and you will find yourself far better off allocating the time to rewrite it all in C# or adapt to writing in VB.</p>


问:
Compile java file with two jars from command line?
Suppose I have two jar files (with classes inside) and a java file:

```<code>name1.jar
name2.jar
code.java
</code>```

As said at How to use classes from .jar files?, if I wanted to import name1.jar, I could add it to my CLASSPATH, and run

```<code>javac -cp '.:name1.jar' code.java
</code>```

every time I wanted to import name1.jar. However, how would I compile the java code and import both jar files, not just name1.jar?

答:
```<code>java -cp name1.jar:name2.jar:name3.jar code.java arg1 arg2 arg3
</code>```

<p>this code runs code.java class with jars (name1,name2,name3) -cp used to ignore any runnable jar or other main() and focus on run code.java with arguments arg1 arg2 arg3 </p>

Body:
Suppose I have two jar files (with classes inside) and a java file:

name1.jar
name2.jar
code.java

As said at How to use classes from .jar files?, if I wanted to import name1.jar, I could add it to my CLASSPATH, and run

javac -cp '.:name1.jar' code.java

every time I wanted to import name1.jar. However, how would I compile the java code and import both jar files, not just name1.jar?

Body:
java -cp name1.jar:name2.jar:name3.jar code.java arg1 arg2 arg3

this code runs code.java class with jars (name1,name2,name3) -cp used to ignore any runnable jar or other main() and focus on run code.java with arguments arg1 arg2 arg3


问:
split a large file into small file based on pattern that can occur randomly Python
I have this large file with following content:

```<code>Column1 column2 column3
 345     367    Ramesh
 456     469    Ramesh
 300     301    Ramesh
 298     390    Naresh
 123     125    Suresh
 394     305    Suresh
 ......
 .....
</code>```

Now, I want to split this file into small files based on the name in column3. Like this:

File1: Ramesh.txt

```<code>column1 column2 column3
345     367      Ramesh
456     469      Ramesh
300     301      Ramesh
</code>```

File2: Naresh.txt

```<code>column1 column2 column3
298     390     Naresh
</code>```

File3: Suresh.txt

```<code>Column1 column2 column3
123     125      suresh
394     305      suresh
</code>```

and likewise.
I wrote the following python codes and it worked:

```<code>def split_file(file1):
source=open(file1)
l=[]
header=0
header_line=""
file_count=0
for line in source:
    line=line.rstrip()
    a=line.split()
    if header==0:
        header_line=line
        header+=1
    else:
        if a[-1] not in l:
            l.append(a[-1])
            file_count+=1
            if file_count>1:
                dest.close()
            else:
                pass
            dest=open(a[-1],'a')
            dest.write(header_line+"\n"+line+"\n")
        else:
            dest.write(line+"\n")
source.close()
dest.close()
</code>```

Now, my query is how can I modify these codes to work even if column3 is not sorted. For example:

```<code>Column1 column2 column3
345     367    Ramesh
123     125    Suresh
456     469    Ramesh
298     390    Naresh
300     301    Ramesh
394     305    Suresh
</code>```

Shall I generate random variable as values (to handle the output file) with the name in column3 as keys. And then use this dictionary to open the file everytime script encounters the key? Any suggestion will be appreciated.

答:
This is a prime example for the groupby() function of pandas dataframes:

```<code>import pandas as pd

data = pd.read_csv('dat.csv', delimiter="\s+")
for val, df in data.groupby(['column3']):
    df.to_csv(val + ".csv", sep='\t', index=False)
</code>```

The steps are relatively simple:

1) Read the file with the correct delimiters (\s+ stands for any number of whitespaces).

2) Loop through the groupy object which contains tuples of the form (common value, dataframe for that value)

2.1) Produce a file for each dataframe with the corresponding name.
(index=False just states that we don't want to print the index in the new files.)

Body:
I have this large file with following content:

Column1 column2 column3
 345     367    Ramesh
 456     469    Ramesh
 300     301    Ramesh
 298     390    Naresh
 123     125    Suresh
 394     305    Suresh
 ......
 .....

Now, I want to split this file into small files based on the name in column3. Like this:

File1: Ramesh.txt

column1 column2 column3
345     367      Ramesh
456     469      Ramesh
300     301      Ramesh

File2: Naresh.txt

column1 column2 column3
298     390     Naresh

File3: Suresh.txt

Column1 column2 column3
123     125      suresh
394     305      suresh

and likewise.
I wrote the following python codes and it worked:

def split_file(file1):
source=open(file1)
l=[]
header=0
header_line=""
file_count=0
for line in source:
    line=line.rstrip()
    a=line.split()
    if header==0:
        header_line=line
        header+=1
    else:
        if a[-1] not in l:
            l.append(a[-1])
            file_count+=1
            if file_count>1:
                dest.close()
            else:
                pass
            dest=open(a[-1],'a')
            dest.write(header_line+"\n"+line+"\n")
        else:
            dest.write(line+"\n")
source.close()
dest.close()

Now, my query is how can I modify these codes to work even if column3 is not sorted. For example:

Column1 column2 column3
345     367    Ramesh
123     125    Suresh
456     469    Ramesh
298     390    Naresh
300     301    Ramesh
394     305    Suresh

Shall I generate random variable as values (to handle the output file) with the name in column3 as keys. And then use this dictionary to open the file everytime script encounters the key? Any suggestion will be appreciated.

Body:
This is a prime example for the groupby() function of pandas dataframes:

import pandas as pd

data = pd.read_csv('dat.csv', delimiter="\s+")
for val, df in data.groupby(['column3']):
    df.to_csv(val + ".csv", sep='\t', index=False)

The steps are relatively simple:

1) Read the file with the correct delimiters (\s+ stands for any number of whitespaces).

2) Loop through the groupy object which contains tuples of the form (common value, dataframe for that value)

2.1) Produce a file for each dataframe with the corresponding name.
(index=False just states that we don't want to print the index in the new files.)


问:
Delete a row with the highest value of a specific column
I want to delete the row with the highest value on specific column

(I know that there are answers for that but none of them work for me for some reason)

All the coding I do in visual studio c# with SQL

MyDatabase: hours

```<code>Hours_Left | Hours_Spent | Time_Written | Mode | Time_Start | Time_End | Index
==============================================================================
aa         | bb          | cc           | dd   | ee         | ff       | 3
gg         | hh          | ii           | jj   | kk         | ll       | 4
mm         | nn          | oo           | pp   | qq         | rr       | 5
ss         | tt          | uu           | vv   | ww         | xx       | 6

[Hours_Left]   VARCHAR (MAX) NULL,
[Hours_Spent]  VARCHAR (MAX) NULL,
[Time_Written] VARCHAR (MAX) NULL,
[Mode]         VARCHAR (MAX) NULL,
[Time_Start]   VARCHAR (MAX) NULL,
[Time_End]     VARCHAR (MAX) NULL,
[Index]        INT           IDENTITY (1, 1) NOT NULL
</code>```

My Code:

```<code>if (con.State != ConnectionState.Open)
        {
            con.Close();
            con.Open();
        }
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = @"DELETE FROM hours WHERE Index = select max(Index) from hours limit 1";
        cmd.ExecuteNonQuery();
        con.Close();
        Display_Data();
</code>```

Don't work either when commandText is

```<code>@"DELETE TOP(1) FROM hours
  WHERE Index in
  (SELECT TOP(1) Index FROM hours
  ORDER BY Index DESC);";
</code>```

I want to delete the whole row of the highest index - i.e delete the row with the index 6 that it is the highest index

Error at:

```<code>cmd.ExecuteNonQuery();
</code>```

The error is:

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Index'. If
  this is intended as a part of a table hint, A WITH keyword and
  parenthesis are now required. See SQL Server Books Online for proper
  syntax.

答:
In SQL Server, you can do:

```<code>DELETE h
    FROM hours h
    WHERE h.Index = (select max(h2.Index) from hours h2) ;
</code>```

If you are concerned that index could have duplicates, then use delete with top.

Body:
I want to delete the row with the highest value on specific column

(I know that there are answers for that but none of them work for me for some reason)

All the coding I do in visual studio c# with SQL

MyDatabase: hours

Hours_Left | Hours_Spent | Time_Written | Mode | Time_Start | Time_End | Index
==============================================================================
aa         | bb          | cc           | dd   | ee         | ff       | 3
gg         | hh          | ii           | jj   | kk         | ll       | 4
mm         | nn          | oo           | pp   | qq         | rr       | 5
ss         | tt          | uu           | vv   | ww         | xx       | 6

[Hours_Left]   VARCHAR (MAX) NULL,
[Hours_Spent]  VARCHAR (MAX) NULL,
[Time_Written] VARCHAR (MAX) NULL,
[Mode]         VARCHAR (MAX) NULL,
[Time_Start]   VARCHAR (MAX) NULL,
[Time_End]     VARCHAR (MAX) NULL,
[Index]        INT           IDENTITY (1, 1) NOT NULL

My Code:

if (con.State != ConnectionState.Open)
        {
            con.Close();
            con.Open();
        }
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = @"DELETE FROM hours WHERE Index = select max(Index) from hours limit 1";
        cmd.ExecuteNonQuery();
        con.Close();
        Display_Data();

Don't work either when commandText is

@"DELETE TOP(1) FROM hours
  WHERE Index in
  (SELECT TOP(1) Index FROM hours
  ORDER BY Index DESC);";

I want to delete the whole row of the highest index - i.e delete the row with the index 6 that it is the highest index

Error at:

cmd.ExecuteNonQuery();

The error is:

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Index'. If
  this is intended as a part of a table hint, A WITH keyword and
  parenthesis are now required. See SQL Server Books Online for proper
  syntax.

Body:
In SQL Server, you can do:

DELETE h
    FROM hours h
    WHERE h.Index = (select max(h2.Index) from hours h2) ;

If you are concerned that index could have duplicates, then use delete with top.


答:
try </p>

```<code> delete from hours where Index = max(index);
</code>```

Title: Delete a row with the highest value of a specific column

Body:
try

 delete from hours where Index = max(index);


问:
Returning Mapkit Userlocation Coordinates
whenever I try to return the lat/long coordinates for my current location, my application crashes with no explanation of the error...

```<code>NSLog(@"%@", mapView.userLocation.location.coordinate);
</code>```

I am waiting until the phone finds the location as well...

答:
For some reason, this didn't work for me. It's taking me to the coordinates (0.0000, 0.0000). Below is my code if you have a chance to check it out. Thanks for the help!</p>

```<code>[mapView setMapType:MKMapTypeStandard];
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
    mapView.showsUserLocation=TRUE;

    MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };

    CLLocationCoordinate2D myCoord = {mapView.userLocation.location.coordinate.latitude,mapView.userLocation.location.coordinate.longitude};
    [mapView setCenterCoordinate:myCoord animated:YES];

    region.span.longitudeDelta = 0.01f;
    region.span.latitudeDelta = 0.01f;
    [mapView setRegion:region animated:YES];

    [mapView setDelegate:self];
</code>```

Body:
whenever I try to return the lat/long coordinates for my current location, my application crashes with no explanation of the error...

NSLog(@"%@", mapView.userLocation.location.coordinate);

I am waiting until the phone finds the location as well...

Body:
For some reason, this didn't work for me. It's taking me to the coordinates (0.0000, 0.0000). Below is my code if you have a chance to check it out. Thanks for the help!

[mapView setMapType:MKMapTypeStandard];
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
    mapView.showsUserLocation=TRUE;

    MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };

    CLLocationCoordinate2D myCoord = {mapView.userLocation.location.coordinate.latitude,mapView.userLocation.location.coordinate.longitude};
    [mapView setCenterCoordinate:myCoord animated:YES];

    region.span.longitudeDelta = 0.01f;
    region.span.latitudeDelta = 0.01f;
    [mapView setRegion:region animated:YES];

    [mapView setDelegate:self];


答:
As mentioned by "ajg", Problem in second query is usage of reserved keyword Index use square bracket to escape the keyword

Better way to do this is using CTE

```<code>;with cte as
(
select top (1) * from hours order by [Index] desc
)
delete from cte
</code>```

Body:
As mentioned by "ajg", Problem in second query is usage of reserved keyword Index use square bracket to escape the keyword

Better way to do this is using CTE

;with cte as
(
select top (1) * from hours order by [Index] desc
)
delete from cte


答: Index is a keyword, you need to use [Index].


问:
Terraform State path
I'm trying to create a resource group with Terraform.io with this example.tf file:

```<code># Configure Azure provider
provider "azurerm" {
  subscription_id = "${var.azure_subscription_id}"
  client_id       = "${var.azure_client_id}"
  client_secret   = "${var.azure_client_secret}"
  tenant_id       = "${var.azure_tenant_id}"
}

# Create a resource group
resource "azurerm_resource_group" "terraform-rg" {
  name     = "terraform-rg"
  location = "ukwest"
}
</code>```

All goes well it seems, but I'm slightly worried about this message at the end:

```<code>Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.

State path:
</code>```

So "Stage path" is empty and it seems important. Is there an argument I should pass to "terraform apply" or put somewhere else in the tf file so that I get a state path?

答: Most likely you have initialized your project with a remote state backend. In that case tf does not store your state on a local path, which results in an empty state path message at the end.</p>

Title: Terraform State path

Body:
I'm trying to create a resource group with Terraform.io with this example.tf file:

# Configure Azure provider
provider "azurerm" {
  subscription_id = "${var.azure_subscription_id}"
  client_id       = "${var.azure_client_id}"
  client_secret   = "${var.azure_client_secret}"
  tenant_id       = "${var.azure_tenant_id}"
}

# Create a resource group
resource "azurerm_resource_group" "terraform-rg" {
  name     = "terraform-rg"
  location = "ukwest"
}

All goes well it seems, but I'm slightly worried about this message at the end:

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.

State path:

So "Stage path" is empty and it seems important. Is there an argument I should pass to "terraform apply" or put somewhere else in the tf file so that I get a state path?


问:
Calculate the rendered size of a 3D object in a view
I'm working on a project that the user navigates around by clicking on icons in 3d space.  When a user engages one of these icons, the camera should pan and zoom so that the selected icon appears in the center of the screen at its original height and size (this is so when the 2d overlay is created over the icon, that it is the same size as its 3d counterpart.

My question is how to calculate the size a rendered object in a 3d view, I should mention that this is using the Alternativa 3D platform.

So there's a camera at (x1, y1, z1) with a FOV of f, pointing at an icon at (x2, y2, z2), all being rendered in a view of dimensions w and h.  This is doing my head in trying to figure it out, any help would be much appreciated.

答:
I figured out the answer hunting around on another forum, what I was really looking for was how to get a 3d object to render in a view at a 1:1 size ratio.

I had come across the formula for calculating the focal length of a 3d camera:

F = d / tan(fov/2)

where d is one half the square root of your views height^2 + width^2

the value of F is the distance from the camera your object should be to render at a 1:1 size.

Hope this helps!


问:
Division and remainder of large numbers in JavaScript
I'm trying to get the remainder of a large number, for example:

1551690021432628813 % 64

But I find that the it's a couple of digits too long for JavaScript. i.e. it's getting rounded to zero.

Is there a way around this other than using a 26kb library like BigInteger.js?

答:
You'd have to use a library (like that one you found). JavaScript's numbers (IEEE-754 double-precision binary floating point) are just not accurate at that scale, and those are the only kind of number JavaScript has*. Once you get past Number.MAX_SAFE_INTEGER + 1 (9,007,199,254,740,992), JavaScript's numbers cannot represent every integer anymore (for instance, can't represent 9,007,199,254,740,993).

* Other than the element type of a typed array, but those don't help you with this for two reasons: 1. There's no typed array for Uint64, the biggest integer is Uint32, and 2. Once you're performing math operations on the entry, you're converting it to standard number.


问:
General questions about JHipster
I am thinking about starting a project using jhipster but I still have a question remaining about the approach.
Jhipster is generating code, ok.
- Is it better to generate a project and then never use jhipster again ?
- or using the approach coding, using jhipster to edit entities, code again, jhipster, coding etc... ?

What is the best thing to do and what is your experience about it?

答: A way to be 'safe' is to use git. Use a master and develop branch (and ideally git flow). After generating your project in the develop branch, create a branch - something like 'original' - and checkout that branch whenever you want to do some JHipster magic. Checkout the develop branch and cherry pick the changes from the 'original' branch. This way you can change whatever you want in the develop branch.</p>

Title: General questions about JHipster


问:
Add image in pdf using pdfbox at a particular cell
I am using pdfbox to generate pdf.
I want to make a letterhead. I am not able to place the image in pdf at front, while I am getting it at the end of  the document.
Why it is not coming in front?</p>

答:
If you navigate to this URL you will see a section with header "Table".

If you check that section you will see how you can create a custom table inside PDF. By creating your custom table, you can create cells for images with the method "Row.createImageCell()" while building the rows and cells for your custom table (there, it just shows the method "createCell" but it also has the method "createImageCell" for images). I hope this helps.

Sample code:

```<code>Image image = new Image(ImageIO.read(new File("/../logo.png")));
// imagine we have pretty big logo and we want scale that a little bit
float imageWidth = 75;
image = image.scaleByWidth(imageWidth);

Row<PDPage> row = table.createRow(12);
cell = row.createCell(30, "Data 1");
cell = row.createImageCell(imageWidth , image);
</code>```

Body:
If you navigate to this URL you will see a section with header "Table".

If you check that section you will see how you can create a custom table inside PDF. By creating your custom table, you can create cells for images with the method "Row.createImageCell()" while building the rows and cells for your custom table (there, it just shows the method "createCell" but it also has the method "createImageCell" for images). I hope this helps.

Sample code:

Image image = new Image(ImageIO.read(new File("/../logo.png")));
// imagine we have pretty big logo and we want scale that a little bit
float imageWidth = 75;
image = image.scaleByWidth(imageWidth);

Row<PDPage> row = table.createRow(12);
cell = row.createCell(30, "Data 1");
cell = row.createImageCell(imageWidth , image);


问:
map values to a specific range
Let say we have some angular values from -inf to +inf as input.

I'd like to map them between only -180 and +180.

How could I properly achieve that?

Here's what I've found so far:

```<code>(i-180)%360-180
</code>```

It works fine, but it maps +180 to -180 which I would like to be +180->+180.

Technically it's the same for my purpose so it's not a big deal, but it would be aesthetically better.

I'm working with Python but it doesn't really matter here.

答:
Suppose you have values in the range -inf to inf in a list sampleList[].
You need to map the values in sampleList[] in range -180 to 180. Lets name the new list of mapped elements as mappedList[]

Consider x as element in sampleList[]

Consider y as element in mappedList[]

Consider maxSL as maximum of sampleList[] and

minSL as minimum of sampleList[]

Therefore,

```<code>        y = ((x - minSL)(((180-(-180))/(maxSL - minSL))) + (-180)
</code>```

Title: map values to a specific range

Body:
Let say we have some angular values from -inf to +inf as input.

I'd like to map them between only -180 and +180.

How could I properly achieve that?

Here's what I've found so far:

(i-180)%360-180

It works fine, but it maps +180 to -180 which I would like to be +180->+180.

Technically it's the same for my purpose so it's not a big deal, but it would be aesthetically better.

I'm working with Python but it doesn't really matter here.

Body:
Suppose you have values in the range -inf to inf in a list sampleList[].
You need to map the values in sampleList[] in range -180 to 180. Lets name the new list of mapped elements as mappedList[]

Consider x as element in sampleList[]

Consider y as element in mappedList[]

Consider maxSL as maximum of sampleList[] and

minSL as minimum of sampleList[]

Therefore,

        y = ((x - minSL)(((180-(-180))/(maxSL - minSL))) + (-180)


问:
VBA find missing text String and count missing values
HI there I am trying to put a VBA code to look for a specific string (text) I have defined in the code  located in another workbook find the number of missing values text from the list I defined and produce a report how many values text are missing and if any values wrong do not match the text how many are wrong. this is some of the code I have put but I am struggling to find a code to look for the defined text and produce a report of the number of missing instrument and nr of wrong instrument: Any suggestions will be highly appreciated. </p>

```<code>Dim mypath As String
Dim folderpath As String
Dim filename As String
Dim MyBook As Workbook, newbook As Workbook
Set MyBook = ThisWorkbook
Dim file As String, sheetdata As String
Dim ws As Worksheet
Dim x As Workbook
Dim y As Workbook
Dim FindString As String
Dim Rng As Range
Dim findrow As Integer
Dim i As Integer
Dim finalrow As Integer
Dim bottomA As Integer
Dim c As Range
Dim TESTMarketFI2015submitted As Worksheet
Dim FI As Worksheet
Dim a As Range
Dim col As Integer
Dim row As Integer
Dim cell As Integer
Dim inputbox As Variant
Dim application As String
Dim value As String

Dim bond As String
Dim promissoryNote As String
Dim loan As String
Dim certificatesOfDeposit As String
Dim embededOptionBond As String
Dim repo As String
Dim bondOption As String
Dim bondForward As String
Dim securedBond As String
Dim inflationLinkedBond As String
Set x = Workbooks.Open(filename:="Z:\Profiles\My Documents\MAPPING\TEST MAPPING TABLES\TEST_Market_FI_2015 - submitted.csv")
worksheets("TEST_Market_FI_2015 - submitted").Range("A:A").Select

For Each c In Sheets("TEST_Market_FI_2015 - submitted").Range("A:A")

Next

If value = ("bond,promissoryNote,loan,certificatesOfDeposit,embededOptionBond,repo,bondOption,bondForward,securedBond,inflationLinkedBond") Then
c.EntireRow.Copy Worksheets("TEST_Market_FI_2015 - submitted").Range("A:A" & Rows.Count).End(xlUp).Offset(1)

    Worksheets("FI").Select

    Range("A2").End(xlUp).Offset(i, 0).PasteSpecial
Else
    MsgBox "Nothing found under instrument"
End If

End Sub
</code>```

答:
You need to put your next under the End If.  When it checks the value, it does not know what it's actually checking.  It should be:

```<code>For Each c In Sheets("TEST_Market_FI_2015 - submitted").Range("A:A")

    If c.value = ("bond,promissoryNote,loan,certificatesOfDeposit,embededOptionBond,repo,bondOption,bondForward,securedBond,inflationLinkedBond") Then

        c.EntireRow.Copy Worksheets("TEST_Market_FI_2015 - submitted").Range("A:A" & Rows.Count).End(xlUp).Offset(1)

        Worksheets("FI").Select

        Range("A2").End(xlUp).Offset(i, 0).PasteSpecial
    Else
        MsgBox "Nothing found under instrument"
    End If

Next
</code>```

So now what will happen is, it will loop through each cell, in your selected range and check the value of c (the cell it's presently looking at). If the value of c matches your string then it will do stuff.

However, I doubt the cell value you're looking for is truly a comma delimited string.  Are you trying to search for all of those strings individually, meaning that if c.value is ANY of the words in your () then it should do stuff. If so, one option to pursue would be creating a string array, and having the c.value look in the array instead.

Body:
HI there I am trying to put a VBA code to look for a specific string (text) I have defined in the code  located in another workbook find the number of missing values text from the list I defined and produce a report how many values text are missing and if any values wrong do not match the text how many are wrong. this is some of the code I have put but I am struggling to find a code to look for the defined text and produce a report of the number of missing instrument and nr of wrong instrument: Any suggestions will be highly appreciated.

Dim mypath As String
Dim folderpath As String
Dim filename As String
Dim MyBook As Workbook, newbook As Workbook
Set MyBook = ThisWorkbook
Dim file As String, sheetdata As String
Dim ws As Worksheet
Dim x As Workbook
Dim y As Workbook
Dim FindString As String
Dim Rng As Range
Dim findrow As Integer
Dim i As Integer
Dim finalrow As Integer
Dim bottomA As Integer
Dim c As Range
Dim TESTMarketFI2015submitted As Worksheet
Dim FI As Worksheet
Dim a As Range
Dim col As Integer
Dim row As Integer
Dim cell As Integer
Dim inputbox As Variant
Dim application As String
Dim value As String

Dim bond As String
Dim promissoryNote As String
Dim loan As String
Dim certificatesOfDeposit As String
Dim embededOptionBond As String
Dim repo As String
Dim bondOption As String
Dim bondForward As String
Dim securedBond As String
Dim inflationLinkedBond As String
Set x = Workbooks.Open(filename:="Z:\Profiles\My Documents\MAPPING\TEST MAPPING TABLES\TEST_Market_FI_2015 - submitted.csv")
worksheets("TEST_Market_FI_2015 - submitted").Range("A:A").Select

For Each c In Sheets("TEST_Market_FI_2015 - submitted").Range("A:A")

Next

If value = ("bond,promissoryNote,loan,certificatesOfDeposit,embededOptionBond,repo,bondOption,bondForward,securedBond,inflationLinkedBond") Then
c.EntireRow.Copy Worksheets("TEST_Market_FI_2015 - submitted").Range("A:A" & Rows.Count).End(xlUp).Offset(1)

    Worksheets("FI").Select

    Range("A2").End(xlUp).Offset(i, 0).PasteSpecial
Else
    MsgBox "Nothing found under instrument"
End If

End Sub

Body:
You need to put your next under the End If.  When it checks the value, it does not know what it's actually checking.  It should be:

For Each c In Sheets("TEST_Market_FI_2015 - submitted").Range("A:A")

    If c.value = ("bond,promissoryNote,loan,certificatesOfDeposit,embededOptionBond,repo,bondOption,bondForward,securedBond,inflationLinkedBond") Then

        c.EntireRow.Copy Worksheets("TEST_Market_FI_2015 - submitted").Range("A:A" & Rows.Count).End(xlUp).Offset(1)

        Worksheets("FI").Select

        Range("A2").End(xlUp).Offset(i, 0).PasteSpecial
    Else
        MsgBox "Nothing found under instrument"
    End If

Next

So now what will happen is, it will loop through each cell, in your selected range and check the value of c (the cell it's presently looking at). If the value of c matches your string then it will do stuff.

However, I doubt the cell value you're looking for is truly a comma delimited string.  Are you trying to search for all of those strings individually, meaning that if c.value is ANY of the words in your () then it should do stuff. If so, one option to pursue would be creating a string array, and having the c.value look in the array instead.