问:
Implementing the decorator pattern in Python
I want to implement the decorator pattern in Python, and I wondered if there is a way to write a decorator that just implements the function it wants to modify, without writing boiler-plate for all the functions that are just forwarded to the decorated object. Like so:

```<code>class foo(object):
    def f1(self):
        print "original f1"
    def f2(self):
        print "original f2"

class foo_decorator(object):
    def __init__(self, decoratee):
        self._decoratee = decoratee
    def f1(self):
        print "decorated f1"
        self._decoratee.f1()
    def f2(self):              # I would like to leave that part out
        self._decoratee.f2()
</code>```

I would like to have calls to foo_decorator.f2 forwarded to decoratee.f2 automatically. Is there a way to write a generic method that forwards all unimplemented function-calls to decoratee?

答:
In one of my projects, I also needed to do one particular thing, that is that even the underlying object should actually execute the method that was reimplemented in the decorator. It is actually quite easy to do if you know where to target it.

The use case is:

I have an object X with methods A and B.

I create a decorator class Y that overrides A.

If I instantiate Y(X) and call A, it will use the decorated A as expected.

If B calls A, then if I instantiate Y(X) and call B on the decorator, the call from within B then goes to the old A on the original object which was undesirable. I want the old B to call the new A as well.

It is possible to reach this behaviour like this:

import inspect
import six      # for handling 2-3 compatibility

class MyBaseDecorator(object):
    def __init__(self, decorated):
        self.decorated = decorated

    def __getattr__(self, attr):
       value = getattr(self.decorated, attr)
       if inspect.ismethod(value):
           function = six.get_method_function(value)
           value = function.__get__(self, type(self))
       return value

class SomeObject(object):
    def a(self):
        pass

    def b(self):
        pass

class MyDecorator(MyBaseDecorator):
    def a(self):
        pass

decorated = MyDecorator(SomeObject())
```

This may not work out of the box as I typed everything else apart from the getattr method from top of my head.

The code looks up the requested attribute in the decorated object, and if it is a method (doesn't work for properties now, but the change to support them should not be too difficult), the code then pulls the actual function out of the method and using the descriptor interface invocation it "rebinds" the function as a method, but on the decorator. Then it is returned and most likely executed.

The effect of this is that if b ever calls a on the original object, then when you have the object decorated and there is any method call coming from the decorator, the decorator makes sure that all methods accessed are bound to the decorator instead, therefore looking up things using the decorator and not the original object, therefore the methods specified in the decorator taking precedence.

P.S.: Yes I know it looks pretty much like inheritance, but this done in the sense of composition of multiple objects.

Body:
I want to implement the decorator pattern in Python, and I wondered if there is a way to write a decorator that just implements the function it wants to modify, without writing boiler-plate for all the functions that are just forwarded to the decorated object. Like so:

class foo(object):
    def f1(self):
        print "original f1"
    def f2(self):
        print "original f2"

class foo_decorator(object):
    def __init__(self, decoratee):
        self._decoratee = decoratee
    def f1(self):
        print "decorated f1"
        self._decoratee.f1()
    def f2(self):              # I would like to leave that part out
        self._decoratee.f2()

I would like to have calls to foo_decorator.f2 forwarded to decoratee.f2 automatically. Is there a way to write a generic method that forwards all unimplemented function-calls to decoratee?

Body:
In one of my projects, I also needed to do one particular thing, that is that even the underlying object should actually execute the method that was reimplemented in the decorator. It is actually quite easy to do if you know where to target it.

The use case is:

I have an object X with methods A and B.

I create a decorator class Y that overrides A.

If I instantiate Y(X) and call A, it will use the decorated A as expected.

If B calls A, then if I instantiate Y(X) and call B on the decorator, the call from within B then goes to the old A on the original object which was undesirable. I want the old B to call the new A as well.

It is possible to reach this behaviour like this:

import inspect
import six      # for handling 2-3 compatibility

class MyBaseDecorator(object):
    def __init__(self, decorated):
        self.decorated = decorated

    def __getattr__(self, attr):
       value = getattr(self.decorated, attr)
       if inspect.ismethod(value):
           function = six.get_method_function(value)
           value = function.__get__(self, type(self))
       return value

class SomeObject(object):
    def a(self):
        pass

    def b(self):
        pass

class MyDecorator(MyBaseDecorator):
    def a(self):
        pass

decorated = MyDecorator(SomeObject())

This may not work out of the box as I typed everything else apart from the getattr method from top of my head.

The code looks up the requested attribute in the decorated object, and if it is a method (doesn't work for properties now, but the change to support them should not be too difficult), the code then pulls the actual function out of the method and using the descriptor interface invocation it "rebinds" the function as a method, but on the decorator. Then it is returned and most likely executed.

The effect of this is that if b ever calls a on the original object, then when you have the object decorated and there is any method call coming from the decorator, the decorator makes sure that all methods accessed are bound to the decorator instead, therefore looking up things using the decorator and not the original object, therefore the methods specified in the decorator taking precedence.

P.S.: Yes I know it looks pretty much like inheritance, but this done in the sense of composition of multiple objects.


来源: stackexchange

问:
I'm using vim editor and my escape button stopped working. I've some unsaved data and I'm in insert mode. How can I still save my data?

Getting my content saved.

I want my content saved or written without using the escape button.

I'm worried as my data will not be saved.

答:
"Easy mode" / 'insertmode'

You can use <c-l> to get to normal mode in case you accidentally set 'insertmode'.

<c-]> / <c-c>

Just as @hobbs and @romainl said, you can always use <c-]> (preferred) / <c-c> to exit to normal mode. <c-]> is the same terminal sequence as <esc>, but <c-c> will exit to normal mode but will also not execute InsertLeave.

<c-o>

<c-o> will put you in normal mode for 1 command then re-enter insert mode.

<c-\><c-n>

Pretty much will exit to normal mode from any other mode except Ex-mode. It will even exit form Terminal-mode, but only for 1 command.

For more help see:

```<code>:h 'insertmode'
:h i_CTRL-L
:h CTRL-C
:h i_CTRL-O
:h CTRL-\_CTRL-N
</code>```

ContentLicense: CC BY-SA 3.0

Body:
"Easy mode" / 'insertmode'

You can use <c-l> to get to normal mode in case you accidentally set 'insertmode'.

<c-]> / <c-c>

Just as @hobbs and @romainl said, you can always use <c-]> (preferred) / <c-c> to exit to normal mode. <c-]> is the same terminal sequence as <esc>, but <c-c> will exit to normal mode but will also not execute InsertLeave.

<c-o>

<c-o> will put you in normal mode for 1 command then re-enter insert mode.

<c-\><c-n>

Pretty much will exit to normal mode from any other mode except Ex-mode. It will even exit form Terminal-mode, but only for 1 command.

For more help see:

:h 'insertmode'
:h i_CTRL-L
:h CTRL-C
:h i_CTRL-O
:h CTRL-\_CTRL-N


问:
MySQL Error "Can't create table" Foreign Key Constraint
I'm trying to create a database using MySQL and having difficulties with my code. I created the base table with one attribute that I plan on using as a foreign key in another table but an error message comes up saying I cannot create the table. I only want help with creating that table as I know how to insert data.

```<code>    create database aerogames_table;

CREATE TABLE
    O_DETAILS
    (
        B_Number INT NOT NULL,
        B_Name VARCHAR(60) NOT NULL,
        Order_ID INT NOT NULL,
        Order_CName VARCHAR(50) NOT NULL
    )
    engine=innodb;

CREATE TABLE
    P_DETAILS
    (
        PRO_ID INT NOT NULL PRIMARY KEY,
        Order_ID INT NOT NULL,
        CONSTRAINT fk_OrdID_this FOREIGN KEY (Order_ID) REFERENCES O_DETAILS(Order_ID),
        PRO_Seller VARCHAR (50) NOT NULL,
        PRO_Name VARCHAR (50) NOT NULL,
        PRO_Year INT NOT NULL,
        PRO_Price INT NOT NULL
    )
    engine=innodb;
</code>```

1005 - Can't create table 'aerogames_table.p_details' (errno: 150)

答:
Due to this https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

```<code>    [CONSTRAINT [symbol]]
        FOREIGN KEY [index_name] (index_col_name, ...)
        REFERENCES tbl_name (index_col_name,...)
</code>```

Foreign key need to reference to index column (no need to be primary key) so you need to create index on O_DETAILS.Order_ID like this

```<code>    CREATE TABLE
        O_DETAILS
        (
            B_Number INT NOT NULL,
            B_Name VARCHAR(60) NOT NULL,
            Order_ID INT NOT NULL,
            Order_CName VARCHAR(50) NOT NULL,
                    KEY (Order_ID)
        )
        engine=innodb;

    CREATE TABLE
        P_DETAILS
        (
            PRO_ID INT NOT NULL PRIMARY KEY,
            Order_ID INT NOT NULL,
            CONSTRAINT fk_OrdID_this FOREIGN KEY (Order_ID) REFERENCES O_DETAILS(Order_ID),
            PRO_Seller VARCHAR (50) NOT NULL,
            PRO_Name VARCHAR (50) NOT NULL,
            PRO_Year INT NOT NULL,
            PRO_Price INT NOT NULL
        )
        engine=innodb;
