问:
Binding to static class/field
I have something of an odd error I am trying to rid myself of. I created a custom .cur Cursor for one of my applications. I have loaded the custom cursor into the project in an image folder, set it to my resources, and made a static class for to open the media stream to for it and pass the cursor to the windows. From there in my XAML I have the following code:

```<code><Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:myCtrls="clr-namespace:UserControlsLibrary;assembly=UserControlsLibrary"
        xmlns:pos="clr-namespace:POSystem"
        x:Name="Main" x:Class="POSystem.MainWindow"
        Title="Purchase Order"
        Cursor="{Binding Source={x:Static pos:POProperties.LTC_Cursor}, Mode=OneWay}"
        Height="850" Width="1100" Background="{StaticResource BackgroundImage}"
        Icon="Images/logo_only_Xns_icon.ico">
    <Grid x:Name="TheGrid" Focusable="True"
        MouseDown="ClearFocus_OnClick" Background="Transparent">
        <StackPanel x:Name="Panelicus">
        </StackPanel>
    </Grid>
</Window>
</code>```

I found this method of binding to static classes here and it technically works. The problem is that even though i have built the project and even run the code successfully it shows an invalid markup error with the description:

The name "POProperties" does not exist in the namespace
  "clr-namespace:POSystem"

This error, however, is incorrect but it is causing me to be unable to use the XAML designer in Visual Studio.

The POProperties code:

```<code>namespace POSystem
{
  public static class POProperties
  {
    private static Cursor _ltc_cursor;
    public static Cursor LTC_Cursor
    {
      get => _ltc_cursor ?? new Cursor(new System.IO.MemoryStream(Properties.Resources.LTC_Custom_Cursor));
      set => _ltc_cursor = value;
    }
  }
}
</code>```

答:
I got impatient with trying to use the static property method so I just made a static instantiation of the POProperties inside a now non-static class with no static items outside the instantiation. Code as follows:

Window:

```<code><Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:myCtrls="clr-namespace:UserControlsLibrary;assembly=UserControlsLibrary"
        x:Name="Main" x:Class="POSystem.MainWindow" Title="Purchase Order" Cursor="{Binding LTC_Cursor, Mode=OneWay}"
        Height="850" Width="1100" Background="{StaticResource BackgroundImage}" Icon="Images/logo_only_Xns_icon.ico">
    <Grid x:Name="TheGrid" Focusable="True" MouseDown="ClearFocus_OnClick" Background="Transparent">
        <StackPanel x:Name="Panelicus">
            <TextBox x:Name="PONumLabel" Style="{StaticResource TBLabelStyle}" Width="250" Text="PO Number:"/>
            <myCtrls:DDTextBox x:Name="ItemsBox" Width="300" VerticalAlignment="Top" HorizontalAlignment="Left" MinHeight="25" Panel.ZIndex="1"/>
        </StackPanel>
    </Grid>
</Window>
</code>```

Code Behind on Window:

```<code>namespace POSystem
{
  public partial class MainWindow : Window, INotifyPropertyChanged
  {
    private DataContext _data = new DataContext();
    internal DataContext Data { get => _data ?? new DataContext(); set => _data = value; }

    public MainWindow()
    {
      InitializeComponent();
      DataContext = POProperties.Instance;
    }

    public void ClearFocus_OnClick(object sender, MouseButtonEventArgs e) { Keyboard.ClearFocus(); }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string Name = "")
    { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Name)); }
  }
}
</code>```

POProperties Code:

```<code>namespace POSystem
{
  public class POProperties : INotifyPropertyChanged
  {
    public POProperties() { }

    private static readonly POProperties instance = new POProperties();
    public static POProperties Instance { get => instance; }

    private UserInformation uinfo = new UserInformation();
    public UserInformation GetUserInformation { get => uinfo; }

    private Cursor _ltc_cursor;
    public Cursor LTC_Cursor
    {
      get => _ltc_cursor ?? new Cursor(new MemoryStream(Properties.Resources.LTC_Custom_Cursor));
      set => _ltc_cursor = value;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string Name = "")
    { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Name)); }
}
</code>```

This method I no longer get any errors from the binding and it works well. I knew about this method prier to the question but i figured the static class method would be better. I was wrong apparently.

Title: Binding to static class/field

Body:
I have something of an odd error I am trying to rid myself of. I created a custom .cur Cursor for one of my applications. I have loaded the custom cursor into the project in an image folder, set it to my resources, and made a static class for to open the media stream to for it and pass the cursor to the windows. From there in my XAML I have the following code:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:myCtrls="clr-namespace:UserControlsLibrary;assembly=UserControlsLibrary"
        xmlns:pos="clr-namespace:POSystem"
        x:Name="Main" x:Class="POSystem.MainWindow"
        Title="Purchase Order"
        Cursor="{Binding Source={x:Static pos:POProperties.LTC_Cursor}, Mode=OneWay}"
        Height="850" Width="1100" Background="{StaticResource BackgroundImage}"
        Icon="Images/logo_only_Xns_icon.ico">
    <Grid x:Name="TheGrid" Focusable="True"
        MouseDown="ClearFocus_OnClick" Background="Transparent">
        <StackPanel x:Name="Panelicus">
        </StackPanel>
    </Grid>
</Window>

I found this method of binding to static classes here and it technically works. The problem is that even though i have built the project and even run the code successfully it shows an invalid markup error with the description:

The name "POProperties" does not exist in the namespace
  "clr-namespace:POSystem"

This error, however, is incorrect but it is causing me to be unable to use the XAML designer in Visual Studio.

The POProperties code:

namespace POSystem
{
  public static class POProperties
  {
    private static Cursor _ltc_cursor;
    public static Cursor LTC_Cursor
    {
      get => _ltc_cursor ?? new Cursor(new System.IO.MemoryStream(Properties.Resources.LTC_Custom_Cursor));
      set => _ltc_cursor = value;
    }
  }
}

Body:
I got impatient with trying to use the static property method so I just made a static instantiation of the POProperties inside a now non-static class with no static items outside the instantiation. Code as follows:

Window:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:myCtrls="clr-namespace:UserControlsLibrary;assembly=UserControlsLibrary"
        x:Name="Main" x:Class="POSystem.MainWindow" Title="Purchase Order" Cursor="{Binding LTC_Cursor, Mode=OneWay}"
        Height="850" Width="1100" Background="{StaticResource BackgroundImage}" Icon="Images/logo_only_Xns_icon.ico">
    <Grid x:Name="TheGrid" Focusable="True" MouseDown="ClearFocus_OnClick" Background="Transparent">
        <StackPanel x:Name="Panelicus">
            <TextBox x:Name="PONumLabel" Style="{StaticResource TBLabelStyle}" Width="250" Text="PO Number:"/>
            <myCtrls:DDTextBox x:Name="ItemsBox" Width="300" VerticalAlignment="Top" HorizontalAlignment="Left" MinHeight="25" Panel.ZIndex="1"/>
        </StackPanel>
    </Grid>
</Window>

Code Behind on Window:

namespace POSystem
{
  public partial class MainWindow : Window, INotifyPropertyChanged
  {
    private DataContext _data = new DataContext();
    internal DataContext Data { get => _data ?? new DataContext(); set => _data = value; }

    public MainWindow()
    {
      InitializeComponent();
      DataContext = POProperties.Instance;
    }

    public void ClearFocus_OnClick(object sender, MouseButtonEventArgs e) { Keyboard.ClearFocus(); }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string Name = "")
    { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Name)); }
  }
}

POProperties Code:

namespace POSystem
{
  public class POProperties : INotifyPropertyChanged
  {
    public POProperties() { }

    private static readonly POProperties instance = new POProperties();
    public static POProperties Instance { get => instance; }

    private UserInformation uinfo = new UserInformation();
    public UserInformation GetUserInformation { get => uinfo; }

    private Cursor _ltc_cursor;
    public Cursor LTC_Cursor
    {
      get => _ltc_cursor ?? new Cursor(new MemoryStream(Properties.Resources.LTC_Custom_Cursor));
      set => _ltc_cursor = value;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string Name = "")
    { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Name)); }
}

This method I no longer get any errors from the binding and it works well. I knew about this method prier to the question but i figured the static class method would be better. I was wrong apparently.


来源: stackexchange

问:
ASP.net Web forms - Page Routing Naming Conflict
I'm rebuilding an old project from asp 4.0 to a 4.52 (moving to bootstrap).
This is a Web Forms website not MVC.
My original version was made with VS2012 and now it's with VS 2015 which chagned a bit for example adding by default the RouteConfig class.

In V4.0 my url formation used to be as follows:

domain.com/nike-shoes

domain.com/nike-shoes/nike-air-pegasus-21-1001

In my new site it does not work because of the "/nike-shoes" duplicity.

Calling "domain.com/nike-shoes/nike-air-pegasus-21" will simply call "domain.com/nike-shoes"

Here is the "new" code:

```<code>Sub Application_Start(sender As Object, e As EventArgs)
    RouteConfig.RegisterRoutes(RouteTable.Routes)
    BundleConfig.RegisterBundles(BundleTable.Bundles)
    RegisterRoutes(RouteTable.Routes)
End Sub

Sub RegisterRoutes(ByVal routes As RouteCollection)
    routes.MapPageRoute("Nike-Shoes", "nike-shoes", "~/nike-shoes.aspx")
    routes.MapPageRoute("Nike-Shoe", "nike-shoes/{shoe-id}", "~/display-shoe.aspx")
End Sub
</code>```

The old code RegisterRoutes Sub was the same but the Application_Start was different (there was no RouteConfig):`

```<code>Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        RegisterRoutes(RouteTable.Routes)
    End Sub