</code>```

Certainly if you make O_DETAILS.Order_ID to be primary key, it will also create for you and this works

Body:
I'm trying to create a database using MySQL and having difficulties with my code. I created the base table with one attribute that I plan on using as a foreign key in another table but an error message comes up saying I cannot create the table. I only want help with creating that table as I know how to insert data.

    create database aerogames_table;

CREATE TABLE
    O_DETAILS
    (
        B_Number INT NOT NULL,
        B_Name VARCHAR(60) NOT NULL,
        Order_ID INT NOT NULL,
        Order_CName VARCHAR(50) NOT NULL
    )
    engine=innodb;

CREATE TABLE
    P_DETAILS
    (
        PRO_ID INT NOT NULL PRIMARY KEY,
        Order_ID INT NOT NULL,
        CONSTRAINT fk_OrdID_this FOREIGN KEY (Order_ID) REFERENCES O_DETAILS(Order_ID),
        PRO_Seller VARCHAR (50) NOT NULL,
        PRO_Name VARCHAR (50) NOT NULL,
        PRO_Year INT NOT NULL,
        PRO_Price INT NOT NULL
    )
    engine=innodb;

1005 - Can't create table 'aerogames_table.p_details' (errno: 150)

Body:
Due to this https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

    [CONSTRAINT [symbol]]
        FOREIGN KEY [index_name] (index_col_name, ...)
        REFERENCES tbl_name (index_col_name,...)

Foreign key need to reference to index column (no need to be primary key) so you need to create index on O_DETAILS.Order_ID like this

    CREATE TABLE
        O_DETAILS
        (
            B_Number INT NOT NULL,
            B_Name VARCHAR(60) NOT NULL,
            Order_ID INT NOT NULL,
            Order_CName VARCHAR(50) NOT NULL,
                    KEY (Order_ID)
        )
        engine=innodb;

    CREATE TABLE
        P_DETAILS
        (
            PRO_ID INT NOT NULL PRIMARY KEY,
            Order_ID INT NOT NULL,
            CONSTRAINT fk_OrdID_this FOREIGN KEY (Order_ID) REFERENCES O_DETAILS(Order_ID),
            PRO_Seller VARCHAR (50) NOT NULL,
            PRO_Name VARCHAR (50) NOT NULL,
            PRO_Year INT NOT NULL,
            PRO_Price INT NOT NULL
        )
        engine=innodb;

Certainly if you make O_DETAILS.Order_ID to be primary key, it will also create for you and this works


问:
Laravel Excel Import - MethodNotAllowedHttpException
In my Laravel Project i import data from Excel (.CSV). When i upload small count data (15 or 10) its imported, but upload more than 200 data its return  (1/1) MethodNotAllowedHttpException. i using Maatwebsite/Laravel-Excel package to upload Data.

Controller Code :

```<code> public function uploadleads(Request $request){

        $usersid = Auth::user()->id;

        if($request->hasFile('leads')){

            Excel::load($request->file('leads')->getRealPath(), function ($reader) use($usersid) {

                foreach ($reader->toArray() as $key => $row) {

                    $data['name'] = ucfirst($row['candidatename']);
                    $data['gender'] = ucfirst($row['gender']);
                    $data['mobile'] = $row['mobileno'];
                    $data['email'] = $row['email'];
                    $data['work_experience'] = $row['workexperience'];
                    $data['resume_title'] = $row['resumetitle'];
                    $data['current_location'] = $row['currentlocation'];
                    $data['preferred_location'] = $row['preferredlocation'];
                    $data['current_employer'] = $row['currentemployer'];
                    $data['current_designation'] = $row['currentdesignation'];
                    $data['annual_salary'] = $row['annualsalary'];
                    $data['ug_course'] = $row['ugcourse'];
                    $data['pg_coruse'] = $row['pgcourse'];
                    $data['post_pg_course'] = $row['postpgcourse'];
                    $data['leads_address'] = $row['address'];
                    $data['telephone'] = $row['telephone'];
                    $data['dateofbirth'] = $row['dateofbirth'];
                    $data['sourcefrom'] = $row['sourcefrom'];
                    $data['created_by'] = $usersid;

                $baseleadscounts=Baseleads::Where('mobile',$row['mobileno'])->OrWhere('email',$row['email'])->count();

                $templeadscount=Templeads::Where('mobile',$row['mobileno'])->OrWhere('email',$row['email'])->count();

                if(($baseleadscounts + $templeadscount) > 0){

                    DB::table('duplileads')->insert($data);

                } else {

                    if((preg_match('/(7|8|9)\d{9}/',$data['mobile'])) && ($row['gender'] == 'Male' || $row['gender'] == 'Female' || $row['gender'] == 'male' || $row['gender'] == 'female')){

                        DB::table('templeads')->insert($data);

                    } else {

                        DB::table('duplileads')->insert($data);

                    }

                }

                }

            });
        }

    alert()->success('Data Imported Successfully.', 'Success!');

    return redirect('importreport');

    }
</code>```

How to fix this Issue

答:
This error MethodNotAllowedHttpException can be triggered when you are trying to submit a form with a method='POST' to a Route::get or vice versa.

Make sure that your route is correct and your form is using the appropriate method.

Body:
In my Laravel Project i import data from Excel (.CSV). When i upload small count data (15 or 10) its imported, but upload more than 200 data its return  (1/1) MethodNotAllowedHttpException. i using Maatwebsite/Laravel-Excel package to upload Data.

Controller Code :

 public function uploadleads(Request $request){

        $usersid = Auth::user()->id;

        if($request->hasFile('leads')){

            Excel::load($request->file('leads')->getRealPath(), function ($reader) use($usersid) {

                foreach ($reader->toArray() as $key => $row) {

                    $data['name'] = ucfirst($row['candidatename']);
                    $data['gender'] = ucfirst($row['gender']);
                    $data['mobile'] = $row['mobileno'];
                    $data['email'] = $row['email'];
                    $data['work_experience'] = $row['workexperience'];
                    $data['resume_title'] = $row['resumetitle'];
                    $data['current_location'] = $row['currentlocation'];
                    $data['preferred_location'] = $row['preferredlocation'];
                    $data['current_employer'] = $row['currentemployer'];
                    $data['current_designation'] = $row['currentdesignation'];
                    $data['annual_salary'] = $row['annualsalary'];
                    $data['ug_course'] = $row['ugcourse'];
                    $data['pg_coruse'] = $row['pgcourse'];
                    $data['post_pg_course'] = $row['postpgcourse'];
                    $data['leads_address'] = $row['address'];
                    $data['telephone'] = $row['telephone'];
                    $data['dateofbirth'] = $row['dateofbirth'];
                    $data['sourcefrom'] = $row['sourcefrom'];
                    $data['created_by'] = $usersid;

                $baseleadscounts=Baseleads::Where('mobile',$row['mobileno'])->OrWhere('email',$row['email'])->count();

                $templeadscount=Templeads::Where('mobile',$row['mobileno'])->OrWhere('email',$row['email'])->count();

                if(($baseleadscounts + $templeadscount) > 0){

                    DB::table('duplileads')->insert($data);

                } else {

                    if((preg_match('/(7|8|9)\d{9}/',$data['mobile'])) && ($row['gender'] == 'Male' || $row['gender'] == 'Female' || $row['gender'] == 'male' || $row['gender'] == 'female')){

                        DB::table('templeads')->insert($data);

                    } else {

                        DB::table('duplileads')->insert($data);

                    }

                }

                }

            });
        }

    alert()->success('Data Imported Successfully.', 'Success!');

    return redirect('importreport');

    }

How to fix this Issue


问:
Passing 2 models to a view possible?
I have a view that must render two reports.

My action:

```<code>public ActionResult TradeUKKPIShowData(SundaysInMonthViewModel model) //show actual data in the view
{
  var tradesmenReportData = _reportingService.GetTradeUKKPITradesmen(model.SelectedSunday);
  var jobSortedReportData = _reportingService.GetTradeUKKPIJobSorted(model.SelectedSunday);
  ViewBag.jobSortedReportDate = model.SelectedSunday;
  ViewBag.addJobSortedModel = jobSortedReportData;
  return View(tradesmenReportData);
}
</code>```

My first problem is with the first two lines of the action above. What must I pass here?
The compile errors I get for those lines:

'TradeUK.Services.IReportingService.GetTradeUKKPITradesmen(TradeUK.Entities.Reporting.KPIResults)' has some invalid arguments

All the stored procedure for the report needs is the date/sunday that was selected

My SundaysInMonthViewModel:

```<code> namespace TradeUK.Admin.Web.ViewModels
 {
    public class SundaysInMonthViewModel
    {
       public IEnumerable<SelectListItem> AllSundays { set; get; }
       public string SelectedSunday { set; get; }
    }
 }
</code>```

Here IReportingServices.cs:

```<code>IEnumerable<KPIResults> GetTradeUKKPITradesmen(DateTime date);
IEnumerable<KPIResults> GetTradeUKKPIJobSorted(DateTime date);
</code>```

and the actual methods for above:

```<code> public IEnumerable<KPIResults> GetTradeUKKPITradesmen(DateTime date)
 {
 }

 public IEnumerable<KPIResults> GetTradeUKKPIJobSorted(DateTime date)
 {
 }
</code>```

KPIResults:

```<code>namespace TradeUK.Entities.Reporting
{
 public class KPIResults
  {
   public virtual string Title { get; set; }
   public virtual int Total { get; set; }
   public virtual int Week6 { get; set; }
   public virtual int Week5 { get; set; }
   public virtual int Week4 { get; set; }
   public virtual int Week3 { get; set; }
   public virtual int Week2 { get; set; }
   public virtual int Week1 { get; set; }
  }
 }
</code>```

The other issue is on the return(View(tradesmenReportData,jobSortedReportData)
Can I do this? In the actual view I have to foreach loops to show the to sets of report data.

Please help?
Thanks

答:
I found this link on the web which may do it for you.

https://weblogs.asp.net/dotnetstories/passing-multiple-models-to-a-view-in-an-asp-net-mvc-5-0-application

Edit :-

The page I have linked to suggests passing a List of Objects to the View, with the list being made up od different Models, here is the example.

```<code>public ActionResult Index()
   {
         List<object> model = new List<object>();
         model.Add(ctx.ProductCategories.ToList());
         model.Add(ctx.Products.ToList());

        return View(model);
    }
}
</code>```

Then in the View you can break the List down to individual models again, here is the example the author gives :-

```<code>@model IEnumerable<object>

@{

    List<PassingMultipleModelsToAView.ProductCategory> lstPCategory = Model.ToList()[0] as List<PassingMultipleModelsToAView.ProductCategory>;

    List<PassingMultipleModelsToAView.Product> lstProduct = Model.ToList()[1] as List<PassingMultipleModelsToAView.Product>;
}

<h3>Categories</h3>

<ul>
    @foreach (var item in lstPCategory)
    {
        <li>@item.Name</li>
    }
</ul>

<hr />

<h3>Products</h3>

<ul>
    @foreach (var item in lstProduct)
    {
        <li>@item.Name-@item.Color</li>
    }