</code>```

Previous version also needed re-routing from /page.aspx to /page which now is by default. Since I do not want to do redirects keeping current url formation is extremely important.

THANKS a lot!

答:
Problem solved -

Changed:

```<code>RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
RegisterRoutes(RouteTable.Routes)
</code>```

To:

```<code> RegisterRoutes(RouteTable.Routes)
    RouteConfig.RegisterRoutes(RouteTable.Routes)
    BundleConfig.RegisterBundles(BundleTable.Bundles)
</code>```

Thanks

ContentLicense: CC BY-SA 3.0

Body:
I'm rebuilding an old project from asp 4.0 to a 4.52 (moving to bootstrap).
This is a Web Forms website not MVC.
My original version was made with VS2012 and now it's with VS 2015 which chagned a bit for example adding by default the RouteConfig class.

In V4.0 my url formation used to be as follows:

domain.com/nike-shoes

domain.com/nike-shoes/nike-air-pegasus-21-1001

In my new site it does not work because of the "/nike-shoes" duplicity.

Calling "domain.com/nike-shoes/nike-air-pegasus-21" will simply call "domain.com/nike-shoes"

Here is the "new" code:

Sub Application_Start(sender As Object, e As EventArgs)
    RouteConfig.RegisterRoutes(RouteTable.Routes)
    BundleConfig.RegisterBundles(BundleTable.Bundles)
    RegisterRoutes(RouteTable.Routes)
End Sub

Sub RegisterRoutes(ByVal routes As RouteCollection)
    routes.MapPageRoute("Nike-Shoes", "nike-shoes", "~/nike-shoes.aspx")
    routes.MapPageRoute("Nike-Shoe", "nike-shoes/{shoe-id}", "~/display-shoe.aspx")
End Sub

The old code RegisterRoutes Sub was the same but the Application_Start was different (there was no RouteConfig):`

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        RegisterRoutes(RouteTable.Routes)
    End Sub

Previous version also needed re-routing from /page.aspx to /page which now is by default. Since I do not want to do redirects keeping current url formation is extremely important.

THANKS a lot!

Body:
Problem solved -

Changed:

RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
RegisterRoutes(RouteTable.Routes)

To:

 RegisterRoutes(RouteTable.Routes)
    RouteConfig.RegisterRoutes(RouteTable.Routes)
    BundleConfig.RegisterBundles(BundleTable.Bundles)

Thanks


问:
How to connect two activities to make a program?
I am a beginner in java.
I want to make sure to link my second main activity on my first activity.
I try to put a line of code in my first activity but that does not connect anything at all.
I put the line of code:

```<code>Intent intent = new Intent(this, DeuxiemeActivity.class);
            startActivity(intent);
            finish();
</code>```

Thanks,

答:
Inside AndroidManifest.xml,

Change

```<code><activity android:name=".MainActivity">
</code>```

to this,

```<code><activity android:name=".MainActivity" android:noHistory="true">
</code>```

noHistory="true" and finish() both are similar.

But, When we start a new activity, It will be closed at the same time. So using noHistory="true" is better than using finish();.

Body:
I am a beginner in java.
I want to make sure to link my second main activity on my first activity.
I try to put a line of code in my first activity but that does not connect anything at all.
I put the line of code:

Intent intent = new Intent(this, DeuxiemeActivity.class);
            startActivity(intent);
            finish();

Thanks,

Body:
Inside AndroidManifest.xml,

Change

<activity android:name=".MainActivity">

to this,

<activity android:name=".MainActivity" android:noHistory="true">

noHistory="true" and finish() both are similar.

But, When we start a new activity, It will be closed at the same time. So using noHistory="true" is better than using finish();.


问:
XPath aware XML templates or content assist
I want to create a custom XML editor that can offer templates or content assists based on the current XPath.
Creating templates using the extension point org.eclipse.ui.editors.templates makes it available to the entire context type, which is a bit too simple.

When googling I get links to oXygen who can handle this, i.e:

...XPath aware content assistant showing functions and axes (all documented with sections from the W3C specification), variables and parameters as well as name tests for elements and attributes in context.

I am guessing i'll need to use the WTP XML editor?

答:
Need to use the WTP XML?  Editor?  I don't understand what you mean, given the option you've researched.  <oXygen/> is fully-functioned XML editor, either standalone or as an Eclipse plugin; it costs a bit of money ($300+) per license, but if you can afford it, go ahead and use it.  It's got the XPath support you're looking for.

I've used it before and was very happy with it.

ContentLicense: CC BY-SA 2.5


问:
How to append string in java script with pre increment in same line
In JavaScript, I have 1 variable contains int value and one having String. Now I want to append the string like pre-increment the int variable like below code I am getting error

```<code>var count = 0;
var message = "value of Variable Count by increment  is:"+ ++count;
</code>```

答:
Wrap your counter with brackets like (++count)

```<code>var count = 0;
var message = "value of Variable Count by increment  is:" + (++count);
console.log(message);
</code>```

var count = 0;
var message = "value of Variable Count by increment  is:"+ (++count);
console.log(message);
console.log("value of Variable Count by increment  is:"+ (++count));```

Body:
In JavaScript, I have 1 variable contains int value and one having String. Now I want to append the string like pre-increment the int variable like below code I am getting error

var count = 0;
var message = "value of Variable Count by increment  is:"+ ++count;

Body:
Wrap your counter with brackets like (++count)

var count = 0;
var message = "value of Variable Count by increment  is:" + (++count);
console.log(message);

var count = 0;
var message = "value of Variable Count by increment  is:"+ (++count);
console.log(message);
console.log("value of Variable Count by increment  is:"+ (++count));


问:
Maven: Invalid content was found starting with element "reportSets"
This is the javadoc plugin in pom.xml:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>2.10.4</version>
    <reportSets>
        <reportSet>
            <id>PDF</id>
            <reports>
                <report>javadoc</report>
            </reports>
            <configuration>
                <name>PDF</name>
                <description>MovieList documentation</description>
                <destDir>pdf</destDir>
                <doclet>com.tarsec.javadoc.pdfdoclet.PDFDoclet</doclet>
                <docletPath>lib\pdfdoclet-1.0.3-all.jar</docletPath>
                <useStandardDocletOptions>false</useStandardDocletOptions>
                <additionalparam>
                    -pdf javadoc.pdf
                </additionalparam>
            </configuration>
        </reportSet>
    </reportSets>
</plugin>
</code>```

And it has an error on <reportSets>.

It says Invalid content was found starting with element 'reportSets'.

I'm trying to use this with the PDFDoclet jar but I can't manage to get it working. What am I doing wrong?

答:
I am not sure, but probably you did not put your plugin in proper element.
This should be in <reporting> element. It should look like:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<project ...>
...
    <reporting>
    ...
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.4</version>
                <reportSets>
                    <reportSet>
                        <id>PDF</id>
                        <reports>
                            <report>javadoc</report>
                        </reports>
                        <configuration>
                            <name>PDF</name>
                            <description>MovieList documentation</description>
                            <destDir>pdf</destDir>
                            <doclet>com.tarsec.javadoc.pdfdoclet.PDFDoclet</doclet>
                            <docletPath>lib\pdfdoclet-1.0.3-all.jar</docletPath>
                            <useStandardDocletOptions>false</useStandardDocletOptions>
                            <additionalparam>
                                -pdf javadoc.pdf
                            </additionalparam>
                        </configuration>
                    </reportSet>
                </reportSets>
            </plugin>
        </plugins>
    ...
    </reporting>
 ...
</project>
</code>```

If you put this section in e.g.  section you got exactly error message like you have got - Invalid content was found starting with element 'reportSets'

Body:
This is the javadoc plugin in pom.xml:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>2.10.4</version>
    <reportSets>
        <reportSet>
            <id>PDF</id>
            <reports>
                <report>javadoc</report>
            </reports>
            <configuration>
                <name>PDF</name>
                <description>MovieList documentation</description>
                <destDir>pdf</destDir>
                <doclet>com.tarsec.javadoc.pdfdoclet.PDFDoclet</doclet>
                <docletPath>lib\pdfdoclet-1.0.3-all.jar</docletPath>
                <useStandardDocletOptions>false</useStandardDocletOptions>
                <additionalparam>
                    -pdf javadoc.pdf
                </additionalparam>
            </configuration>
        </reportSet>
    </reportSets>
</plugin>

And it has an error on <reportSets>.

It says Invalid content was found starting with element 'reportSets'.

I'm trying to use this with the PDFDoclet jar but I can't manage to get it working. What am I doing wrong?

Body:
I am not sure, but probably you did not put your plugin in proper element.
This should be in <reporting> element. It should look like:

<?xml version="1.0" encoding="ISO-8859-1"?>
<project ...>
...
    <reporting>
    ...
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.4</version>
                <reportSets>
                    <reportSet>
                        <id>PDF</id>
                        <reports>
                            <report>javadoc</report>
                        </reports>
                        <configuration>
                            <name>PDF</name>
                            <description>MovieList documentation</description>
                            <destDir>pdf</destDir>
                            <doclet>com.tarsec.javadoc.pdfdoclet.PDFDoclet</doclet>
                            <docletPath>lib\pdfdoclet-1.0.3-all.jar</docletPath>
                            <useStandardDocletOptions>false</useStandardDocletOptions>
                            <additionalparam>
                                -pdf javadoc.pdf
                            </additionalparam>
                        </configuration>
                    </reportSet>
                </reportSets>
            </plugin>
        </plugins>
    ...
    </reporting>
 ...
</project>

If you put this section in e.g.  section you got exactly error message like you have got - Invalid content was found starting with element 'reportSets'


问:
Nativebase Only one default export allowed per module
I have a react js app and i need to make 2 exports. The first is

```<code>export  default reduxForm({
  form: 'simple'  // a unique identifier for this form
})(SimpleForm)
</code>```

to handle form submission and the next is to bind some ui actions

```<code>export default connect(mapStateToProps, bindAction)(Inbox);
</code>```

When i have the two exports, i get the error that i cant have 2 exports in one module. Can the problem be solved by combining the two exports?.

答:
You can have more than one exports. When you want to export only single function/class/const etc, you should use default export. For multiple exports use exports only.

```<code>export reduxForm()
export connect()
</code>```

of course, you have to add codes with them :p
and just import { reduxForm, connect } from 'path'

Body:
I have a react js app and i need to make 2 exports. The first is

export  default reduxForm({
  form: 'simple'  // a unique identifier for this form
})(SimpleForm)

to handle form submission and the next is to bind some ui actions

export default connect(mapStateToProps, bindAction)(Inbox);

When i have the two exports, i get the error that i cant have 2 exports in one module. Can the problem be solved by combining the two exports?.

Body:
You can have more than one exports. When you want to export only single function/class/const etc, you should use default export. For multiple exports use exports only.

export reduxForm()
export connect()

of course, you have to add codes with them :p
and just import { reduxForm, connect } from 'path'


问:
C++ Convert Large Number into Hexadecimal
I got a large number of this value

```<code>DECIMAL: 3712299789313814843
</code>```

I want to convert it into hexadecimal using C++

I did an online conversion and I realized the

```<code>hexadecimal value is     3384BCFD61CEB13B
</code>```

I found some solution online and I try convert but it give me this:

```<code>string hex_value(int decimal)
{
  static const string hex_digits("0123456789ABCDEF");

  string hex;
  int scratch = decimal;

  while (scratch != 0)
  {
    hex += hex_digits[scratch % 16];
    scratch /= 16;
  }

  reverse(hex.begin(), hex.end());

  return hex;
}

input= hex_value(atoi(buffer.c_str()));

HEXA: 61CEB13B
</code>```

I think integer is too small to send in the data.. i do use NTL, namely ZZ class but i not sure how to use it in this case..

anyone can guide me on how to convert this large number into hexadecimal..

Thanks!!

答:
I suggest using the library gmp to represent big numbers: it is very intuitive and quite simple. It is mostly for C but there are some extensions for C++ that make things easier.

After representing your big number with such a library, then you can apply the steps to convert to hex:

Suppose N is your number:

initialise an empty string res

Calculate N modulo 16 (the reminder of the division)

Represent the value you obtained in hex into a string: ex. 10 becomes "a"

append the result to res

N = N/16 (integer division)

Repeat from the second steps until N becomes 0 -

I will give the following example:

```<code>    #include <gmp.h> //contains all the functions and types
    #include <gmpxx.h> //contains some classes for C++
    string toFormatFromDecimal(mpz_class t);

    int main()
    {
        mpz_class N = "3712299789313814843"; //string initialisation
        std::cout<<toFormatDecimal(N);
        return 0;
    }

    string toFormatFromDecimal(mpz_class t)//mpz_class is the C++ equivalent of mpz_t
    {
        static const char hexmap[] = {'0', '1', '2', '3', '4', '5', '6', '7',
                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        string res = "";
        mpz_t temp; //C variable to store a big number
        mpz_init_set_ui(temp, 0); //initialisation
        unsigned int pos;
         do {
             pos = mpz_mod_ui(temp, t.get_mpz_t(), 16); //calculate the reminder: t%16
             res = res+hexmap[pos] ;
             t = t/16;

        } while ((mpz_cmp_ui(t.get_mpz_t(), 0) != 0));

        return string(res.rbegin(), res.rend());
    }
</code>```

Body:
I got a large number of this value

DECIMAL: 3712299789313814843

I want to convert it into hexadecimal using C++

I did an online conversion and I realized the

hexadecimal value is     3384BCFD61CEB13B

I found some solution online and I try convert but it give me this:

string hex_value(int decimal)
{
  static const string hex_digits("0123456789ABCDEF");

  string hex;
  int scratch = decimal;

  while (scratch != 0)
  {
    hex += hex_digits[scratch % 16];
    scratch /= 16;
  }

  reverse(hex.begin(), hex.end());

  return hex;
}

input= hex_value(atoi(buffer.c_str()));

HEXA: 61CEB13B

I think integer is too small to send in the data.. i do use NTL, namely ZZ class but i not sure how to use it in this case..

anyone can guide me on how to convert this large number into hexadecimal..

Thanks!!

Body:
I suggest using the library gmp to represent big numbers: it is very intuitive and quite simple. It is mostly for C but there are some extensions for C++ that make things easier.

After representing your big number with such a library, then you can apply the steps to convert to hex:

Suppose N is your number:

initialise an empty string res

Calculate N modulo 16 (the reminder of the division)

Represent the value you obtained in hex into a string: ex. 10 becomes "a"

append the result to res

N = N/16 (integer division)

Repeat from the second steps until N becomes 0 -

I will give the following example:

    #include <gmp.h> //contains all the functions and types
    #include <gmpxx.h> //contains some classes for C++
    string toFormatFromDecimal(mpz_class t);

    int main()
    {
        mpz_class N = "3712299789313814843"; //string initialisation
        std::cout<<toFormatDecimal(N);
        return 0;
    }

    string toFormatFromDecimal(mpz_class t)//mpz_class is the C++ equivalent of mpz_t
    {
        static const char hexmap[] = {'0', '1', '2', '3', '4', '5', '6', '7',
                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        string res = "";
        mpz_t temp; //C variable to store a big number
        mpz_init_set_ui(temp, 0); //initialisation
        unsigned int pos;
         do {
             pos = mpz_mod_ui(temp, t.get_mpz_t(), 16); //calculate the reminder: t%16
             res = res+hexmap[pos] ;
             t = t/16;

        } while ((mpz_cmp_ui(t.get_mpz_t(), 0) != 0));

        return string(res.rbegin(), res.rend());
    }


问:
how to make responsive hexagon with 6 and 8 triangles
I found a code on codepen like this and here is the link : https://codepen.io/FStop/pen/uvenj

how to make this with 6 and 8 triangles?

```<code><div class="hexagon">
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
</div>
</code>```

you can see css code on codepen link...I couldnt paste here...its very hard to ask something here

答:
Did you mean how to make eight triangles out of these six?
In case you mean that just add two more div elements with the class "triangle" and play around with the numbers. The rotation has to be 45deg because you have eight triangles now (360:8) and the width must fit with the numbers of triangles you have now.
After playing around a little I got following solution:

HTML:

```<code><div class="hexagon">
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
</div>
</code>```

CSS:

```<code>body{
  padding: 25px;
}

@mixin hexagon($width: 100px, $color: #19c, $dir: down){
  // Math for calculating the height of equilateral triangle
  // Rounding this up helps a little with sub pixel rendering BS
  $height: ceil($width*(sqrt(3))/2);
  height: $height;
  width: $width;
  position: relative;
  // might as well center the thing
  margin: 0 auto;
  transform-origin: 0 0;
  transform: translateX($width/2) rotate(30deg);
  .triangle{
    position: absolute;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: $height/3 $width/8.5 0;
    border-color: #19c transparent;
    transform-origin: $width/8.5 $height/3 + 2;
    // Sass function to auto generate rotation
    $deg: 45deg;
    @for $i from 1 through 7{
      &:nth-child(#{$i}){
        transform: rotate(#{$deg});
      }
      $deg: $deg + 45;
    }
    &:nth-child(5), &:nth-child(6){
      border-color: lighten(#19c,25%) transparent;
    }
    &:nth-child(2), &:nth-child(3){
      border-color: darken(#19c,10%) transparent;
    }
  }
}

.hexagon{
  @include hexagon(300px);
}
</code>```

codePen Example

Body:
I found a code on codepen like this and here is the link : https://codepen.io/FStop/pen/uvenj

how to make this with 6 and 8 triangles?

you can see css code on codepen link...I couldnt paste here...its very hard to ask something here

Body:
Did you mean how to make eight triangles out of these six?
In case you mean that just add two more div elements with the class "triangle" and play around with the numbers. The rotation has to be 45deg because you have eight triangles now (360:8) and the width must fit with the numbers of triangles you have now.
After playing around a little I got following solution:

HTML:

<div class="hexagon">
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
  <div class="triangle"></div>
</div>

CSS:

body{
  padding: 25px;
}

@mixin hexagon($width: 100px, $color: #19c, $dir: down){
  // Math for calculating the height of equilateral triangle
  // Rounding this up helps a little with sub pixel rendering BS
  $height: ceil($width*(sqrt(3))/2);
  height: $height;
  width: $width;
  position: relative;
  // might as well center the thing
  margin: 0 auto;
  transform-origin: 0 0;
  transform: translateX($width/2) rotate(30deg);
  .triangle{
    position: absolute;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: $height/3 $width/8.5 0;
    border-color: #19c transparent;
    transform-origin: $width/8.5 $height/3 + 2;
    // Sass function to auto generate rotation
    $deg: 45deg;
    @for $i from 1 through 7{
      &:nth-child(#{$i}){
        transform: rotate(#{$deg});
      }
      $deg: $deg + 45;
    }
    &:nth-child(5), &:nth-child(6){
      border-color: lighten(#19c,25%) transparent;
    }
    &:nth-child(2), &:nth-child(3){
      border-color: darken(#19c,10%) transparent;
    }
  }
}

.hexagon{
  @include hexagon(300px);
}

codePen Example


问:
Gulp watch path excluding directory
I have a Gulp watch task pointing at my SCSS files like so:

```<code>gulp.task('watch', () => {
  watch('assets/scss/**/*.scss', () => {
    gulp.start('css-development');
  });
});
</code>```

My text editor Coda saves to a temporary buffer file such as (A Document Being Saved By Coda)/styles.scss. My watch task sees that file and tries to execute, so I need to get it to ignore any instance of that folder. What should my new watch path look like?

I image it would be something like this, although this is obviously wrong.

```<code>watch('assets/scss/**{!(A Document Being Saved By Coda)}/*.scss'
</code>```

答:
If I understood that question right you want to ignore a specific file? If so this should work, just like in gulp.src:

```<code>gulp.watch('assets/scss/*.scss', ['!assets/scss/YourFile.scss']);
</code>```

A quick response if it worked would be good, same if it not worked so we can figure out a better solution.

Title: Gulp watch path excluding directory

Body:
I have a Gulp watch task pointing at my SCSS files like so:

gulp.task('watch', () => {
  watch('assets/scss/**/*.scss', () => {
    gulp.start('css-development');
  });
});

My text editor Coda saves to a temporary buffer file such as (A Document Being Saved By Coda)/styles.scss. My watch task sees that file and tries to execute, so I need to get it to ignore any instance of that folder. What should my new watch path look like?

I image it would be something like this, although this is obviously wrong.

watch('assets/scss/**{!(A Document Being Saved By Coda)}/*.scss'

Body:
If I understood that question right you want to ignore a specific file? If so this should work, just like in gulp.src:

gulp.watch('assets/scss/*.scss', ['!assets/scss/YourFile.scss']);

A quick response if it worked would be good, same if it not worked so we can figure out a better solution.


问:
ASyncTask load GridView thumbnails loads latest file twice, then slowly loads from the top of the list
I'm using an ASyncTask to load my thumbnails in a GridView layout that I have, but when I refresh the data, the thumbnails load in an odd order. It always loads the last element first, but it renders it with the first elements thumbnail, then re-renders it with the proper thumbnail (the last elements), then it properly loads every other thumbnail from first to second-last. It also reloads the images many times and is fairly slow at loading them (16mp images however)

Here's my GridView adapter (with the ASyncTask).

```<code>public class ReceiptListAdapter extends ArrayAdapter {

    public ReceiptListAdapter(Context context, ArrayList<Receipt> receipts){
        super(context, 0, receipts);
//        getItem(1);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder holder;

        // Lookup view for data population
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.receipt_list_element, parent, false);
            holder = new ViewHolder();
            // Populate the data into the template view using the data object
            holder.title = (TextView) convertView.findViewById(R.id.TitleView);
            holder.date = (TextView) convertView.findViewById(R.id.DateView);
            holder.image = (ImageView) convertView.findViewById(R.id.containerImage);
            holder.spn = (ProgressBar) convertView.findViewById(R.id.spinner);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Receipt receipt = (Receipt) getItem(position);
        holder.imagePath = receipt.getFilepath();
        final int tWidth = receipt.getWidth();

        // manipulate data here...
        holder.spn.setVisibility(View.VISIBLE);
        holder.image.setVisibility(View.GONE);
        holder.title.setText(receipt.getDesc());

        new AsyncTask<ViewHolder, Void, Bitmap>() {

            private ViewHolder h;

            @Override
            protected Bitmap doInBackground(ViewHolder... t) {
                h = t[0];
                Bitmap thumb = ExifUtil.rotateBitmap(h.imagePath, ThumbnailUtils.extractThumbnail(
                        BitmapFactory.decodeFile(h.imagePath),
                        tWidth,
                        tWidth));
                return thumb;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);

                    h.spn.setVisibility(View.GONE);
                    h.image.setVisibility(View.VISIBLE);
                    h.image.setImageBitmap(result);

            }
        }.execute(holder);

        // Return the completed view to render on screen
        return convertView;
    }

    static class ViewHolder {
        private TextView title;
        private TextView date;
        private ImageView image;
        private String imagePath;
        private ProgressBar spn;
    }

}
</code>```

答:
Id go with just using another library, but let me explain where some of the issues are coming. First as per AsyncTask

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

Which meanst that you are loading only 1 thumbnail at a time. Your second issue is because viewHolder is actually reused. You create 2 AsyncTasks for the same view, which are executed in different times (but correct order). This can be fixed by keeping refference to the Task, and stopping it before creating new one.

Body:
I'm using an ASyncTask to load my thumbnails in a GridView layout that I have, but when I refresh the data, the thumbnails load in an odd order. It always loads the last element first, but it renders it with the first elements thumbnail, then re-renders it with the proper thumbnail (the last elements), then it properly loads every other thumbnail from first to second-last. It also reloads the images many times and is fairly slow at loading them (16mp images however)

Here's my GridView adapter (with the ASyncTask).

public class ReceiptListAdapter extends ArrayAdapter {

    public ReceiptListAdapter(Context context, ArrayList<Receipt> receipts){
        super(context, 0, receipts);
//        getItem(1);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder holder;

        // Lookup view for data population
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.receipt_list_element, parent, false);
            holder = new ViewHolder();
            // Populate the data into the template view using the data object
            holder.title = (TextView) convertView.findViewById(R.id.TitleView);
            holder.date = (TextView) convertView.findViewById(R.id.DateView);
            holder.image = (ImageView) convertView.findViewById(R.id.containerImage);
            holder.spn = (ProgressBar) convertView.findViewById(R.id.spinner);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Receipt receipt = (Receipt) getItem(position);
        holder.imagePath = receipt.getFilepath();
        final int tWidth = receipt.getWidth();

        // manipulate data here...
        holder.spn.setVisibility(View.VISIBLE);
        holder.image.setVisibility(View.GONE);
        holder.title.setText(receipt.getDesc());

        new AsyncTask<ViewHolder, Void, Bitmap>() {

            private ViewHolder h;

            @Override
            protected Bitmap doInBackground(ViewHolder... t) {
                h = t[0];
                Bitmap thumb = ExifUtil.rotateBitmap(h.imagePath, ThumbnailUtils.extractThumbnail(
                        BitmapFactory.decodeFile(h.imagePath),
                        tWidth,
                        tWidth));
                return thumb;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);

                    h.spn.setVisibility(View.GONE);
                    h.image.setVisibility(View.VISIBLE);
                    h.image.setImageBitmap(result);

            }
        }.execute(holder);

        // Return the completed view to render on screen
        return convertView;
    }

    static class ViewHolder {
        private TextView title;
        private TextView date;
        private ImageView image;
        private String imagePath;
        private ProgressBar spn;
    }

}


答:
This sounds like an exam question - is it?!

This would be my solution using recursion and Python's list manipulation operators:

```<code>def clockwise(input_list, output_list):
    list_size = len(input_list[0])
    if list_size == 1:
        output_list.append(input_list[0][0])
    else:
        for i in range(list_size):
            output_list.append(input_list[0][i])

        for i in range(list_size)[1:]:
            output_list.append(input_list[i][list_size - 1])

        for i in reversed(range(list_size)[:-1]):
            output_list.append(input_list[list_size - 1][i])

        for i in reversed(range(list_size)[1:-1]):
            output_list.append(input_list[i][0])

        new_list = list()
        for i in range(list_size - 2):
            new_list.append(input_list[i + 1][1:-1])

        return clockwise(new_list, output_list)

l = [[2, 3, 5, 9, 10],[ 8, 7, 1, 11, 13],[ 0, 4, 6, 21, 22], [12, 19, 17, 18, 25], [14, 15, 16, 23, 24]]
output_list = []
clockwise(l, output_list)

print output_list
</code>```

Title: Python: 2D to 1D list in clockwise direction?

Body:
I am a bit newbie to Python and I am looking for a function that will convert any n x n 2D list to a 1D list in clockwise direction.

For example:

When n = 3

list = [[2, 3, 5],[ 8, 7, 1],[ 0, 4, 6]]

or

list = [[2, 3, 5]
       ,[8, 7, 1]
       ,[0, 4, 6]]

would become

result = [2, 3, 5, 1, 6, 4, 0, 8, 7]

and when n = 5

list = [[2, 3, 5, 9, 10],[ 8, 7, 1, 11, 13],[ 0, 4, 6, 21, 22], [12, 19, 17, 18, 25], [14, 15, 16, 23, 24]]

or

list = [[  2,  3,  5,  9, 10]
       ,[  8,  7,  1, 11, 13]
       ,[  0,  4,  6, 21, 22]
       ,[ 12, 19, 17, 18, 25]
      , [ 14, 15, 16, 23, 24]]

would become

result = [2, 3, 5, 9, 10, 13, 22, 25, 24, 23, 16, 15, 14, 12, 0, 8, 7, 1, 11, 21, 18, 17, 19, 4, 6]

How can I efficiently do that for any value of nxn ??

Body:
This sounds like an exam question - is it?!

This would be my solution using recursion and Python's list manipulation operators:

def clockwise(input_list, output_list):
    list_size = len(input_list[0])
    if list_size == 1:
        output_list.append(input_list[0][0])
    else:
        for i in range(list_size):
            output_list.append(input_list[0][i])

        for i in range(list_size)[1:]:
            output_list.append(input_list[i][list_size - 1])

        for i in reversed(range(list_size)[:-1]):
            output_list.append(input_list[list_size - 1][i])

        for i in reversed(range(list_size)[1:-1]):
            output_list.append(input_list[i][0])

        new_list = list()
        for i in range(list_size - 2):
            new_list.append(input_list[i + 1][1:-1])

        return clockwise(new_list, output_list)

l = [[2, 3, 5, 9, 10],[ 8, 7, 1, 11, 13],[ 0, 4, 6, 21, 22], [12, 19, 17, 18, 25], [14, 15, 16, 23, 24]]
output_list = []
clockwise(l, output_list)

print output_list


问:
How to call object from one class to another in C#
I have a problem that I just can't solve on my own. I am new to programming and I would appreciate if you could help me with this issue:

I have a class I would like to inherit from:

```<code>namespace rsDeployer.Common.SQLServerCommunication
{
    public class RSDatabaseConnectionCreator: LoggerBase
    {
        public RSProfile profile;
        public RSDatabaseConnectionCreator(RSProfile profile)
        {
            this.profile = profile;
        }

        public SqlConnection CreateConnection(RSDatabaseNames DatabaseName, bool UseWindowsAuthentication, bool testConnection = false)
        {
            var connectionString = BuildRSDatabaseConnectionString(DatabaseName, UseWindowsAuthentication);
            if (testConnection)
            {
                return IsConnectionAvailable(connectionString) ? new SqlConnection(connectionString) : null;
            }
            return new SqlConnection(connectionString);
        }
    }
}
</code>```

and I would like to call CreateConnection() in another class to inject to methods to allow me to open connection and then execute scripts.

Edit 1 - class I would like to have it injected to.

```<code>        public void QueryExecution(string SQLQuery)
    {

        //here's where I would like to inject it
        SqlCommand command = new SqlCommand(SQLQuery, conn);
        var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
        file.WriteLine(command);
        file.Close();
    }
</code>```

If this question is way to silly to deserve answer would you just point in the direction where I should read about it?

I hope this question is well asked and clear.
Thanks in advance.

答:
Hope this is what you are requesting for    </p>

```<code>public class ClassX
{
    private RSProfile _rsprofile;
    RSDatabaseConnectionCreator _dbConnectionCreator;
    private SqlConnection _sqlConnection;

        public ClassX()
        {
           _rsProfile = xxx; //  Get the RSProfile object
           _dbConnectionCreator = new RSDatabaseConnectionCreator (_rsProfile);
           RSDatabaseNames databaseName = yyy; //  get the RSDatabaseNames
           var useWindowsAuthentication = true;
           var testConnection = false;

          _sqlConnection = _dbConnectionCreator.CreateConnection(databaseName,useWindowsAuthentication ,testConnection );
        }

}
</code>```

Body:
I have a problem that I just can't solve on my own. I am new to programming and I would appreciate if you could help me with this issue:

I have a class I would like to inherit from:

namespace rsDeployer.Common.SQLServerCommunication
{
    public class RSDatabaseConnectionCreator: LoggerBase
    {
        public RSProfile profile;
        public RSDatabaseConnectionCreator(RSProfile profile)
        {
            this.profile = profile;
        }

        public SqlConnection CreateConnection(RSDatabaseNames DatabaseName, bool UseWindowsAuthentication, bool testConnection = false)
        {
            var connectionString = BuildRSDatabaseConnectionString(DatabaseName, UseWindowsAuthentication);
            if (testConnection)
            {
                return IsConnectionAvailable(connectionString) ? new SqlConnection(connectionString) : null;
            }
            return new SqlConnection(connectionString);
        }
    }
}

and I would like to call CreateConnection() in another class to inject to methods to allow me to open connection and then execute scripts.

Edit 1 - class I would like to have it injected to.

        public void QueryExecution(string SQLQuery)
    {

        //here's where I would like to inject it
        SqlCommand command = new SqlCommand(SQLQuery, conn);
        var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
        file.WriteLine(command);
        file.Close();
    }

If this question is way to silly to deserve answer would you just point in the direction where I should read about it?

I hope this question is well asked and clear.
Thanks in advance.

Body:
Hope this is what you are requesting for

public class ClassX
{
    private RSProfile _rsprofile;
    RSDatabaseConnectionCreator _dbConnectionCreator;
    private SqlConnection _sqlConnection;

        public ClassX()
        {
           _rsProfile = xxx; //  Get the RSProfile object
           _dbConnectionCreator = new RSDatabaseConnectionCreator (_rsProfile);
           RSDatabaseNames databaseName = yyy; //  get the RSDatabaseNames
           var useWindowsAuthentication = true;
           var testConnection = false;

          _sqlConnection = _dbConnectionCreator.CreateConnection(databaseName,useWindowsAuthentication ,testConnection );
        }

}


答:
That regex is not legal in sed; since it uses Perl syntax, my recommendation would be to use perl instead. The regular expression works exactly as-is, and even the command line is almost the same; you just need to add the -p option to get perl to operate in filter mode (which sed does by default). I would also recommend adding an argument suffix to the -i option (whether using sed or perl), so that you have a backup of the original file in case something goes horribly wrong. As for quoting, all you need to do is put the substitution command in single quotation marks:

```<code>perl -p -i.bak -e \
's/((?:\[)[0-9]{2})([0-9]+)(\.)([0-9]+)(,)([0-9]{2})([0-9]+)(\.)([0-9]+(?:\]))/$1\.$2$4,$6.$7$9/g' \
large_file.geojson
</code>```

Title: sed regexp, number reformatting: how to escape for bash

Body:
I have a working (in macOS app Patterns) RegExp that reformats GeoJSON MultiPolygon coordinates, but don't know how to escape it for sed.

The file I'm working on is over 90 Mb in size, so bash terminal looks like the ideal place and sed the perfect tool for the job.

Search Text Example:

[[[379017.735,6940036.7955],[379009.8431,6940042.5761],[379000.4869,6940048.9545],[378991.5455,6940057.8128],[378984.0665,6940066.0744],[378974.7072,6940076.2152],[378962.8639,6940090.5283],[378954.5822,6940101.4028],[378947.9369,6940111.3128],[378941.4564,6940119.5094],[378936.2565,6940128.1229],[378927.6089,6940141.4764],[378919.6611,6940154.0312],[378917.21,6940158.7053],[378913.7614,6940163.4443],[378913.6515,6940163.5893],[378911.4453,6940166.3531],

Desired outcome:

[[[37.9017735,69.400367955],[37.90098431,69.400425761],[37.90004869,69.400489545],[37.89915455,69.400578128],[37.89840665,69.400660744],[37.89747072,69.400762152],[37.89628639,69.400905283],[37.89545822,69.401014028],[37.89479369,69.401113128],[37.89414564,69.401195094],[37.89362565,69.401281229],[37.89276089,69.401414764],[37.89196611,69.401540312],[37.891721,69.401587053],[37.89137614,69.401634443],[37.89136515,69.401635893],[37.89114453,69.401663531],

My current RegExp:

((?:\[)[0-9]{2})([0-9]+)(\.)([0-9]+)(,)([0-9]{2})([0-9]+)(\.)([0-9]+(?:\]))

and reformatting:

$1\.$2$4,$6.$7$9

The command should be something along these lines:

sed -i -e 's/ The RegExp escaped /$1\.$2$4,$6.$7$9/g' large_file.geojson

But what should be escaped in the RegExp to make it work?
My attempts always complain of being unbalanced.

I'm sorry if this has already been answered elsewhere, but I couldn't find even after extensive searching.

Edit: 2017-01-07: I didn't make it clear that the file contains properties other than just the GPS-points. One of the other example values picked from GeoJSON Feature properties is "35.642.1.001_001", which should be left unchanged. The braces check in my original regex is there for this reason.

Body:
That regex is not legal in sed; since it uses Perl syntax, my recommendation would be to use perl instead. The regular expression works exactly as-is, and even the command line is almost the same; you just need to add the -p option to get perl to operate in filter mode (which sed does by default). I would also recommend adding an argument suffix to the -i option (whether using sed or perl), so that you have a backup of the original file in case something goes horribly wrong. As for quoting, all you need to do is put the substitution command in single quotation marks:

perl -p -i.bak -e \
's/((?:\[)[0-9]{2})([0-9]+)(\.)([0-9]+)(,)([0-9]{2})([0-9]+)(\.)([0-9]+(?:\]))/$1\.$2$4,$6.$7$9/g' \
large_file.geojson


问:
Convert binary number 5 into list of intergers (4,1)
I have a configuration value expressed as a binary number to allow several options within the same value.

E.g. the value of 5 would be "101" or both 4 and 1.

Does anyone know of the best/fastest way to "input" the value '5' and get a list of {1,4} back?

答:
If you want to get powers of 2 which the value consists of:

```<code>int value = 5;
var addendums = Enumerable.Range(0, sizeof(int) * 8 - 1)
                          .Select(i => (1 << i) & value)
                          .Where(x => x != 0)
                          .ToList();
</code>```

Result:

```<code>[ 1, 4 ]
</code>```

Note that if you want to have addendums in descending order, you can apply Reverse() after filtering sequence.

TL;DR The first step generates integer values which correspond to bit positions in integer value 0, 1, 2, ..., 31. Max index is a number of bits in Int32 value - 1 (because we need the index of the bit).

Next step selects a result of bitwise AND operation of the 1 shifted to the corresponding index (same as the power of 2) with the value itself (only first 4 bits shown here):

```<code>i    1<<i     value           (1<<i) & value
    Binary    Binary       Binary      Decimal
0    0001      0101         0001          1
1    0010      0101         0000          0
2    0100      0101         0100          4
3    1000      0101         0000          0
...
</code>```

All you have to do after this step - filter out zeroes.

Body:
If you want to get powers of 2 which the value consists of:

int value = 5;
var addendums = Enumerable.Range(0, sizeof(int) * 8 - 1)
                          .Select(i => (1 << i) & value)
                          .Where(x => x != 0)
                          .ToList();

Result:

[ 1, 4 ]

Note that if you want to have addendums in descending order, you can apply Reverse() after filtering sequence.

TL;DR The first step generates integer values which correspond to bit positions in integer value 0, 1, 2, ..., 31. Max index is a number of bits in Int32 value - 1 (because we need the index of the bit).

Next step selects a result of bitwise AND operation of the 1 shifted to the corresponding index (same as the power of 2) with the value itself (only first 4 bits shown here):

i    1<<i     value           (1<<i) & value
    Binary    Binary       Binary      Decimal
0    0001      0101         0001          1
1    0010      0101         0000          0
2    0100      0101         0100          4
3    1000      0101         0000          0
...

All you have to do after this step - filter out zeroes.


问:
No provider for Router?
Im getting this error:

EXCEPTION: Error in ./AppComponent class AppComponent - inline
template:0:0 caused by: No provider for Router!

This is my app component:

import {Component} from '@angular/core';
import {LoginComponent} from './login/components/login.component';
@Component({
    selector: 'my-app',
    template: '<login></login>',

})
export class AppComponent {

}
```
<p>I tried this in my app module:</p>
<pre class="lang-ts prettyprint-override"><code>import { RouterModule } from '@angular/router';

  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LoginModule,
    RouterModule
  ],
  bootstrap: [AppComponent, RouterModule]
</code>```

But then i get this error:

Error: Error: No Directive annotation found on RouterModule

I found some examples but they use router-deprecated, and i dont have that folder. Do i need that or what? Any suggstion?

UPDATE:

This is my app.module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { LoginModule } from './login/login.module';
import { RouterModule } from '@angular/router';
//import 'rxjs/Rx';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LoginModule,
    RouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```
<p>app.component:</p>
<pre class="lang-ts prettyprint-override"><code>import {Component} from '@angular/core';
import {LoginComponent} from './login/components/login.component';
@Component({
    selector: 'my-app',
    template: '<login></login>',

})
export class AppComponent {

}
</code>```

And then i have login.component:

import {Component, EventEmitter, Input, OnChanges} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import { LoginService } from '../services/login.service';
import { Login } from '../model/login'
import {Router} from '@angular/router';
@Component({
    selector: 'login',
    templateUrl: 'login-form',

})
export class LoginComponent {
  // Constructor with injected service
      constructor(
          private loginService: LoginService,
          private router: Router
          ){}

      submitLogin(values){

          // Variable to hold a reference of addComment/updateComment
             let loginOperation:Observable<any>;
             loginOperation = this.loginService.Login(values);
             loginOperation.subscribe(
                function(response) { console.log("Success Response" + response)},
                function(error) { console.log("Error happened" + error)},
                function() {
                   console.log("the subscription is completed");
                     this.router.navigate(['/About']);

                 }
            );

           }
}
```
<p>Maybe problem is in this line:</p>
<pre class="lang-ts prettyprint-override"><code> this.router.navigate(['/home']);
</code>```

This is my login.module:

import { NgModule }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { LoginComponent } from './components/login.component';
import { RouterModule } from '@angular/router';

import { LoginService } from './services/login.service';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
     HttpModule,
    JsonpModule,
    RouterModule

  ],
  declarations: [
    LoginComponent
  ],

  providers: [
      LoginService
  ],

  exports:[
    LoginComponent
  ]

})
export class LoginModule {
}
```

答:
Babar Bilal's answer likely worked perfectly for earlier Angular 2 alpha/beta releases.  However, anyone solving this problem with Angular release v4+ may want to try the following change to his answer instead (wrapping the single route in the required array):</p>

```<code>RouterModule.forRoot([{ path: "", component: LoginComponent}])
</code>```

ContentLicense: CC BY-SA 4.0

Title: No provider for Router?

Body:
Im getting this error:

EXCEPTION: Error in ./AppComponent class AppComponent - inline
template:0:0 caused by: No provider for Router!

This is my app component:

import {Component} from '@angular/core';
import {LoginComponent} from './login/components/login.component';
@Component({
    selector: 'my-app',
    template: '<login></login>',

})
export class AppComponent {

}

I tried this in my app module:

import { RouterModule } from '@angular/router';

  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LoginModule,
    RouterModule
  ],
  bootstrap: [AppComponent, RouterModule]

But then i get this error:

Error: Error: No Directive annotation found on RouterModule

I found some examples but they use router-deprecated, and i dont have that folder. Do i need that or what? Any suggstion?

UPDATE:

This is my app.module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { LoginModule } from './login/login.module';
import { RouterModule } from '@angular/router';
//import 'rxjs/Rx';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LoginModule,
    RouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component:

import {Component} from '@angular/core';
import {LoginComponent} from './login/components/login.component';
@Component({
    selector: 'my-app',
    template: '<login></login>',

})
export class AppComponent {

}

And then i have login.component:

import {Component, EventEmitter, Input, OnChanges} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import { LoginService } from '../services/login.service';
import { Login } from '../model/login'
import {Router} from '@angular/router';
@Component({
    selector: 'login',
    templateUrl: 'login-form',

})
export class LoginComponent {
  // Constructor with injected service
      constructor(
          private loginService: LoginService,
          private router: Router
          ){}

      submitLogin(values){

          // Variable to hold a reference of addComment/updateComment
             let loginOperation:Observable<any>;
             loginOperation = this.loginService.Login(values);
             loginOperation.subscribe(
                function(response) { console.log("Success Response" + response)},
                function(error) { console.log("Error happened" + error)},
                function() {
                   console.log("the subscription is completed");
                     this.router.navigate(['/About']);

                 }
            );

           }
}

Maybe problem is in this line:

 this.router.navigate(['/home']);

This is my login.module:

import { NgModule }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { LoginComponent } from './components/login.component';
import { RouterModule } from '@angular/router';

import { LoginService } from './services/login.service';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
     HttpModule,
    JsonpModule,
    RouterModule

  ],
  declarations: [
    LoginComponent
  ],

  providers: [
      LoginService
  ],

  exports:[
    LoginComponent
  ]

})
export class LoginModule {
}