</ul>
</code>```

Title: Passing 2 models to a view possible?

Body:
I have a view that must render two reports.

My action:

public ActionResult TradeUKKPIShowData(SundaysInMonthViewModel model) //show actual data in the view
{
  var tradesmenReportData = _reportingService.GetTradeUKKPITradesmen(model.SelectedSunday);
  var jobSortedReportData = _reportingService.GetTradeUKKPIJobSorted(model.SelectedSunday);
  ViewBag.jobSortedReportDate = model.SelectedSunday;
  ViewBag.addJobSortedModel = jobSortedReportData;
  return View(tradesmenReportData);
}

My first problem is with the first two lines of the action above. What must I pass here?
The compile errors I get for those lines:

'TradeUK.Services.IReportingService.GetTradeUKKPITradesmen(TradeUK.Entities.Reporting.KPIResults)' has some invalid arguments

All the stored procedure for the report needs is the date/sunday that was selected

My SundaysInMonthViewModel:

 namespace TradeUK.Admin.Web.ViewModels
 {
    public class SundaysInMonthViewModel
    {
       public IEnumerable<SelectListItem> AllSundays { set; get; }
       public string SelectedSunday { set; get; }
    }
 }

Here IReportingServices.cs:

IEnumerable<KPIResults> GetTradeUKKPITradesmen(DateTime date);
IEnumerable<KPIResults> GetTradeUKKPIJobSorted(DateTime date);

and the actual methods for above:

 public IEnumerable<KPIResults> GetTradeUKKPITradesmen(DateTime date)
 {
 }

 public IEnumerable<KPIResults> GetTradeUKKPIJobSorted(DateTime date)
 {
 }

KPIResults:

namespace TradeUK.Entities.Reporting
{
 public class KPIResults
  {
   public virtual string Title { get; set; }
   public virtual int Total { get; set; }
   public virtual int Week6 { get; set; }
   public virtual int Week5 { get; set; }
   public virtual int Week4 { get; set; }
   public virtual int Week3 { get; set; }
   public virtual int Week2 { get; set; }
   public virtual int Week1 { get; set; }
  }
 }

The other issue is on the return(View(tradesmenReportData,jobSortedReportData)
Can I do this? In the actual view I have to foreach loops to show the to sets of report data.

Please help?
Thanks

Body:
I found this link on the web which may do it for you.

https://weblogs.asp.net/dotnetstories/passing-multiple-models-to-a-view-in-an-asp-net-mvc-5-0-application

Edit :-

The page I have linked to suggests passing a List of Objects to the View, with the list being made up od different Models, here is the example.

public ActionResult Index()
   {
         List<object> model = new List<object>();
         model.Add(ctx.ProductCategories.ToList());
         model.Add(ctx.Products.ToList());

        return View(model);
    }
}

Then in the View you can break the List down to individual models again, here is the example the author gives :-

@model IEnumerable<object>

@{

    List<PassingMultipleModelsToAView.ProductCategory> lstPCategory = Model.ToList()[0] as List<PassingMultipleModelsToAView.ProductCategory>;

    List<PassingMultipleModelsToAView.Product> lstProduct = Model.ToList()[1] as List<PassingMultipleModelsToAView.Product>;
}

<h3>Categories</h3>

<ul>
    @foreach (var item in lstPCategory)
    {
        <li>@item.Name</li>
    }
</ul>

<hr />

<h3>Products</h3>

<ul>
    @foreach (var item in lstProduct)
    {
        <li>@item.Name-@item.Color</li>
    }
</ul>


问:
Variable arguments inside a macro
I have two functions foo1(a,b) & foo2(a,b,c) and a macro

```<code>#define add(a,b) foo(a,b)
</code>```

I need to re-define macro to accomplish,

1.if add() is called with 2 parameters, then call foo1

if add() is called with 3 parameters then call foo2

Im new to the option VA_ARGS. How can I do that

答:
If you must use variadic macros, then here is a trick.

```<code>#define add(...) _Generic ( &(int[]){__VA_ARGS__}, \
                            int(*)[2]: add2,       \
                            int(*)[3]: add3) (__VA_ARGS__)
</code>```

Have the macro create a compound literal array. The size of this array will depend on the number of arguments.

Grab the address of the compound literal, to get an array pointer type.

Let _Generic check which type you got, then call the proper function based on that.

This is 100% standard C and also type safe.

Demo:

```<code>#include <stdio.h>

#define add(...) _Generic ( &(int[]){__VA_ARGS__}, \
                            int(*)[2]: add2,       \
                            int(*)[3]: add3) (__VA_ARGS__)

int add2 (int a, int b);
int add3 (int a, int b, int c);

int main (void)
{
  printf("%d\n", add(1, 2));
  printf("%d\n", add(1, 2, 3));
//printf("%d\n", add(1, 2, 3, 4)); Compiler error for this.
}

int add2 (int a, int b)
{
  return a + b;
}

int add3 (int a, int b, int c)
{
  return a + b + c;
}
</code>```

Title: Variable arguments inside a macro

Body:
I have two functions foo1(a,b) & foo2(a,b,c) and a macro

#define add(a,b) foo(a,b)

I need to re-define macro to accomplish,

1.if add() is called with 2 parameters, then call foo1

if add() is called with 3 parameters then call foo2

Im new to the option VA_ARGS. How can I do that

Body:
If you must use variadic macros, then here is a trick.

#define add(...) _Generic ( &(int[]){__VA_ARGS__}, \
                            int(*)[2]: add2,       \
                            int(*)[3]: add3) (__VA_ARGS__)

Have the macro create a compound literal array. The size of this array will depend on the number of arguments.

Grab the address of the compound literal, to get an array pointer type.

Let _Generic check which type you got, then call the proper function based on that.

This is 100% standard C and also type safe.

Demo:

#include <stdio.h>

#define add(...) _Generic ( &(int[]){__VA_ARGS__}, \
                            int(*)[2]: add2,       \
                            int(*)[3]: add3) (__VA_ARGS__)

int add2 (int a, int b);
int add3 (int a, int b, int c);

int main (void)
{
  printf("%d\n", add(1, 2));
  printf("%d\n", add(1, 2, 3));
//printf("%d\n", add(1, 2, 3, 4)); Compiler error for this.
}

int add2 (int a, int b)
{
  return a + b;
}

int add3 (int a, int b, int c)
{
  return a + b + c;
}


问:
how to connect two projects Laravel 4.2 and laravel 5.5?
i have a laravel 4.2 project that i want to connect it to laravel 5.5 project

Q1) how to login in the first and and authenticated to the second to so i don't have to login to the second

Q2)how to connect them to the same DB

Q3)let's say i'm in page X in laravel 4.2 and i want to direct it to Y in laravel 5.5 where i should write the route in laravel 4.2 or in 5.5 ?

at the end both of the projects are going to be on the same server and have the same domain if that is going to be helpful

答:
This is easy to do, just put both applications on the same server and link them using the same credentials in the .ENV file, don't forget you will also need to create Models in both apps so that both apps can use the tables.

As for the routes, you would need to add the routes & functions that can be called in each individual app.

So if the user clicks the URL for /link-to-4.2 you should have a route in 4.2:

```<code>Route::get('/link-to-4.2', 'index@controller');
</code>```

and then in your 5.5 you should have a route for any URLs that direct to anything there. i.e: /link-to-5.5

```<code>    Route::get('/link-to-5.5', 'index@controller');
</code>```

this all being said, what is the justification for using 2 apps? I think there could be a number of security issues that might cause headaches, this will also likely be a real nightmare to manage moving forward.

I would strongely suggest that you just upgrade the 4.2 app to be 5.5.

Body:
This is easy to do, just put both applications on the same server and link them using the same credentials in the .ENV file, don't forget you will also need to create Models in both apps so that both apps can use the tables.

As for the routes, you would need to add the routes & functions that can be called in each individual app.

So if the user clicks the URL for /link-to-4.2 you should have a route in 4.2:

Route::get('/link-to-4.2', 'index@controller');

and then in your 5.5 you should have a route for any URLs that direct to anything there. i.e: /link-to-5.5

    Route::get('/link-to-5.5', 'index@controller');

this all being said, what is the justification for using 2 apps? I think there could be a number of security issues that might cause headaches, this will also likely be a real nightmare to manage moving forward.

I would strongely suggest that you just upgrade the 4.2 app to be 5.5.


问:
Making Dedupe learn from existing label data
I am aware that Dedupe uses  Active learning to  remove duplicates and perform Record linkage.

However , I would like to know  if we can pass  excel sheet with already matched pairs(label data) as the input for active learning?

答:
Not directly.

You'll need to get your data into a format that markPairs can consume.

Something like:

```<code>labeled_examples = {'match'    : [],
                    'distinct' : [({'name' : 'Georgie Porgie'},
                                   {'name' : 'Georgette Porgette'})]
                    }
deduper.markPairs(labeled_examples)
</code>```

We do provide a convenience function for getting spreadsheet data into this format trainingDataDedupe.

(I am an author of dedupe)

Body:
Not directly.

You'll need to get your data into a format that markPairs can consume.

Something like:

labeled_examples = {'match'    : [],
                    'distinct' : [({'name' : 'Georgie Porgie'},
                                   {'name' : 'Georgette Porgette'})]
                    }
deduper.markPairs(labeled_examples)

We do provide a convenience function for getting spreadsheet data into this format trainingDataDedupe.

(I am an author of dedupe)


问:
How to center align text in a HTML table cell, without considering other elements in the cell

How do I center text in a div in a column without counting other element in same div, please?

td {
  border: 1px solid black;
  width: 150px;
  text-align: center;
}

button {
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>text1</td>
  </tr>
    <td>text2<button>ok</button></td>
  <tr>
    <td>text3</td>
  </tr>
</table></code>```

答:
You are going to have to use position:absolute; on the button so it can be ignored and allow the text to be centered.

td {
  border: 1px solid black;
  width: 150px;
  text-align: center;
  position: relative;
}