Body:
Babar Bilal's answer likely worked perfectly for earlier Angular 2 alpha/beta releases.  However, anyone solving this problem with Angular release v4+ may want to try the following change to his answer instead (wrapping the single route in the required array):

RouterModule.forRoot([{ path: "", component: LoginComponent}])


问:
THREE.Color: Unknown color #002dff (warning/error)
I need to update the color after receiving the value from dat.GUI .
But, this

```<code>var colored = new THREE.Color(value.replace("#","0x"));
</code>```

is throwing this warning "THREE.Color: Unknown color 0x002dff" and the 'colored' isn't updating.

value = #002dff (at that time, it keeps on changing, user input)

Edit: I know I can use this as "THREE.Color( #002dff )", but the color is changing at run time according to the user input from controls I've created using dat.GUI, so I won't be knowing the actual value that can be added to the code.

PS: It was replace() which was causing the problem. It's solved.

答:
THREE.Color() has the .setStyle() method.

```<code>var obj;
var gui = new dat.GUI();
var props = {
    color: '#002dff'
};
var colorController = gui.addColor(props, 'color');
colorController.onChange(
    function(value){
    // uncomment this to see it's working
    //var colored = new THREE.Color(value);
    //console.log(colored);
    obj.material.color.setStyle(value);
  }
);

var sphere = new THREE.Mesh(new THREE.SphereGeometry(2, 32, 24), new THREE.MeshStandardMaterial());
sphere.material.color.setStyle("#002dff");
scene.add(sphere);
obj = sphere;
</code>```

jsfiddle example. three.js r85, dat.GUI 0.6.5

PS Don't use new THREE.Color() to change an exisiting colour of a material, use setXXXXX() methods of THREE.Color()

Body:
I need to update the color after receiving the value from dat.GUI .
But, this

var colored = new THREE.Color(value.replace("#","0x"));

is throwing this warning "THREE.Color: Unknown color 0x002dff" and the 'colored' isn't updating.

value = #002dff (at that time, it keeps on changing, user input)

Edit: I know I can use this as "THREE.Color( #002dff )", but the color is changing at run time according to the user input from controls I've created using dat.GUI, so I won't be knowing the actual value that can be added to the code.

PS: It was replace() which was causing the problem. It's solved.

Body:
THREE.Color() has the .setStyle() method.

var obj;
var gui = new dat.GUI();
var props = {
    color: '#002dff'
};
var colorController = gui.addColor(props, 'color');
colorController.onChange(
    function(value){
    // uncomment this to see it's working
    //var colored = new THREE.Color(value);
    //console.log(colored);
    obj.material.color.setStyle(value);
  }
);

var sphere = new THREE.Mesh(new THREE.SphereGeometry(2, 32, 24), new THREE.MeshStandardMaterial());
sphere.material.color.setStyle("#002dff");
scene.add(sphere);
obj = sphere;