.okButton {
position: absolute;
right: 0;
top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>text1</td>
  </tr>
  <td>text2<button class="okButton">ok</button></td>
  <tr>
    <td>text3</td>
  </tr>
</table></code>```

Body:
How do I center text in a div in a column without counting other element in same div, please?

td {
  border: 1px solid black;
  width: 150px;
  text-align: center;
}

button {
  float: right;
}

    text1

    text2<button>ok</button>

    text3

Body:
You are going to have to use position:absolute; on the button so it can be ignored and allow the text to be centered.

td {
  border: 1px solid black;
  width: 150px;
  text-align: center;
  position: relative;
}

.okButton {
position: absolute;
right: 0;
top: 0;
}

<table>
  <tr>
    <td>text1</td>
  </tr>
  <td>text2<button class="okButton">ok</button></td>
  <tr>
    <td>text3</td>
  </tr>
</table>


问:
Bluetooth LE GAP Service and appearance characteristic
I am studying a Bluetooth LE peripheral and I noticed it doesn't include the Appearance characteristic of the GAP service, just the Device Name characteristic.

If the GAP service lacks the Appearance characteristic which is mandatory in the table below, is it still Bluetooth compliance?

the device is Bluetooth LE 4.0

The only I could find in the CORE 4.0 specs is:

CORE specs 4.0

答:
You can find more information on Appearance in Core Specification Supplement.
Also all the Appearance assigned keys can be found here.</p>


问:
Large TChart takes a long time to draw
Top post: I have accepted an answer,but it doesn't work for me. I will post a new question, stressing Delphi 7. Thanks to all who gave some good input

I have measurements taken at one second intervals over an hour.

I had a previous question where it was taking 45 seconds to updates a TStringGrid and managed to get that down to "faster than the eye can see". Partly by moving some computation and database related functionality of of the loop, but - surprisingly to me - the change that really made the difference was setting the strindgrid's rowCount to 3600 before the loop rather than incrementing it inside the loop.

Now I have a similar problem with a TChart. Maybe if I try preallocating the chart? So, I could Chart1.Series[0].Count := 3600, but than I can't use AddXy() or Add(), so how would I explicitly set the values in series?

I have a very simple chart, with Floats on the y-axis and hour:seconds on the x-axis

Can anyone help, or suggest another way to speed up chart drawing?

Update: several have suggested using TFastLineSeries, but I don't see how.

Aha - double click on the Chart, to show all series, select one & click change

答: You can find the "official" recommendations about fast charting on Steema website </p>

ContentLicense: CC BY-SA 2.5

Title: Large TChart takes a long time to draw


问:
How can we compute solar position at a given place on a given day and time?
I have UTC time (hours, minutes, seconds), longitude(deg E), latitude (deg N) and date. Can anyone provide me with a code to calculate solar zenith angle in Python 2.7? </p>

答:
@alecxe's answer is great, but I thought I'd add a slight modification that's a bit closer to what the original question is asking (the zenithal angle at a specific time)

```<code>from astropy.coordinates import get_sun, AltAz, EarthLocation
from astropy.time import Time

sun_time = Time('2017-12-6 17:00') #UTC time
loc = EarthLocation.of_address('Baltimore, MD')  # anything the google geocoding API resolves
altaz = AltAz(obstime=sun_time, location=loc)

zen_ang = get_sun(sun_time).transform_to(altaz).zen
</code>```

zen_ang is then an Angle object - see more about those in the docs, but basically they end up working like numpy scalars with associated units of "degrees".

Body:
@alecxe's answer is great, but I thought I'd add a slight modification that's a bit closer to what the original question is asking (the zenithal angle at a specific time)

from astropy.coordinates import get_sun, AltAz, EarthLocation
from astropy.time import Time

sun_time = Time('2017-12-6 17:00') #UTC time
loc = EarthLocation.of_address('Baltimore, MD')  # anything the google geocoding API resolves
altaz = AltAz(obstime=sun_time, location=loc)

zen_ang = get_sun(sun_time).transform_to(altaz).zen

zen_ang is then an Angle object - see more about those in the docs, but basically they end up working like numpy scalars with associated units of "degrees".


问:
azure webapps 404 error
I have web application developed in Spring boot (REST services) which is deployed on Azure webapps (Azure app service). My plan is Standard: 1 Small.

The application has been running smoothly since 2 weeks. All of a sudden, today, the application went down. Consumer application which calls these REST services started experiencing 404 errors (The origin server did not find a current representation for target resource or it is not willing to disclose that one exists)

When I check the logs, I did not find any root cause which will bring whole application down. This was second time it happened and this time too I am unable to find root cause (Memory usage/CPU usage seems fine).
"Always on" setting is turned ON.

I have following questions: 1) What may be the root cause and Is there a way to find it ?

2) Is there way (in azure webapps) to know when application goes down and auto scale ? (I have already set auto scale rules for CPU usage and Memory usage but this did not help).

答:
A few thoughts:

If this is a critical service, you need two instances of your Web App running, even if you don't have the load to justify the second instance. The second instance is for reliability purposes.

The fact that you're getting a 404 instead of a 50x makes me think that this isn't an issue with your server being too busy and giving up due to resource starvation such as CPU utilization, http queue length, etc.

Places to check for troubleshooting:

On your Web App management blade in the Azure Portal, go to the Diagnostic Logs menu item. Turn on Application Logging, Web server logging, detailed error messages, and failed request tracing.

After completing the previous step, you will be able to go to the Diagnose and Solve Problems menu option and view Failed Request Tracing Logs. You will also be able to browse both the web server logs and application logs. I find it easiest to use Visual Studio to do so.

Just for fun, also check the Metrics per Instance under Diagnose and Solve problems. Check all categories during your reported 404 issue. This will let you check for conditions such as CPU usage, memory usage, number of threads, HTTP Queue length, etc.

Title: azure webapps 404 error


问:
npm start Microsoft JScript runtime error 800A138F object expected
Getting started with NPM...

I can run the following command to start my app.

```<code>node app
</code>```

But when I run the following command, I get the following error:

```<code>npm start
</code>```

Windows Script Host
  Object expected

Line 2

800A138F

Microsoft JScript runtime error

App.js:

```<code>var port = 5000;
var express = require('express');
</code>```

Package.json:

```<code>{
  "name": "2",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.13.3"
  }
}
</code>```

And I've run this command of course:

```<code>npm install express --save
</code>```

Seems like NPM can't find the express package? Why not?

答:
I had this problem as well. The .js files are associated with the Microsoft Script Engine. Some suggested that we dis-associate the extension with the program, but I do not think that is necessary. I was able to fix the issue with the following instruction that I found in the NODE Docs.

Please make sure that your file(s) referenced in bin starts with

```<code>#!/usr/bin/env node
</code>```

otherwise the scripts are started without the node executable!

Body:
Getting started with NPM...

I can run the following command to start my app.

node app

But when I run the following command, I get the following error:

npm start

Windows Script Host
  Object expected

Line 2

800A138F

Microsoft JScript runtime error

App.js:

var port = 5000;
var express = require('express');

Package.json:

{
  "name": "2",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.13.3"
  }
}

And I've run this command of course:

npm install express --save

Seems like NPM can't find the express package? Why not?

Body:
I had this problem as well. The .js files are associated with the Microsoft Script Engine. Some suggested that we dis-associate the extension with the program, but I do not think that is necessary. I was able to fix the issue with the following instruction that I found in the NODE Docs.

Please make sure that your file(s) referenced in bin starts with

#!/usr/bin/env node

otherwise the scripts are started without the node executable!


问:
Prevent access to constructor / only specific class has access
Let's say I have an Apple Class and an AppleFactoryClass.
Nobody should be able to use Apple redApple = new Apple(). Instead new Apples should only be able to be created from  AppleFactory.Create().

This mean the Constructor of Apple must be inaccessible for everyone but the AppleFactory Class.

How can this be done?

EDIT: Apple is more like an AppleModel. So there is only Properties in there.

答:
You can make Apple abstract, then make a private subclass inside AppleFactory.

However, you can't prevent other people from making their own subclasses.


问:
Can a function type be a class template parameter?
The code below is rejected by VC++ 2012 with "error C2207: 'A::bar' : a member of a class template cannot acquire a function type".

```<code>int Hello(int n)
{
    return n;
}

template<class FunctionPtr>
struct A
{
    A(FunctionPtr foo)
        : bar(foo)
    {}

    FunctionPtr bar;
};

int main()
{
    A<decltype(Hello)> a(Hello);

    return 0;
}
</code>```

Why?

答:
Adding on the other answers, you can take advantage of the fact that:

decltype(Hello) evaluates to int (int) (not to a function pointer type);

a function is implicitly convertible to a pointer to itself; this conversion happens pretty much everywhere (e.g. pass function by value (?) instead of function pointer?).

The following code:

```<code>#include <type_traits>

template<class F>
struct A
{
    A(F foo) : bar(foo) {}

    typename std::conditional<std::is_function<F>::value,
                              typename std::add_pointer<F>::type,
                              F>::type bar;
};
</code>```

is a generic solution allowing the same syntax for functions, function pointers, functors and lambdas:

```<code>#include <type_traits>
#include <iostream>

void Hello() { std::cout << "Function\n"; }

struct Hello2 { void operator()() { std::cout << "Struct\n"; } };

void Hello3() { std::cout << "Function pointer\n"; }

template<class F>
struct A
{
  A(F foo) : bar(foo) { bar(); }

  std::conditional_t<std::is_function<F>::value, std::add_pointer_t<F>, F> bar;
};