jsfiddle example. three.js r85, dat.GUI 0.6.5

PS Don't use new THREE.Color() to change an exisiting colour of a material, use setXXXXX() methods of THREE.Color()


问:
How to get json object array from deep nested json array?
This is my json, I wanted to get 'products' arrays object.

```<code>{
       "Categories":[
          {
             "id":6,
             "status":"1",
             "parent_id":"0",
             "name":"Bottom Wear",
             "name_ar":"\u0623\u0633\u0641\u0644 \u0627\u0631\u062a\u062f\u0627\u0621",
             "picture":null,
             "description":"gents bottom wear",
             "slug":"bottom-wear",
             "created_at":"2017-06-05 21:08:28",
             "updated_at":"2017-06-05 21:08:28",
             "deleted_at":null,
             "product":[
                {
                   "id":2,
                   "status":"1",
                   "name":"Pants",
                   "name_ar":"\u0628\u0646\u0637\u0644\u0648\u0646",
                   "dryclean_price":"9",
                   "washing_price":"6",
                   "press":"4",
                   "sw_dryclean_price":"9",
                   "sw_washing_price":"6",
                   "sw_press":"4",
                   "picture":null,
                   "created_at":"2017-04-19 21:32:04",
                   "updated_at":"2017-06-05 21:18:04",
                   "deleted_at":null,
                   "pivot":{
                      "category_id":"6",
                      "product_id":"2"
                   }
                },
                {
                   "id":8,
                   "status":"1",
                   "parent_id":"0",
                   "name":"Undergarments",
                   "name_ar":"\u0623\u062b\u0648\u0627\u0628 \u062a\u062d\u062a\u0627\u0646\u064a\u0629",
                   "picture":null,
                   "description":"Undergarments",
                   "slug":"undergarments",
                   "created_at":"2017-06-05 21:22:09",
                   "updated_at":"2017-06-05 21:22:09",
                   "deleted_at":null,
                   "product":[
                      {
                         "id":23,
                         "status":"1",
                         "name":"Underwear",
                         "name_ar":"\u062b\u064a\u0627\u0628 \u062f\u0627\u062e\u0644\u064a\u0629",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-04-19 21:35:31",
                         "updated_at":"2017-06-05 21:23:42",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"23"
                         }
                      },
                      {
                         "id":34,
                         "status":"1",
                         "name":"Socks",
                         "name_ar":"\u062c\u0648\u0627\u0631\u0628",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-06-05 21:26:14",
                         "updated_at":"2017-06-05 21:26:14",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"34"
                         }
                      }
                   ]
                }
             ]
          }
       ]
    }
</code>```