int main()
{
  A<decltype(Hello)> a(Hello);

  Hello2 h2;
  A<decltype(h2)> b(h2);

  A<decltype(&Hello3)> c(&Hello3);

  auto Hello4 = []() { std::cout << "Lambda\n"; };
  A<decltype(Hello4)> d(Hello4);
}
</code>```

(here I've slightly changed the solution taking advantage of C++14 features).

Indeed std::function is a (not always better) alternative.

Body:
The code below is rejected by VC++ 2012 with "error C2207: 'A::bar' : a member of a class template cannot acquire a function type".

int Hello(int n)
{
    return n;
}

template<class FunctionPtr>
struct A
{
    A(FunctionPtr foo)
        : bar(foo)
    {}

    FunctionPtr bar;
};

int main()
{
    A<decltype(Hello)> a(Hello);

    return 0;
}

Why?

Body:
Adding on the other answers, you can take advantage of the fact that:

decltype(Hello) evaluates to int (int) (not to a function pointer type);

a function is implicitly convertible to a pointer to itself; this conversion happens pretty much everywhere (e.g. pass function by value (?) instead of function pointer?).

The following code:

#include <type_traits>

template<class F>
struct A
{
    A(F foo) : bar(foo) {}

    typename std::conditional<std::is_function<F>::value,
                              typename std::add_pointer<F>::type,
                              F>::type bar;
};

is a generic solution allowing the same syntax for functions, function pointers, functors and lambdas:

#include <type_traits>
#include <iostream>

void Hello() { std::cout << "Function\n"; }

struct Hello2 { void operator()() { std::cout << "Struct\n"; } };

void Hello3() { std::cout << "Function pointer\n"; }

template<class F>
struct A
{
  A(F foo) : bar(foo) { bar(); }

  std::conditional_t<std::is_function<F>::value, std::add_pointer_t<F>, F> bar;
};

int main()
{
  A<decltype(Hello)> a(Hello);

  Hello2 h2;
  A<decltype(h2)> b(h2);

  A<decltype(&Hello3)> c(&Hello3);

  auto Hello4 = []() { std::cout << "Lambda\n"; };
  A<decltype(Hello4)> d(Hello4);
}

(here I've slightly changed the solution taking advantage of C++14 features).

Indeed std::function is a (not always better) alternative.

ContentLicense: CC BY-SA 4.0


答: There was Azure outage reported (which happened twice in one month). They said they are working on this and above mentioned issue is caused by Outage in West Europe region.</p>

Title: azure webapps 404 error

Body:
I have web application developed in Spring boot (REST services) which is deployed on Azure webapps (Azure app service). My plan is Standard: 1 Small.

The application has been running smoothly since 2 weeks. All of a sudden, today, the application went down. Consumer application which calls these REST services started experiencing 404 errors (The origin server did not find a current representation for target resource or it is not willing to disclose that one exists)

When I check the logs, I did not find any root cause which will bring whole application down. This was second time it happened and this time too I am unable to find root cause (Memory usage/CPU usage seems fine).
"Always on" setting is turned ON.

I have following questions: 1) What may be the root cause and Is there a way to find it ?

2) Is there way (in azure webapps) to know when application goes down and auto scale ? (I have already set auto scale rules for CPU usage and Memory usage but this did not help).


问:
Possible to get name of current class from an uninstantiated object in PHP?
I know you can use get_class($this) normally but I need to get the name of the class in a static function where the object hasn't been instantiated.

See the following code:

```<code>class ExampleClass
{
    static function getClassName()
    {
        echo get_class($this); // doesn't work unless the object is instantiated.
    }
}

$test1 = new ExampleClass();
$test1->getClassName(); // works

ExampleClass::getClassName(); // doesn't work
</code>```

答:
I think you're looking for the get_called_class() function, if you wish to get the class name from a static method.

See get_called_class documentation for more information.

OwnerDisplayName: Andrew G. Johnson

Body:
I know you can use get_class($this) normally but I need to get the name of the class in a static function where the object hasn't been instantiated.

See the following code:

class ExampleClass
{
    static function getClassName()
    {
        echo get_class($this); // doesn't work unless the object is instantiated.
    }
}

$test1 = new ExampleClass();
$test1->getClassName(); // works

ExampleClass::getClassName(); // doesn't work

OwnerDisplayName: Eddie Parker


问:
Load MovieClip inline in TextField
I want to load a MovieClip inside a TextField inline with the text.

The TextField documentation says "HTML text that you assign to a text field can contain embedded media (movie clips, SWF files, GIF files, PNG files, and JPEG files)."

How can this be done with MovieClips? There must be a listener we can override.

source: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextField.html

答:
From the documentation :

src: Specifies the URL to an image or
  SWF file, or the linkage identifier
  for a movie clip symbol in the
  library. This attribute is required;
  all other attributes are optional.
  External files (JPEG, GIF, PNG, and
  SWF files) do not show until they are
  downloaded completely.

You can add MovieClip by setting his linkage identifier in the src attribute of the  node.

Title: Load MovieClip inline in TextField

Body:
From the documentation :

src: Specifies the URL to an image or
  SWF file, or the linkage identifier
  for a movie clip symbol in the
  library. This attribute is required;
  all other attributes are optional.
  External files (JPEG, GIF, PNG, and
  SWF files) do not show until they are
  downloaded completely.

You can add MovieClip by setting his linkage identifier in the src attribute of the <img> node.


问:
Default .NET sanitization on DropDownList (WebControls)
I'm working with legacy code - WebControls with some .NET, got XSS problems.
In my code behind I've got simple DropDownList with ListItems added in a foreach like this:

```<code> foreach (string enumValue in aEnumValues)
      pListBox.Items.Add(new ListItem(enumValue, enumValue));
</code>```

But, when the dropDown is generated, value attributes of options aren't fully sanitized. The options in response body look like this:

```<code><option selected="selected" value=""><img src=2 onerror=alert(y65)>">"><img src=2 onerror=alert(y65)></option>
<option value="df">df</option>
<option value=""dsdf><img src=2 onerror=alert(y65)> "><img src=2 onerror=alert(y65)>    ">"dsdf><img src=2 onerror=alert(y65)>    "><img src=2 onerror=alert(y65)>  </option>
</code>```

As you can see, for value attributes, not all characters are escaped. How can I fix this? Or is this some issue with WebControls?

答:
Values in ListControls are usually integers, if you can refactor it it would be more maintainable for any future changes. If you want a quick fix, u can need to encode the html parts:

```<code>foreach (string enumValue in aEnumValues)
    pListBox.Items.Add(new ListItem(enumValue, Server.HtmlEncode(enumValue)));
</code>```

Update(based on yr comment):

if u look at the select tag it show html tags, have u ever seen a select tag showing html tags? I bet the select tag is hidden and it's for some logic in page. Usally the value attribute in the option tag is one word like integer or code:

```<code><select id="card">
  <option value="visa">Visa</option>
  <option value="mc">Master card</option>  -- value is abbreviation of display text
  <option value="amex">American Express</option>
</select>
<select id="lstStates">
  <option value="CA">California</option>  -- value is state's code
  <option value="FL">Florida</option>
</select>
<select id="lstStaffs">
  <option value="1001">Daniel Smith</option>   --value is StaffId
  <option value="1008">John Doe</option>
</select>
</code>```

Body:
I'm working with legacy code - WebControls with some .NET, got XSS problems.
In my code behind I've got simple DropDownList with ListItems added in a foreach like this:

 foreach (string enumValue in aEnumValues)
      pListBox.Items.Add(new ListItem(enumValue, enumValue));

But, when the dropDown is generated, value attributes of options aren't fully sanitized. The options in response body look like this:

<option selected="selected" value="">">"></option>
<option value="df">df</option>
<option value=""dsdf> ">    ">"dsdf>    ">  </option>

As you can see, for value attributes, not all characters are escaped. How can I fix this? Or is this some issue with WebControls?

Body:
Values in ListControls are usually integers, if you can refactor it it would be more maintainable for any future changes. If you want a quick fix, u can need to encode the html parts:

foreach (string enumValue in aEnumValues)
    pListBox.Items.Add(new ListItem(enumValue, Server.HtmlEncode(enumValue)));

Update(based on yr comment):

if u look at the select tag it show html tags, have u ever seen a select tag showing html tags? I bet the select tag is hidden and it's for some logic in page. Usally the value attribute in the option tag is one word like integer or code:

<select id="card">
  <option value="visa">Visa</option>
  <option value="mc">Master card</option>  -- value is abbreviation of display text
  <option value="amex">American Express</option>
</select>
<select id="lstStates">
  <option value="CA">California</option>  -- value is state's code
  <option value="FL">Florida</option>
</select>
<select id="lstStaffs">
  <option value="1001">Daniel Smith</option>   --value is StaffId
  <option value="1008">John Doe</option>
</select>


问:
Window.scroll within an iframe
I searched, but couldn't find anything.

I have a sticky header that shows up on the page after scrolling down on the page. This was working wonderfully on the page. However, I now have to unfortunately have to put it within an iframe.

I have to same exact code, but I believe it's the window.scroll that is causing it to trip up. The content is just sitting at the top of the page behind everything and when inspecting the code it stops at that function and goes no further.

Is there an alternative to window.scroll (or scroll function) or is there a way to make it work within an iframe? All my attempts have failed.

My example is here https://www.bootply.com/edHiY15iJy#

My HTML for the header

```<code><div class="container">
        <header class="header-wrapper">
            <div class="sticky-header">
                <div class="row">
                        <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Customer Name: </label>
                            <label>Person!! </label>
                        </div>
                        <div class="form-group">
                            <label class="bold">Address: </label>
                            <label>101 Main Street </label>
                        </div>

                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Email:</label>
                            <label>something@email.com </label>
                        </div>
                        <div class="form-group">
                            <label class="bold">City, State:</label>
                            <label>Tavierner, FL </label>
                        </div>

                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Phone:</label>
                            <label>555-555-5555 </label>
                        </div>

                        <div class="form-group">
                            <label class="bold">Club Code:</label>
                            <label>456 </label>
                            <label class="bold">Associate#:</label>
                            <label>45 </label>
                        </div>
                    </div>
                </div>
            </div>
        </header>
  <section>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>

  </section>
</div>
</code>```

and my jquery

```<code> if ($('.sticky-header').length >= 1) {
        $(window).scroll(function () {
            var header = $(document).scrollTop();
            var headerHeight = $('.header-wrapper').height();
            if (header > headerHeight) {
                $('.sticky-header').addClass('sticky');
                $('.sticky-header').fadeIn();
            } else {
                $('.sticky-header').removeClass('sticky');
            }
        });
    }
</code>```

A screenshot of what the menu looks like when it's not working:

答:
my solution is: use a wrapper to the whole page, you can use body tag too, put the following css:

```<code><style>
 html,
 body {
   height: 100%;
 }
 body {
   overflow-y: scroll;
 }
</style>
</code>```

and test it in your js:

```<code><script>
  $('body').on('scroll', function() {
  // your code goes here...
  console.log('scroll being made');
  })
</script>
</code>```

Title: Window.scroll within an iframe

Body:
I searched, but couldn't find anything.

I have a sticky header that shows up on the page after scrolling down on the page. This was working wonderfully on the page. However, I now have to unfortunately have to put it within an iframe.

I have to same exact code, but I believe it's the window.scroll that is causing it to trip up. The content is just sitting at the top of the page behind everything and when inspecting the code it stops at that function and goes no further.

Is there an alternative to window.scroll (or scroll function) or is there a way to make it work within an iframe? All my attempts have failed.

My example is here https://www.bootply.com/edHiY15iJy#

My HTML for the header

                            Customer Name:
                            Person!!

                            Address:
                            101 Main Street

                            Email:
                            something@email.com

                            City, State:
                            Tavierner, FL

                            Phone:
                            555-555-5555

                            Club Code:
                            456
                            Associate#:
                            45

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

and my jquery

 if ($('.sticky-header').length >= 1) {
        $(window).scroll(function () {
            var header = $(document).scrollTop();
            var headerHeight = $('.header-wrapper').height();
            if (header > headerHeight) {
                $('.sticky-header').addClass('sticky');
                $('.sticky-header').fadeIn();
            } else {
                $('.sticky-header').removeClass('sticky');
            }
        });
    }

A screenshot of what the menu looks like when it's not working:

Body:
my solution is: use a wrapper to the whole page, you can use body tag too, put the following css:

<style>
 html,
 body {
   height: 100%;
 }
 body {
   overflow-y: scroll;
 }
</style>

and test it in your js:

<script>
  $('body').on('scroll', function() {
  // your code goes here...
  console.log('scroll being made');
  })
</script>


问:
Emacs enum indentation
I'm having a problem with Emacs's indentation of Java enums. While it indents the first member OK, it wants to give all of the rest of the static enum members an additional level of indentation. It looks like this:

```<code>class MyClass {
    public enum MyEnum {
        ONE(1), //good
            TWO(2), // not good!
            THREE(3),
            FOUR(4);
        private final int value;
    }
}
</code>```

When I run C-c C-s on the line that opens the enum, it gives me ((inclass 1) (topmost-intro 1)), which doesn't seem quite right -- it seems like it should be giving brace-list-open. When I run it on the first enum member, it gives me ((defun-block-intro 21)), which is definitely not right. Every subsequent member gives (statement-cont 50).

I'm in java-mode and I'm using the java style of indentation. Does anyone know what the problem might be?

答: The CVS version of CC-mode does indeed contain the necessary fixes, as Nathaniel Flath mentioned earlier. It is easy to install. Just check it out from here (let's say, into ~/.emacs.d/cc-mode), byte-compile, as explained in readme, and add to load path by adding (add-to-list 'load-path "~/.emacs.d/cc-mode") to your ~/.emacs.d/init.el. Then enum indentation works like a charm !</p>

Title: Emacs enum indentation

Body:
I'm having a problem with Emacs's indentation of Java enums. While it indents the first member OK, it wants to give all of the rest of the static enum members an additional level of indentation. It looks like this:

class MyClass {
    public enum MyEnum {
        ONE(1), //good
            TWO(2), // not good!
            THREE(3),
            FOUR(4);
        private final int value;
    }
}

When I run C-c C-s on the line that opens the enum, it gives me ((inclass 1) (topmost-intro 1)), which doesn't seem quite right -- it seems like it should be giving brace-list-open. When I run it on the first enum member, it gives me ((defun-block-intro 21)), which is definitely not right. Every subsequent member gives (statement-cont 50).

I'm in java-mode and I'm using the java style of indentation. Does anyone know what the problem might be?


问:
Google Slides API, positioning of image on the slide
I am inserting an Image to a Google Slide using Google Slides API , My code is

```<code>    $emu4M = array('magnitude' => 5500000, 'unit' => 'EMU');
    $requests = array();
    $requests[] = new Google_Service_Slides_Request(array(
      'createImage' => array (
        'objectId' => '303030',
        'url' => $imageUrl,
        'elementProperties' => array(
          'pageObjectId' => $pageId,
          'size' => array(
            'height' => $emu4M,
            'width' => $emu4M
          ),
          'transform' => array(
            'scaleX' => 1,
            'scaleY' => 1,
            'translateX' => 5000,
            'translateY' => 5000,
            'unit' => 'EMU'
          )
        )
      )
    ));