I am able to save categories in my db like this.

```<code>  protected final String CategoryTable = "category_table";
    protected final String D_ID = "category_id";
    protected final String D_SERVER_ID = "categoryserver_id";
    protected final String D_JSON = "category_json";

 public boolean insertCategory(Category model) {
        ContentValues cv = new ContentValues();
        database = this.getWritableDatabase();
        cv.put(D_SERVER_ID, model.getId());
        cv.put(D_JSON, new Gson().toJson(model));
        int res = (int) database.insert(CategoryTable, null, cv);
        database.close();
        if (res > 0) {
            return true;
        } else {
            return false;
        }
    }

  public Collection<Category> getAllCategories() {
        database = this.getReadableDatabase();
        Gson gson = new Gson();
        ArrayList<Category> lst = new ArrayList<>();
        Cursor c = database.rawQuery("SELECT * FROM " + CategoryTable, null);
        if (c.moveToFirst()) {
            do {
                Category obj = gson.fromJson(c.getString(c.getColumnIndex(D_JSON)), Category.class);
                if (obj != null)
                    lst.add(obj);
            } while (c.moveToNext());
        }
        return lst;
    }
</code>```

Here is a Category Model class:

```<code>public class Category {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("parent_id")
    @Expose
    private String parentId;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("name_ar")
    @Expose
    private String nameAr;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("deleted_at")
    @Expose
    private Object deletedAt;
    @SerializedName("product")
    @Expose
    private List<Product> product = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNameAr() {
        return nameAr;
    }

    public void setNameAr(String nameAr) {
        this.nameAr = nameAr;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Object getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(Object deletedAt) {
        this.deletedAt = deletedAt;
    }

    public List<Product> getProduct() {
        return product;
    }

    public void setProduct(List<Product> product) {
        this.product = product;
    }

}
</code>```

I am using retrofit library to get data. Here is the method I am using to save categories array in my db.

```<code>@Override
    public void onSuccess(Call call, Response response, int reqCode) {
        Loading.cancel();
        ProductsResponse productsResponse = (ProductsResponse) response.body();
        for (int i = 0; i < productsResponse.getCategories().size(); i++) {
            Category obj = productsResponse.getCategories().get(i);
            categories.add(obj);
            categoriesHandler.insertCategory(obj);
            categoriesHandler.insertLabel(obj.getName());
        }
        adapter.notifyDataSetChanged();
        loadSpinnerData();
}
</code>```

But how can I get product jsonArray from categories. Tried a lot but not able to find a method. Your help would be appreciated. Need to get products on the bases of categories. Kindly help. Thanks in advance.

Ashish I am using your method:

```<code> private void categorySelector(String str){
        Gson gson = new GsonBuilder().create();
        JSONArray mainData = (JSONArray) categoriesHandler.getAllCategories();
        ArrayList<Category> responseAsArrayList =
                gson.fromJson(mainData.toString(), new TypeToken<List<Category>>() {
                }.getType());
        for(int i =0;i<responseAsArrayList.size();i++)
        {
            for(int j = 0; j < responseAsArrayList.get(i).getProduct().size();j++)
            {
                Category category =  responseAsArrayList.get(i);
                Product product = category.getProduct().get(j);
                products.add(product);
            }

        }
</code>```

答:
json.getJSONArray("Categories").getJSONObject(0).getJSONArray("product")

will give you product array

Body:
This is my json, I wanted to get 'products' arrays object.

{
       "Categories":[
          {
             "id":6,
             "status":"1",
             "parent_id":"0",
             "name":"Bottom Wear",
             "name_ar":"\u0623\u0633\u0641\u0644 \u0627\u0631\u062a\u062f\u0627\u0621",
             "picture":null,
             "description":"gents bottom wear",
             "slug":"bottom-wear",
             "created_at":"2017-06-05 21:08:28",
             "updated_at":"2017-06-05 21:08:28",
             "deleted_at":null,
             "product":[
                {
                   "id":2,
                   "status":"1",
                   "name":"Pants",
                   "name_ar":"\u0628\u0646\u0637\u0644\u0648\u0646",
                   "dryclean_price":"9",
                   "washing_price":"6",
                   "press":"4",
                   "sw_dryclean_price":"9",
                   "sw_washing_price":"6",
                   "sw_press":"4",
                   "picture":null,
                   "created_at":"2017-04-19 21:32:04",
                   "updated_at":"2017-06-05 21:18:04",
                   "deleted_at":null,
                   "pivot":{
                      "category_id":"6",
                      "product_id":"2"
                   }
                },
                {
                   "id":8,
                   "status":"1",
                   "parent_id":"0",
                   "name":"Undergarments",
                   "name_ar":"\u0623\u062b\u0648\u0627\u0628 \u062a\u062d\u062a\u0627\u0646\u064a\u0629",
                   "picture":null,
                   "description":"Undergarments",
                   "slug":"undergarments",
                   "created_at":"2017-06-05 21:22:09",
                   "updated_at":"2017-06-05 21:22:09",
                   "deleted_at":null,
                   "product":[
                      {
                         "id":23,
                         "status":"1",
                         "name":"Underwear",
                         "name_ar":"\u062b\u064a\u0627\u0628 \u062f\u0627\u062e\u0644\u064a\u0629",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-04-19 21:35:31",
                         "updated_at":"2017-06-05 21:23:42",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"23"
                         }
                      },
                      {
                         "id":34,
                         "status":"1",
                         "name":"Socks",
                         "name_ar":"\u062c\u0648\u0627\u0631\u0628",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-06-05 21:26:14",
                         "updated_at":"2017-06-05 21:26:14",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"34"
                         }
                      }
                   ]
                }
             ]
          }
       ]
    }

I am able to save categories in my db like this.

  protected final String CategoryTable = "category_table";
    protected final String D_ID = "category_id";
    protected final String D_SERVER_ID = "categoryserver_id";
    protected final String D_JSON = "category_json";

 public boolean insertCategory(Category model) {
        ContentValues cv = new ContentValues();
        database = this.getWritableDatabase();
        cv.put(D_SERVER_ID, model.getId());
        cv.put(D_JSON, new Gson().toJson(model));
        int res = (int) database.insert(CategoryTable, null, cv);
        database.close();
        if (res > 0) {
            return true;
        } else {
            return false;
        }
    }

  public Collection<Category> getAllCategories() {
        database = this.getReadableDatabase();
        Gson gson = new Gson();
        ArrayList<Category> lst = new ArrayList<>();
        Cursor c = database.rawQuery("SELECT * FROM " + CategoryTable, null);
        if (c.moveToFirst()) {
            do {
                Category obj = gson.fromJson(c.getString(c.getColumnIndex(D_JSON)), Category.class);
                if (obj != null)
                    lst.add(obj);
            } while (c.moveToNext());
        }
        return lst;
    }

Here is a Category Model class:

public class Category {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("parent_id")
    @Expose
    private String parentId;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("name_ar")
    @Expose
    private String nameAr;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("deleted_at")
    @Expose
    private Object deletedAt;
    @SerializedName("product")
    @Expose
    private List<Product> product = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNameAr() {
        return nameAr;
    }

    public void setNameAr(String nameAr) {
        this.nameAr = nameAr;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Object getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(Object deletedAt) {
        this.deletedAt = deletedAt;
    }

    public List<Product> getProduct() {
        return product;
    }

    public void setProduct(List<Product> product) {
        this.product = product;
    }

}

I am using retrofit library to get data. Here is the method I am using to save categories array in my db.

@Override
    public void onSuccess(Call call, Response response, int reqCode) {
        Loading.cancel();
        ProductsResponse productsResponse = (ProductsResponse) response.body();
        for (int i = 0; i < productsResponse.getCategories().size(); i++) {
            Category obj = productsResponse.getCategories().get(i);
            categories.add(obj);
            categoriesHandler.insertCategory(obj);
            categoriesHandler.insertLabel(obj.getName());
        }
        adapter.notifyDataSetChanged();
        loadSpinnerData();
}

But how can I get product jsonArray from categories. Tried a lot but not able to find a method. Your help would be appreciated. Need to get products on the bases of categories. Kindly help. Thanks in advance.

Ashish I am using your method:

 private void categorySelector(String str){
        Gson gson = new GsonBuilder().create();
        JSONArray mainData = (JSONArray) categoriesHandler.getAllCategories();
        ArrayList<Category> responseAsArrayList =
                gson.fromJson(mainData.toString(), new TypeToken<List<Category>>() {
                }.getType());
        for(int i =0;i<responseAsArrayList.size();i++)
        {
            for(int j = 0; j < responseAsArrayList.get(i).getProduct().size();j++)
            {
                Category category =  responseAsArrayList.get(i);
                Product product = category.getProduct().get(j);
                products.add(product);
            }

        }


问:
Button Click not working After Ajax call in bootstrap modal
Button is working before ajax call in bootstrap Modal.
But After Ajax call click event is not working.

```<code>function book_appointment_timeslot(job_id,planner_date,time_slot,contract_id){
       $.ajax({
                  type: "POST",
                  url: "/add_appointment_planner",
                  data: { contract_id: contract_id,job_id : job_id,  planner_date: planner_date, time_slot: time_slot, _token: CSRF_TOKEN },
                  success: function(data){
                         if(data['status']=='success')
                         {
                                show_notification(data['status'],data['message']);
                                $("#apt_status_table").load(location.href + " #apt_status_table");
                                $(".tbl_planner_list_whole").load(location.href + " .tbl_planner_list_whole");

                         }
                  }
    });
}
</code>```

I Have tried below solutions ,

Solution-1 :-

```<code>$(document).on('click', '.appointment_edit_button', function(){
    alert("success");
});
</code>```

Solution-2 :-

```<code>$(document).delegate('click', '.appointment_edit_button', function(){
    alert("success");
});
</code>```

I tried with unbind() also. It also not working.
When I put script directly in Console. Then it's working. So may be it's due to bootstrap modal.

So, I want to enable button click event after ajax call in bootstrap modal.

EDIT :-

HTML Code :-

```<code><tbody>
    <tr>
                            <td>
                                <div class="agenda-date">
                                    <div class="dayofmonth color_font_date">2017-06-01</div>
                                    <div class="dayofweek">
                                        thursday                                            </div>
                                </div>
                            </td>
                            <td>
                                <div class="row margin_two_planner">
                                        <button type="button" class="btn btn-sm btn-primary" onclick="book_appointment_timeslot(19,"2017-06-01",
                                            1,43)">am </button>
                                        <a data-toggle="modal" href="#add_apt_status" class=""><input type="number" value="8" name="" class="number_planner"></a>
                                        <input type="number" value="9" name="" class="max_limit" disabled="">
                                        <input type="hidden" value="am" name="" class="timeslot_max_limit" disabled="">
                                </div>
                                <div class="row margin_two_planner">
                                        <button type="button" class="btn btn-sm btn-primary" onclick="book_appointment_timeslot(19,"2017-06-01",
                                            2,43)">pm </button>
                                        <a data-toggle="modal" href="#add_apt_status" class=""><input type="number" value="6" name="" class="number_planner"></a>
                                        <input type="number" value="5" name="" class="max_limit" disabled="">
                                        <input type="hidden" value="pm" name="" class="timeslot_max_limit" disabled="">
                                </div>
                            </td>
                            <td style="width: 20%;">
                                    <textarea id="" class="form-control initial_cap appointment_note" required="required" rows="3" name="appointment_note" cols="50" aria-required="true" disabled="">       asdsad             </textarea>
                            </td>
                            <td style="width: 20%;">
                                <textarea id="" class="form-control initial_cap holiday_note" required="required" rows="3" name="holiday_note" cols="50" aria-required="true" disabled="">       asasdsaddsad        </textarea>
                            </td>
                            <td>
                            <div class="text-right">
                                    <input type="hidden" class="planner_date" name="" value="2017-06-01">
                                    <input type="hidden" class="contract_id" name="" value="43">
                                    <button type="button" id="" class="btn btn-primary appointment_edit_button">edit </button>
                                    <button type="button" id="" onclick="planner_note_edit(10,event)" class="btn btn-md btn-primary appointment_update_button" style="display:none"> update </button>
                                    <button type="button" id="" class="btn btn-md btn-cancel appointment_cancel_button" style="display:none">cancel </button>
                            </div>
                            </td>
    </tr>
</tbody>
</code>```

Through this appointment_edit_button class I'm doing this process.

```<code>$(".appointment_edit_button").on("click",function(event) {
        $(this).closest('tr').find(".appointment_note").prop("disabled", false);
        $(this).closest('tr').find(".holiday_note").prop("disabled", false);
        $(this).closest('tr').find(".max_limit").prop("disabled", false);
        $(this).next('button').show();
        $(this).next('button').next('button').show();
        $(this).hide();
});
</code>```

I looks like.

答:
I am guessing your dom is manipulated by that ajax success callback so the click event registration is removed. Try to bind the click event again in the ajax callback.</p>

```<code>function book_appointment_timeslot(job_id,planner_date,time_slot,contract_id){
   $.ajax({
              type: "POST",
              url: "/add_appointment_planner",
              data: { contract_id: contract_id,job_id : job_id,  planner_date: planner_date, time_slot: time_slot, _token: CSRF_TOKEN },
              success: function(data){
                     if(data['status']=='success')
                     {
                            show_notification(data['status'],data['message']);
                            $("#apt_status_table").load(location.href + " #apt_status_table");
                            $(".tbl_planner_list_whole").load(location.href + " .tbl_planner_list_whole");
                            $('.appointment_edit_button').click(function(){alert("success");});

                     }
              }
});
}
</code>```

Body:
Button is working before ajax call in bootstrap Modal.
But After Ajax call click event is not working.

function book_appointment_timeslot(job_id,planner_date,time_slot,contract_id){
       $.ajax({
                  type: "POST",
                  url: "/add_appointment_planner",
                  data: { contract_id: contract_id,job_id : job_id,  planner_date: planner_date, time_slot: time_slot, _token: CSRF_TOKEN },
                  success: function(data){
                         if(data['status']=='success')
                         {
                                show_notification(data['status'],data['message']);
                                $("#apt_status_table").load(location.href + " #apt_status_table");
                                $(".tbl_planner_list_whole").load(location.href + " .tbl_planner_list_whole");

                         }
                  }
    });
}

I Have tried below solutions ,

Solution-1 :-

$(document).on('click', '.appointment_edit_button', function(){
    alert("success");
});

Solution-2 :-

$(document).delegate('click', '.appointment_edit_button', function(){
    alert("success");
});

I tried with unbind() also. It also not working.
When I put script directly in Console. Then it's working. So may be it's due to bootstrap modal.

So, I want to enable button click event after ajax call in bootstrap modal.

EDIT :-

HTML Code :-

2017-06-01

                                        thursday

                                        <button type="button" class="btn btn-sm btn-primary" onclick="book_appointment_timeslot(19,"2017-06-01",
                                            1,43)">am </button>
                                        <input type="number" value="8" name="" class="number_planner">
                                        <input type="number" value="9" name="" class="max_limit" disabled="">
                                        <input type="hidden" value="am" name="" class="timeslot_max_limit" disabled="">

                                        <button type="button" class="btn btn-sm btn-primary" onclick="book_appointment_timeslot(19,"2017-06-01",
                                            2,43)">pm </button>
                                        <input type="number" value="6" name="" class="number_planner">
                                        <input type="number" value="5" name="" class="max_limit" disabled="">
                                        <input type="hidden" value="pm" name="" class="timeslot_max_limit" disabled="">

                                    <textarea id="" class="form-control initial_cap appointment_note" required="required" rows="3" name="appointment_note" cols="50" aria-required="true" disabled="">       asdsad             </textarea>

                                <textarea id="" class="form-control initial_cap holiday_note" required="required" rows="3" name="holiday_note" cols="50" aria-required="true" disabled="">       asasdsaddsad        </textarea>

                                    <input type="hidden" class="planner_date" name="" value="2017-06-01">
                                    <input type="hidden" class="contract_id" name="" value="43">
                                    <button type="button" id="" class="btn btn-primary appointment_edit_button">edit </button>
                                    <button type="button" id="" onclick="planner_note_edit(10,event)" class="btn btn-md btn-primary appointment_update_button" style="display:none"> update </button>
                                    <button type="button" id="" class="btn btn-md btn-cancel appointment_cancel_button" style="display:none">cancel </button>

Through this appointment_edit_button class I'm doing this process.

$(".appointment_edit_button").on("click",function(event) {
        $(this).closest('tr').find(".appointment_note").prop("disabled", false);
        $(this).closest('tr').find(".holiday_note").prop("disabled", false);
        $(this).closest('tr').find(".max_limit").prop("disabled", false);
        $(this).next('button').show();
        $(this).next('button').next('button').show();
        $(this).hide();
});

I looks like.

Body:
I am guessing your dom is manipulated by that ajax success callback so the click event registration is removed. Try to bind the click event again in the ajax callback.

function book_appointment_timeslot(job_id,planner_date,time_slot,contract_id){
   $.ajax({
              type: "POST",
              url: "/add_appointment_planner",
              data: { contract_id: contract_id,job_id : job_id,  planner_date: planner_date, time_slot: time_slot, _token: CSRF_TOKEN },
              success: function(data){
                     if(data['status']=='success')
                     {
                            show_notification(data['status'],data['message']);
                            $("#apt_status_table").load(location.href + " #apt_status_table");
                            $(".tbl_planner_list_whole").load(location.href + " .tbl_planner_list_whole");
                            $('.appointment_edit_button').click(function(){alert("success");});

                     }
              }
});
}


问:
MS-SQL 2000: Turn off logging during stored procedure
Here's my scenario:

I have a simple stored procedure that removes a specific set of rows from a table (we'll say about 30k rows), and then inserts about the same amount of rows.  This generally should only take a few seconds; however, the table has a trigger on it that watches for inserts/deletes, and tries to mimic what happened to a linked table on another server.

This process in turn is unbareably slow due to the trigger, and the table is also locked during this process.  So here are my two questions:

I'm guessing a decent part of the slowdown is due to the transaction log.  Is there a way for me to specify in my stored procedure that I do not want what's in the procedure to be logged?

Is there a way for me to do my 'DELETE FROM' and 'INSERT INTO' commands without me locking the table during the entire process?

Thanks!

edit - Thanks for the answers; I figured it was the case (not being able to do either of the above), but wanted to make sure.  The trigger was created a long time ago, and doesn't look very effecient, so it looks like my next step will be to go in to that and find out what's needed and how it can be improved.  Thanks!

答: You can't turn off transactional integrity when modifying the data. You could ignore locks when you select data using select * from table (nolock); however, you need to be very careful and ensure your application can handle doing dirty reads.

OwnerDisplayName: John

LastEditorDisplayName: CodeSlave

OwnerDisplayName: Josh