</code>```

It works fine but the image inserted is like this

I want the image to appear in center and reduce padding from top. Any help?

答:
Slides image positioning works by creating a rectangle based on your given size, aspect fitting the actual image in that rectangle, then applying your transform. As a result, you'll often get extra padding if the size you provide doesn't match the aspect ratio of the image.

Make sure the size you're providing matches the size of the image, and then do some math with the pageSize and image size to figure out the right values of translateX/translateY to use.

Body:
I am inserting an Image to a Google Slide using Google Slides API , My code is

    $emu4M = array('magnitude' => 5500000, 'unit' => 'EMU');
    $requests = array();
    $requests[] = new Google_Service_Slides_Request(array(
      'createImage' => array (
        'objectId' => '303030',
        'url' => $imageUrl,
        'elementProperties' => array(
          'pageObjectId' => $pageId,
          'size' => array(
            'height' => $emu4M,
            'width' => $emu4M
          ),
          'transform' => array(
            'scaleX' => 1,
            'scaleY' => 1,
            'translateX' => 5000,
            'translateY' => 5000,
            'unit' => 'EMU'
          )
        )
      )
    ));

It works fine but the image inserted is like this

I want the image to appear in center and reduce padding from top. Any help?


问:
Parsing every file in submap recursively to output folder whilst maintaining relativity
I'm using the following batch code to convert all files in a certain directory if the target file doesn't already exist however I'm stuck at getting this to run through every submap and file within that (and keep the output relative with that submap)

So I currently use this:

```<code>for %%f in (input/textures/*.*) do ( IF NOT EXIST "ouput/textures/%%~nf.dds" (
"bin/ThempImageParser.exe" "input/textures/%%f" "ouput/textures/%%~nf.dds"
)
)
</code>```

This works perfectly for a single folder (as was intended), it takes all the files in that specific folder, and passes them as arguments to my executable, which then outputs the file on the path of the second argument.

However this also contains a flaw (this is an additional problem though..) as it does not work if the output -folder- does not exist, so if possible I'd also want it to create the folder if need be.

I've found some batch documentation (I really don't have much experience with Batch) showing me a command called FORFILES and the /R parameter, however I couldn't adjust this so it'd keep the relative paths for the output too, it'd require string manipulation and I have no clue on how to do that.

So the result I'm after is something like this, it takes any file deeper than "input/textures/ for example:

```<code>input/textures/some/very/deep/submap/why/does/it/go/on/myfile.anyExtension
</code>```

it should then take that file (and relative path) and basically change "input" with "output" and replace the file extension with .dds like this:

```<code>ouput/textures/some/very/deep/submap/why/does/it/go/on/myfile.dds
</code>```

and pass those two strings to my executable.

答:
@ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir\t w o"
SET "destdir=U:\destdir\wherever\something"

FOR /f "delims=" %%a IN ('xcopy /y /L /s "%sourcedir%\*"') DO (
 SET "destfile=%%a"
 SET "destfile=!destfile:*%sourcedir%=%destdir%!"
 IF /i "%%a" neq "!destfile!" (
  FOR %%m IN ("!destfile!") DO IF NOT EXIST "%%~dpm%%~na.dds" (
   ECHO MD "%%~dpm"
   ECHO "bin\ThempImageParser.exe" "%%a" "%%~dpm%%~na.dds"
  )
 )
)

GOTO :EOF
```

You would need to change the settings of sourcedir and destdir to suit your circumstances.

First, perform an xcopy with the /L option to list-only the individual fullnames of files that would be copied by the xcopy.

Assign each name found from %%a to destfile, then remove all characters before the source-directoryname from that filename, and replace that string with the destination directoryname.

This will yield the destination name for the file (with the original extension). The only exception will be the very last output line, which is a count-of-files report. Since this line will not contain the source directoryname, the replacement will not take place, so %%a will be the same as !destfile! - so we eliminate that.

Now assign the destination filename to a metavariable so we can select its various parts, and if the filename made from the destination drive and pathname, the name part of the original file and .dds does not exist, then make the destination directoryname and execute the imageparser, providing the desired output filename.

Note that these last two are ECHOed instead of being executed for testing purposes. Remove the ECHOes to actually perform the command.

Note that / is a switch-indicator, \ is a directory-separator.

Note that MD will report an error if the directory already exists. Append 2>nul to the end of the md command to suppress that error message.

Body:
I'm using the following batch code to convert all files in a certain directory if the target file doesn't already exist however I'm stuck at getting this to run through every submap and file within that (and keep the output relative with that submap)

So I currently use this:

for %%f in (input/textures/*.*) do ( IF NOT EXIST "ouput/textures/%%~nf.dds" (
"bin/ThempImageParser.exe" "input/textures/%%f" "ouput/textures/%%~nf.dds"
)
)

This works perfectly for a single folder (as was intended), it takes all the files in that specific folder, and passes them as arguments to my executable, which then outputs the file on the path of the second argument.

However this also contains a flaw (this is an additional problem though..) as it does not work if the output -folder- does not exist, so if possible I'd also want it to create the folder if need be.

I've found some batch documentation (I really don't have much experience with Batch) showing me a command called FORFILES and the /R parameter, however I couldn't adjust this so it'd keep the relative paths for the output too, it'd require string manipulation and I have no clue on how to do that.

So the result I'm after is something like this, it takes any file deeper than "input/textures/ for example:

input/textures/some/very/deep/submap/why/does/it/go/on/myfile.anyExtension

it should then take that file (and relative path) and basically change "input" with "output" and replace the file extension with .dds like this:

ouput/textures/some/very/deep/submap/why/does/it/go/on/myfile.dds

and pass those two strings to my executable.

Body:
@ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir\t w o"
SET "destdir=U:\destdir\wherever\something"

FOR /f "delims=" %%a IN ('xcopy /y /L /s "%sourcedir%\*"') DO (
 SET "destfile=%%a"
 SET "destfile=!destfile:*%sourcedir%=%destdir%!"
 IF /i "%%a" neq "!destfile!" (
  FOR %%m IN ("!destfile!") DO IF NOT EXIST "%%~dpm%%~na.dds" (
   ECHO MD "%%~dpm"
   ECHO "bin\ThempImageParser.exe" "%%a" "%%~dpm%%~na.dds"
  )
 )
)

GOTO :EOF

You would need to change the settings of sourcedir and destdir to suit your circumstances.

First, perform an xcopy with the /L option to list-only the individual fullnames of files that would be copied by the xcopy.

Assign each name found from %%a to destfile, then remove all characters before the source-directoryname from that filename, and replace that string with the destination directoryname.

This will yield the destination name for the file (with the original extension). The only exception will be the very last output line, which is a count-of-files report. Since this line will not contain the source directoryname, the replacement will not take place, so %%a will be the same as !destfile! - so we eliminate that.

Now assign the destination filename to a metavariable so we can select its various parts, and if the filename made from the destination drive and pathname, the name part of the original file and .dds does not exist, then make the destination directoryname and execute the imageparser, providing the desired output filename.

Note that these last two are ECHOed instead of being executed for testing purposes. Remove the ECHOes to actually perform the command.

Note that / is a switch-indicator, \ is a directory-separator.

Note that MD will report an error if the directory already exists. Append 2>nul to the end of the md command to suppress that error message.


问:
Extracting JSON-data from CSV file
I'm trying to extract a JSON data which is a column in a CSV file. So far I've come to the point where I've extracted the column in the right format, but the formatting is only correct when the variable type is factor. But I can't convert a factor to a json-file using the jsonlite package.

```<code>[1] {"id":509746197991998767,"visibility":{"percentage":100,"time":149797,"visible1":true,"visible2":false,"visible3":false,"activetab":true},"interaction":{"mouseovercount":1,"mouseovertime":1426,"videoplaytime":0,"engagementtime":0,"expandtime":0,"exposuretime":35192}}
</code>```

Another approach is to use stringsAsFactors = F when importing, but I'm struggling in getting the formatting right, where each entry looks like this:

```<code>[1] "{\"id\":509746197991998767,\"visibility\":{\"percentage\":100,\"time\":149797,\"visible1\":true,\"visible2\":false,\"visible3\":false,\"activetab\":true},\"interaction\":{\"mouseovercount\":1,\"mouseovertime\":1426,\"videoplaytime\":0,\"engagementtime\":0,\"expandtime\":0,\"exposuretime\":35192}}"
</code>```

Am I missing something obvious here? I simply just want to exract the JSON files that sits inside a CSV file.

Heres a small example of the CSV file:

```<code>"","CookieID","UnloadVars"
"1",-8857188784608690176,"{""id"":509746197991998767,""visibility"":{""percentage"":100,""time"":149797,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":1,""mouseovertime"":1426,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":35192}}"
"2",-1695626857458244096,"{""id"":2917654329769114342,""visibility"":{""percentage"":46,""time"":0,""visible1"":false,""visible2"":false,""visible3"":false,""activetab"":true}}"
"3",437299165071669184,"{""id"":2252707957388071809,""visibility"":{""percentage"":99,""time"":10168,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":542},""clicks"":[{""x"":105,""y"":449}]}"
"4",292660729552227520,""
"5",7036383942916227072,"{""id"":2299674593327687292,""visibility"":{""percentage"":76,""time"":1145,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":74},""clicks"":[{""x"":197,""y"":135},{""x"":197,""y"":135}]}"
</code>```

Regards,

Frederik.

答:
It can be very tricky to deal with JSON data. As a general guide line, you should always strive to have your data in a data frame. This, however, is not always possible. In the specific case, I don't see a way you can have both visibility and interaction values at once in a nicely formatted data frame.

What I will do next is to extract the information from interaction into a data frame.

Load required packages and read the data

```<code>library(purrr)
library(dplyr)
library(tidyr)
df <- read.csv("sample.csv", stringsAsFactors = FALSE)
</code>```

Then remove unvalid JSON

```<code># remove rows without JSON (in this case, the 4th row)
df <- df %>%
  dplyr::filter(UnloadVars != "")
</code>```

Transform each JSON into a list and put them into UnloadVars column. If you didn't know that, it is possible to have list column in a data frame. This can be very useful.

```<code>out <- data_frame(CookieID = numeric(),
                  UnloadVars = list())

for (row in 1:nrow(df)) {
  new_row <- data_frame(CookieID = df[row, ]$CookieID,
                        UnloadVars = list(jsonlite::fromJSON(df[row, ]$UnloadVars)))

  out <- bind_rows(out, new_row)
}

out
</code>```

We can now extract the IDs from the lists in Unload Vars. This is straight forward because there is only one ID per list.

```<code>out <- out %>%
  mutate(id = map_chr(UnloadVars, ~ .$id))
</code>```

This final part can seem a bit intimidating. But what I am doing here is taking interaction part from UnloadVars column and putting it into a interaction column. I then transform each row from interaction, which is a list, into a data frame with two columns: key and value. key contains the name of the interaction metric and value its value. I finally unnest it, so we get rid of list columns and end up with a nicely formatted data frame.

```<code>unpack_list <- function(obj, key_name) {
  as.data.frame(obj) %>%
    gather(key) %>%
    return()
}

df_interaction <- out %>%
    mutate(interaction = map(UnloadVars, ~ .$interaction)) %>%
    mutate(interaction = map(interaction, ~ unpack_list(.x, key))) %>%
    unnest(interaction)

df_interaction
</code>```

The solution is not very elegant, but gets the job done. You could apply the same logic to extract information from visibility.

Title: Extracting JSON-data from CSV file

Body:
I'm trying to extract a JSON data which is a column in a CSV file. So far I've come to the point where I've extracted the column in the right format, but the formatting is only correct when the variable type is factor. But I can't convert a factor to a json-file using the jsonlite package.

[1] {"id":509746197991998767,"visibility":{"percentage":100,"time":149797,"visible1":true,"visible2":false,"visible3":false,"activetab":true},"interaction":{"mouseovercount":1,"mouseovertime":1426,"videoplaytime":0,"engagementtime":0,"expandtime":0,"exposuretime":35192}}

Another approach is to use stringsAsFactors = F when importing, but I'm struggling in getting the formatting right, where each entry looks like this:

[1] "{\"id\":509746197991998767,\"visibility\":{\"percentage\":100,\"time\":149797,\"visible1\":true,\"visible2\":false,\"visible3\":false,\"activetab\":true},\"interaction\":{\"mouseovercount\":1,\"mouseovertime\":1426,\"videoplaytime\":0,\"engagementtime\":0,\"expandtime\":0,\"exposuretime\":35192}}"

Am I missing something obvious here? I simply just want to exract the JSON files that sits inside a CSV file.

Heres a small example of the CSV file:

"","CookieID","UnloadVars"
"1",-8857188784608690176,"{""id"":509746197991998767,""visibility"":{""percentage"":100,""time"":149797,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":1,""mouseovertime"":1426,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":35192}}"
"2",-1695626857458244096,"{""id"":2917654329769114342,""visibility"":{""percentage"":46,""time"":0,""visible1"":false,""visible2"":false,""visible3"":false,""activetab"":true}}"
"3",437299165071669184,"{""id"":2252707957388071809,""visibility"":{""percentage"":99,""time"":10168,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":542},""clicks"":[{""x"":105,""y"":449}]}"
"4",292660729552227520,""
"5",7036383942916227072,"{""id"":2299674593327687292,""visibility"":{""percentage"":76,""time"":1145,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":74},""clicks"":[{""x"":197,""y"":135},{""x"":197,""y"":135}]}"

Regards,

Frederik.

Body:
It can be very tricky to deal with JSON data. As a general guide line, you should always strive to have your data in a data frame. This, however, is not always possible. In the specific case, I don't see a way you can have both visibility and interaction values at once in a nicely formatted data frame.

What I will do next is to extract the information from interaction into a data frame.

Load required packages and read the data

library(purrr)
library(dplyr)
library(tidyr)
df <- read.csv("sample.csv", stringsAsFactors = FALSE)

Then remove unvalid JSON

# remove rows without JSON (in this case, the 4th row)
df <- df %>%
  dplyr::filter(UnloadVars != "")

Transform each JSON into a list and put them into UnloadVars column. If you didn't know that, it is possible to have list column in a data frame. This can be very useful.

out <- data_frame(CookieID = numeric(),
                  UnloadVars = list())

for (row in 1:nrow(df)) {
  new_row <- data_frame(CookieID = df[row, ]$CookieID,
                        UnloadVars = list(jsonlite::fromJSON(df[row, ]$UnloadVars)))

  out <- bind_rows(out, new_row)
}

out

We can now extract the IDs from the lists in Unload Vars. This is straight forward because there is only one ID per list.

out <- out %>%
  mutate(id = map_chr(UnloadVars, ~ .$id))

This final part can seem a bit intimidating. But what I am doing here is taking interaction part from UnloadVars column and putting it into a interaction column. I then transform each row from interaction, which is a list, into a data frame with two columns: key and value. key contains the name of the interaction metric and value its value. I finally unnest it, so we get rid of list columns and end up with a nicely formatted data frame.

unpack_list <- function(obj, key_name) {
  as.data.frame(obj) %>%
    gather(key) %>%
    return()
}

df_interaction <- out %>%
    mutate(interaction = map(UnloadVars, ~ .$interaction)) %>%
    mutate(interaction = map(interaction, ~ unpack_list(.x, key))) %>%
    unnest(interaction)

df_interaction

The solution is not very elegant, but gets the job done. You could apply the same logic to extract information from visibility.


问:
AWS SQS subscription to AWS SNS topic
I have use case in that I want to subscribe single SQS to two SNS topic. So that whatever message publish to any SNS should be available in SQS. So my question is Can we subscribe one sqs to two SNS topic? </p>

<p>Any help here will be appreciated. </p>

答:
```<code>{
"Version": "2012-10-17",
"Id": "arn:aws:sqs:us-east-1:<account-number>:<sqs-name>/SQSDefaultPolicy",
"Statement": [
     {
    "Sid": "<sid>",
    "Effect": "Allow",
    "Principal": "*",
    "Action": "SQS:SendMessage",
    "Resource": "arn:aws:sqs:us-east-1:<account-number>:<name>",
    "Condition": {
            "ArnEquals": {
                  "aws:SourceArn": "arn:aws:sns:us-west-2:<account-number>:*"
                 }
            }
  }
 ]
}
</code>```

Here * is the key. It allows other sns to write to the same queue.

I have answered the same here SNS multiple subscribers

Title: AWS SQS subscription to AWS SNS topic

Body:
I have use case in that I want to subscribe single SQS to two SNS topic. So that whatever message publish to any SNS should be available in SQS. So my question is Can we subscribe one sqs to two SNS topic?

Any help here will be appreciated.

Body:
{
"Version": "2012-10-17",
"Id": "arn:aws:sqs:us-east-1:<account-number>:<sqs-name>/SQSDefaultPolicy",
"Statement": [
     {
    "Sid": "<sid>",
    "Effect": "Allow",
    "Principal": "*",
    "Action": "SQS:SendMessage",
    "Resource": "arn:aws:sqs:us-east-1:<account-number>:<name>",
    "Condition": {
            "ArnEquals": {
                  "aws:SourceArn": "arn:aws:sns:us-west-2:<account-number>:*"
                 }
            }
  }
 ]
}

Here * is the key. It allows other sns to write to the same queue.

I have answered the same here SNS multiple subscribers


问:
Angular Material - Prevent mat-stepper from navigating between steps
I have a mat-horizontal-stepper where I set linear property as true. When all the steps are valid as of now I can navigate to previous steps by clicking the header or label. I don't want that property.

I need to navigate only through buttons.

I tried disabling pointer function with:

```<code>    .mat-horizontal-stepper-header{
       pointer-events: none;
     }
</code>```

but it didn't worked.

I need either to stop navigating by clicking header or fire a function on clicking the stepper header.

答:
To fire a function when clicking the stepper header, you can subscribe to MatStepper.selectionChange. It is emitted when switching steps and gives you information about the previous step and the selected step.

html:

```<code><mat-horizontal-stepper #stepper[linear]="true">
  <mat-step label="firstStep">
    ...
  </mat-step>
</mat-horizontal-stepper>
</code>```

ts:

```<code>class ExampleComponent implements OnInit {
  @ViewChild('stepper') stepper: MatStepper;

  ngOnInit() {
    this.stepper.selectionChange.subscribe(selection => {
       console.log(selection.selectedStep)
       console.log(selection.previouslySelectedStep)
    }
 }
</code>```

When the selected step is the last one, you could use this to set editable = false in all the previous steps:

```<code>this.stepper._steps.forEach(step => step.editable = false);
</code>```

Body:
I have a mat-horizontal-stepper where I set linear property as true. When all the steps are valid as of now I can navigate to previous steps by clicking the header or label. I don't want that property.

I need to navigate only through buttons.

I tried disabling pointer function with:

    .mat-horizontal-stepper-header{
       pointer-events: none;
     }

but it didn't worked.

I need either to stop navigating by clicking header or fire a function on clicking the stepper header.

Body:
To fire a function when clicking the stepper header, you can subscribe to MatStepper.selectionChange. It is emitted when switching steps and gives you information about the previous step and the selected step.

html:

<mat-horizontal-stepper #stepper[linear]="true">
  <mat-step label="firstStep">
    ...
  </mat-step>
</mat-horizontal-stepper>

ts:

class ExampleComponent implements OnInit {
  @ViewChild('stepper') stepper: MatStepper;

  ngOnInit() {
    this.stepper.selectionChange.subscribe(selection => {
       console.log(selection.selectedStep)
       console.log(selection.previouslySelectedStep)
    }
 }

When the selected step is the last one, you could use this to set editable = false in all the previous steps:

this.stepper._steps.forEach(step => step.editable = false);


问:
How to create a list of igraph graphs from .graphml files in R
I'm trying to execute the CalculateVertexHistKernel(G) in the graphkernels R package method to compute the similarity between two graphs.

G is a list of igraph graphs. How do I create a igraph list from a set of graphml files?

答:
Below is the code for building a list of igraph graphs for existing .graphml files. graphkernals work with only (positive) numerical values. Hence I had to replace the operators with numerical codes. I have used (* == 1). Otherwise the and the function CalculateVertexHistKernel(G) crashes.

```<code>#loading the files
g1 <- read.graph("15_4.graphml", format = "graphml")
g2 <- read.graph("30_2.graphml", format = "graphml")

#replacing * with 1
V(G[[1]])$label
[1] NaN  15   4 #NaN is the *
V(G[[2]])$label
[1] NaN  30   2

V(G[[1]])$label[1] <- 1
V(G[[2]])$label[1] <- 1

#creating the list
gList = list(g1,g2)

#computing similarity
k<-CalculateVertexHistKernel(gList)
</code>```

Author of the package Dr. Mahito Sugiyama provided this solution.

Body:
Below is the code for building a list of igraph graphs for existing .graphml files. graphkernals work with only (positive) numerical values. Hence I had to replace the operators with numerical codes. I have used (* == 1). Otherwise the and the function CalculateVertexHistKernel(G) crashes.

#loading the files
g1 <- read.graph("15_4.graphml", format = "graphml")
g2 <- read.graph("30_2.graphml", format = "graphml")

#replacing * with 1
V(G[[1]])$label
[1] NaN  15   4 #NaN is the *
V(G[[2]])$label
[1] NaN  30   2

V(G[[1]])$label[1] <- 1
V(G[[2]])$label[1] <- 1

#creating the list
gList = list(g1,g2)

#computing similarity
k<-CalculateVertexHistKernel(gList)

Author of the package Dr. Mahito Sugiyama provided this solution.


问:
set base URL dynamicaly in Laravel 5
I have two versions of a site one running at on example.com
and other at example.com/version2.

In web.php I have

```<code>    Route::group(['middleware'=>['webconfig'],'prefix'=>'version2'], function(){
        //Routes for version2 site
    });
// Routes for main site
</code>```

In webconfig middleware I set database connection for version2 site. Which is working fine but I am also setting base URL for version2 site. which not working url() method returns example.com
Here is my webconfig middleware

```<code>public function handle($request, Closure $next)
{
    \Config::set('database.default', 'mysql_us');
    \Config::set('app.url', url('version2'));
    return $next($request);
}
</code>```

So how can I set base url dynamicaly.

答:
since your 2 version deployed in the same hosting and you just add a prefix 'version2' for your new version. why not just create a middleware that checked your segment(1) if it's version2 or not then set the correct database that it'll be using. I believe you want to redirect to other database when users are in version2 segment, am i right?

In this case you can just use a solution like this in your middleware,

```<code>if (Str::lower($request->segment(1) == "version2") {
    config()->set('database.default', 'mysql_us');
} else {
    // your another config.
}
</code>```

i hope this will help you with your issue.

Title: set base URL dynamicaly in Laravel 5

Body:
I have two versions of a site one running at on example.com
and other at example.com/version2.

In web.php I have

    Route::group(['middleware'=>['webconfig'],'prefix'=>'version2'], function(){
        //Routes for version2 site
    });
// Routes for main site

In webconfig middleware I set database connection for version2 site. Which is working fine but I am also setting base URL for version2 site. which not working url() method returns example.com
Here is my webconfig middleware

public function handle($request, Closure $next)
{
    \Config::set('database.default', 'mysql_us');
    \Config::set('app.url', url('version2'));
    return $next($request);
}

So how can I set base url dynamicaly.

Body:
since your 2 version deployed in the same hosting and you just add a prefix 'version2' for your new version. why not just create a middleware that checked your segment(1) if it's version2 or not then set the correct database that it'll be using. I believe you want to redirect to other database when users are in version2 segment, am i right?

In this case you can just use a solution like this in your middleware,

if (Str::lower($request->segment(1) == "version2") {
    config()->set('database.default', 'mysql_us');
} else {
    // your another config.
}

i hope this will help you with your issue.


问:
change the html of div tag using jquery ajax in codeigniter
hi i am new at codeigniter.
i want to change my div tag using jquery ajax.</p>

答:
As per your comment your current code seems to be like this -

```<code>function submitVote(frmName){
  $.ajax({
   type: "POST",
   url: "<?php echo SITEURL; ?>/community/community/add_vote/?",
   data: "vote="+the_value+"&poll="+poll,
   success: function(msg){
    alert(msg);
   }
 });
}
</code>```

First thing i would like to add is from where are you getting the the_value and poll valuesenter code here ? Because you have mentioned nowhere regarding this in your code.
secondly there is no need to send ? in your url. Also the parameter frmName which you are taking in function is used nowhere.

Your code can be modified to work properly as follows -

```<code>function submitVote(frmName){
      $.ajax({
       type: "POST",
       dataType: 'text',
       url: "<?php echo SITEURL; ?>/community/community/add_vote/",
       data: "vote="+the_value+"&poll="+poll,
       success: function(msg){
        //i am assuming that from controller in msg you are sending the total number of votes to that particular entity after ending current vote.
        $('#div id where you have displayed your current vote count').html(msg);
       }
     });
    }
</code>```

Body:
As per your comment your current code seems to be like this -

function submitVote(frmName){
  $.ajax({
   type: "POST",
   url: "<?php echo SITEURL; ?>/community/community/add_vote/?",
   data: "vote="+the_value+"&poll="+poll,
   success: function(msg){
    alert(msg);
   }
 });
}

First thing i would like to add is from where are you getting the the_value and poll valuesenter code here ? Because you have mentioned nowhere regarding this in your code.
secondly there is no need to send ? in your url. Also the parameter frmName which you are taking in function is used nowhere.

Your code can be modified to work properly as follows -

function submitVote(frmName){
      $.ajax({
       type: "POST",
       dataType: 'text',
       url: "<?php echo SITEURL; ?>/community/community/add_vote/",
       data: "vote="+the_value+"&poll="+poll,
       success: function(msg){
        //i am assuming that from controller in msg you are sending the total number of votes to that particular entity after ending current vote.
        $('#div id where you have displayed your current vote count').html(msg);
       }
     });
    }


问:
How to find binary files in a directory?
I need to find the binary files in a directory. I want to do this with file, and after that I will check the results with grep. But my problem is that I have no idea what is a binary file. What will give the file command for binary files or what should I check with grep?</p>

答:
This finds all non-text based, binary, and empty files.

Edit

Solution with only grep (from Mehrdad's comment):

```<code>grep -rIL .
</code>```

Original answer

This does not require any other tool except find and grep:

```<code>find . -type f -exec grep -IL . "{}" \;
</code>```

-I tells grep to assume binary files as unmatched

-L prints only unmatched files

. matches anything else

Edit 2

This finds all non-empty binary files:

```<code>find . -type f ! -size 0 -exec grep -IL . "{}" \;
</code>```

Body:
This finds all non-text based, binary, and empty files.

Edit

Solution with only grep (from Mehrdad's comment):

grep -rIL .

Original answer

This does not require any other tool except find and grep:

find . -type f -exec grep -IL . "{}" \;

-I tells grep to assume binary files as unmatched

-L prints only unmatched files

. matches anything else

Edit 2

This finds all non-empty binary files:

find . -type f ! -size 0 -exec grep -IL . "{}" \;