问:
Stackoverflow exception (0xc00000fd) in Windows service
I have developed a windows service .exe having multiple services in it like below:

```<code> static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service1(),
            new Service2(),
            new Service3(),
            new Service4()
        };
        ServiceBase.Run(ServicesToRun);
    }
</code>```

I am getting following fatal error (checking event logs) on production which is stackoverflow exception:

Faulting application name: MyApp.exe, version: 1.0.0.0, time stamp: 0x522e8317

Faulting module name: clr.dll, version: 4.0.30319.18047, time stamp: 0x58dcff99

Exception code: 0xc00000fd

Fault offset: 0x004226a2

Faulting process id: 0xeb4c

Faulting application start time: 0x01d2a9de37398bdb

Faulting application path: C:\Users\Administrator\Desktop\MyApp.exe

Faulting module path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll

Report Id: d52424aa-1a16-11e3-bc4b-002590a4ec55

Below is the code for one of my windows service :

```<code>private Timer timer1 = null;
private static object _intervalSync = new object();

protected override void OnStart(string[] args)
    {
        try
        {
            timer1 = new Timer();
            this.timer1.Interval = Convert.ToDouble(900000); // 15mins
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled = true;
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
        }
    }

    protected override void OnStop()
    {
        try
        {
            timer1.Enabled = false;
            timer1.Stop();
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
        }
    }

    private void timer1_Tick(object sender, ElapsedEventArgs e)
    {
        if (System.Threading.Monitor.TryEnter(_intervalSync))
        {
            try
            {
               // execute code
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
            finally
            {
                System.Threading.Monitor.Exit(_intervalSync);
            }
        }
    }
</code>```

Please find the recursive code:

```<code>public void fetchInventorySupplyFromAmazon(Parameter parameter, DateTime queryStartDateTime)
    {
        ListInventorySupplyResponse listInventorySupplyResponse = new ListInventorySupplyResponse();
        ListInventorySupplyByNextTokenResponse listInventorySupplyByNextTokenResponse = new ListInventorySupplyByNextTokenResponse();
        FBAInventoryDetailServiceMWS fbaInventoryDetailServiceMWS = new FBAInventoryDetailServiceMWS(parameter);
        SetParameter setParameter = new SetParameter();
        try
        {
            if (parameter.nextToken != null && parameter.nextToken != "")
            {

                listInventorySupplyByNextTokenResponse = fbaInventoryDetailServiceMWS.InvokeListInventorySupplyByNextToken(parameter.nextToken);
                foreach (var inventorySupply in listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult.InventorySupplyList.member)
                {
                    insertUpdateInventory(inventorySupply, parameter);
                }
                if (listInventorySupplyByNextTokenResponse.IsSetListInventorySupplyByNextTokenResult())
                {
                    setParameter.SetParameterValue(parameter, listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult.NextToken);
                //recursive call
                    fetchInventorySupplyFromAmazon(parameter, queryStartDateTime);
                }
            }
            else
            {
                listInventorySupplyResponse = fbaInventoryDetailServiceMWS.InvokeListInventorySupply(queryStartDateTime);
                foreach (var inventorySupply in listInventorySupplyResponse.ListInventorySupplyResult.InventorySupplyList.member)
                {
                    insertUpdateInventory(inventorySupply, parameter);
                }
                if (listInventorySupplyResponse.ListInventorySupplyResult.NextToken != null && listInventorySupplyResponse.ListInventorySupplyResult.NextToken != "")
                {
                    setParameter.SetParameterValue(parameter, listInventorySupplyResponse.ListInventorySupplyResult.NextToken);
                //recursive call
                    fetchInventorySupplyFromAmazon(parameter, queryStartDateTime);
                }
            }

        }
        catch (MarketplaceWebServiceOrdersException ex)
        {
            if ((!string.IsNullOrEmpty(ex.ErrorCode) ? ex.ErrorCode.ToString().Trim().ToUpper().Equals("NEXTTOKENCORRUPTED") : false) ||
                ex.StatusCode.ToString().Trim().ToUpper().Equals("UNAUTHORIZED"))
            {
                setParameter.SetParameterValue(parameter, null);
                //recursive call
                fetchInventorySupplyFromAmazon(parameter, queryStartDateTime);
            }
            else
            {
                throw;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
</code>```

Any Help would be great !!

答:
The problem was with my business logic.
I have changed the fetchInventorySupplyFromAmazon function to include do while loop instead of recursive calls.

```<code> public void fetchInventorySupplyFromAmazon(Parameter parameter, DateTime queryStartDateTime)
    {
        ListInventorySupplyResponse listInventorySupplyResponse = new ListInventorySupplyResponse();
        ListInventorySupplyByNextTokenResponse listInventorySupplyByNextTokenResponse = new ListInventorySupplyByNextTokenResponse();
        FBAInventoryDetailServiceMWS fbaInventoryDetailServiceMWS = new FBAInventoryDetailServiceMWS(parameter);
        SetParameter setParameter = new SetParameter();

        try
        {
            parameter.nextToken = null;
            do
            {
                if (string.IsNullOrEmpty(parameter.nextToken))
                {
                    listInventorySupplyResponse = fbaInventoryDetailServiceMWS.InvokeListInventorySupply(queryStartDateTime);
                    if (listInventorySupplyResponse.ListInventorySupplyResult != null)
                    {
                        if (listInventorySupplyResponse.ListInventorySupplyResult.InventorySupplyList != null)
                        {
                            foreach (var inventorySupply in listInventorySupplyResponse.ListInventorySupplyResult.InventorySupplyList.member)
                            {
                                insertUpdateInventory(inventorySupply, parameter);
                            }
                        }

                        setParameter.SetParameterValue(parameter, listInventorySupplyResponse.ListInventorySupplyResult.NextToken);
                    }
                }
                else
                {
                    listInventorySupplyByNextTokenResponse = fbaInventoryDetailServiceMWS.InvokeListInventorySupplyByNextToken(parameter.nextToken);
                    if (listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult != null)
                    {
                        if (listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult.InventorySupplyList != null)
                        {
                            foreach (var inventorySupply in listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult.InventorySupplyList.member)
                            {
                                insertUpdateInventory(inventorySupply, parameter);
                            }
                        }
                        setParameter.SetParameterValue(parameter, listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult.NextToken);
                    }
                    else
                    {
                        setParameter.SetParameterValue(parameter, null);
                    }
                }
            } while (!string.IsNullOrEmpty(parameter.nextToken));

        }
        catch (Exception)
        {
            throw;
        }
    }
</code>```

Body:
I have developed a windows service .exe having multiple services in it like below:

 static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service1(),
            new Service2(),
            new Service3(),
            new Service4()
        };
        ServiceBase.Run(ServicesToRun);
    }

I am getting following fatal error (checking event logs) on production which is stackoverflow exception:

Faulting application name: MyApp.exe, version: 1.0.0.0, time stamp: 0x522e8317

Faulting module name: clr.dll, version: 4.0.30319.18047, time stamp: 0x58dcff99

Exception code: 0xc00000fd

Fault offset: 0x004226a2

Faulting process id: 0xeb4c

Faulting application start time: 0x01d2a9de37398bdb

Faulting application path: C:\Users\Administrator\Desktop\MyApp.exe

Faulting module path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll

Report Id: d52424aa-1a16-11e3-bc4b-002590a4ec55

Below is the code for one of my windows service :

private Timer timer1 = null;
private static object _intervalSync = new object();

protected override void OnStart(string[] args)
    {
        try
        {
            timer1 = new Timer();
            this.timer1.Interval = Convert.ToDouble(900000); // 15mins
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled = true;
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
        }
    }

    protected override void OnStop()
    {
        try
        {
            timer1.Enabled = false;
            timer1.Stop();
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
        }
    }

    private void timer1_Tick(object sender, ElapsedEventArgs e)
    {
        if (System.Threading.Monitor.TryEnter(_intervalSync))
        {
            try
            {
               // execute code
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
            finally
            {
                System.Threading.Monitor.Exit(_intervalSync);
            }
        }
    }

Please find the recursive code:

public void fetchInventorySupplyFromAmazon(Parameter parameter, DateTime queryStartDateTime)
    {
        ListInventorySupplyResponse listInventorySupplyResponse = new ListInventorySupplyResponse();
        ListInventorySupplyByNextTokenResponse listInventorySupplyByNextTokenResponse = new ListInventorySupplyByNextTokenResponse();
        FBAInventoryDetailServiceMWS fbaInventoryDetailServiceMWS = new FBAInventoryDetailServiceMWS(parameter);
        SetParameter setParameter = new SetParameter();
        try
        {
            if (parameter.nextToken != null && parameter.nextToken != "")
            {

                listInventorySupplyByNextTokenResponse = fbaInventoryDetailServiceMWS.InvokeListInventorySupplyByNextToken(parameter.nextToken);
                foreach (var inventorySupply in listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult.InventorySupplyList.member)
                {
                    insertUpdateInventory(inventorySupply, parameter);
                }
                if (listInventorySupplyByNextTokenResponse.IsSetListInventorySupplyByNextTokenResult())
                {
                    setParameter.SetParameterValue(parameter, listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult.NextToken);
                //recursive call
                    fetchInventorySupplyFromAmazon(parameter, queryStartDateTime);
                }
            }
            else
            {
                listInventorySupplyResponse = fbaInventoryDetailServiceMWS.InvokeListInventorySupply(queryStartDateTime);
                foreach (var inventorySupply in listInventorySupplyResponse.ListInventorySupplyResult.InventorySupplyList.member)
                {
                    insertUpdateInventory(inventorySupply, parameter);
                }
                if (listInventorySupplyResponse.ListInventorySupplyResult.NextToken != null && listInventorySupplyResponse.ListInventorySupplyResult.NextToken != "")
                {
                    setParameter.SetParameterValue(parameter, listInventorySupplyResponse.ListInventorySupplyResult.NextToken);
                //recursive call
                    fetchInventorySupplyFromAmazon(parameter, queryStartDateTime);
                }
            }

        }
        catch (MarketplaceWebServiceOrdersException ex)
        {
            if ((!string.IsNullOrEmpty(ex.ErrorCode) ? ex.ErrorCode.ToString().Trim().ToUpper().Equals("NEXTTOKENCORRUPTED") : false) ||
                ex.StatusCode.ToString().Trim().ToUpper().Equals("UNAUTHORIZED"))
            {
                setParameter.SetParameterValue(parameter, null);
                //recursive call
                fetchInventorySupplyFromAmazon(parameter, queryStartDateTime);
            }
            else
            {
                throw;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

Any Help would be great !!

Body:
The problem was with my business logic.
I have changed the fetchInventorySupplyFromAmazon function to include do while loop instead of recursive calls.

 public void fetchInventorySupplyFromAmazon(Parameter parameter, DateTime queryStartDateTime)
    {
        ListInventorySupplyResponse listInventorySupplyResponse = new ListInventorySupplyResponse();
        ListInventorySupplyByNextTokenResponse listInventorySupplyByNextTokenResponse = new ListInventorySupplyByNextTokenResponse();
        FBAInventoryDetailServiceMWS fbaInventoryDetailServiceMWS = new FBAInventoryDetailServiceMWS(parameter);
        SetParameter setParameter = new SetParameter();

        try
        {
            parameter.nextToken = null;
            do
            {
                if (string.IsNullOrEmpty(parameter.nextToken))
                {
                    listInventorySupplyResponse = fbaInventoryDetailServiceMWS.InvokeListInventorySupply(queryStartDateTime);
                    if (listInventorySupplyResponse.ListInventorySupplyResult != null)
                    {
                        if (listInventorySupplyResponse.ListInventorySupplyResult.InventorySupplyList != null)
                        {
                            foreach (var inventorySupply in listInventorySupplyResponse.ListInventorySupplyResult.InventorySupplyList.member)
                            {
                                insertUpdateInventory(inventorySupply, parameter);
                            }
                        }

                        setParameter.SetParameterValue(parameter, listInventorySupplyResponse.ListInventorySupplyResult.NextToken);
                    }
                }
                else
                {
                    listInventorySupplyByNextTokenResponse = fbaInventoryDetailServiceMWS.InvokeListInventorySupplyByNextToken(parameter.nextToken);
                    if (listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult != null)
                    {
                        if (listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult.InventorySupplyList != null)
                        {
                            foreach (var inventorySupply in listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult.InventorySupplyList.member)
                            {
                                insertUpdateInventory(inventorySupply, parameter);
                            }
                        }
                        setParameter.SetParameterValue(parameter, listInventorySupplyByNextTokenResponse.ListInventorySupplyByNextTokenResult.NextToken);
                    }
                    else
                    {
                        setParameter.SetParameterValue(parameter, null);
                    }
                }
            } while (!string.IsNullOrEmpty(parameter.nextToken));

        }
        catch (Exception)
        {
            throw;
        }
    }


来源: stackexchange

问:
API working fine in postman but not in angular2
I have an API to send an OTP to mobile. It is working fine via PostMan but not via angular2.

I am getting this error "Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response."

Any help

Thanks in advance

答: This is a backend issue, backend developer has to write code to allow headers and allow origin for all APIs.</p>

ContentLicense: CC BY-SA 3.0


问:
How to hide form field in opencart
I am new to opencart, i want to hide Address2 From registration form.
I tried more but not working.</p>

```<code>   <div class="form-group">
        <label class="col-sm-2 control-label" for="input-address-2"><?php echo $entry_address_2; ?></label>
        <div class="col-sm-10">
          <input type="text" name="address_2" value="<?php echo $address_2; ?>" placeholder="<?php echo $entry_address_2; ?>" id="input-address-2" class="form-control" />
        </div>
      </div>
</code>```

答:
Add class hide to form-group container

```<code><div class="form-group hide">
</code>```

In that way you hide it with label.

And this way is standard for opencart templates.

Title: How to hide form field in opencart

Body:
I am new to opencart, i want to hide Address2 From registration form.
I tried more but not working.

        <?php echo $entry_address_2; ?>

          <input type="text" name="address_2" value="<?php echo $address_2; ?>" placeholder="<?php echo $entry_address_2; ?>" id="input-address-2" class="form-control" />

Body:
Add class hide to form-group container

<div class="form-group hide">

In that way you hide it with label.

And this way is standard for opencart templates.


问:
Activities not applying themes correctly on tablet
All my activities are set in AndroidManifest.xml to      android:theme="@style/AppTheme".
They apply the style correctly on phones I tested so far, however when I tested on tablets (API 21, API 23) some activities have light-grey background instead of white. The theme is Theme.AppCompat.Light.

I dealt with it by setting the white background color programmatically in my BaseActivity like so:

```<code>public void setActivityBackgroundColor(int color) {
    View view = this.getWindow().getDecorView();
    view.setBackgroundColor(color);
}
</code>```

and then calling it inside onCreate() method. I'm puzzled however at the difference in behavior in phones and tablets. I have tested on devices (pairs: phone\tablet) with the same APIs and they differ. What could be the reason?

答: Turns out I'm a bit color blind. I couldn't notice the difference on phones, but when I took some screenshots and compared the look of activities it turned out that the activities were colored the same way on phones and tablets. Still puzzled as to why some were applying AppTheme correctly and others did not. Any ideas?

Body:
All my activities are set in AndroidManifest.xml to      android:theme="@style/AppTheme".
They apply the style correctly on phones I tested so far, however when I tested on tablets (API 21, API 23) some activities have light-grey background instead of white. The theme is Theme.AppCompat.Light.

I dealt with it by setting the white background color programmatically in my BaseActivity like so:

public void setActivityBackgroundColor(int color) {
    View view = this.getWindow().getDecorView();
    view.setBackgroundColor(color);
}

and then calling it inside onCreate() method. I'm puzzled however at the difference in behavior in phones and tablets. I have tested on devices (pairs: phone\tablet) with the same APIs and they differ. What could be the reason?


问:
Brace placement after init list in C++
For anyone who places braces thus:

```<code>void f() {
    stuff();
}
</code>```

How do you prefer to place braces after long initializer lists?

The same way?

```<code>Object::Object()
    : foo(1)
    , bar(2) {
    stuff();
}
</code>```

Or make an exception so you actually see where the init list ends?

```<code>Object::Object()
    : foo(1)
    , bar(2)
{
    stuff();
}
</code>```

Or leave a blank line?

```<code>Object::Object()
    : foo(1)
    , bar(2) {

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

Or maybe make a weird hybrid?

```<code>Object::Object()
    : foo(1)
    , bar(2)
    {
    stuff();
}
</code>```

Or abuse indentation

```<code>Object::Object()
: foo(1)
, bar(2) {
    stuff();
}

Object::Object() : foo(1)
                            , bar(2) {
    stuff();
}
</code>```

In this small example all are pretty but crank a dozen initializers and a moderately long function body and this quickly changes.

答:
I put the opening brace on a new line. The result looks mostly like the 2nd example, but without the indentation of the initializers.

That said, as this seems to be the part of C++ that has the widest range of layouts in practice, personally I've gone back to initializing variables in the constructor (where still efficient) in order to avoid offending anybody.

OwnerDisplayName: Iraimbilanja

LastEditorDisplayName: Iraimbilanja

ContentLicense: CC BY-SA 2.5

Title: Brace placement after init list in C++

Body:
For anyone who places braces thus:

void f() {
    stuff();
}

How do you prefer to place braces after long initializer lists?

The same way?

Object::Object()
    : foo(1)
    , bar(2) {
    stuff();
}

Or make an exception so you actually see where the init list ends?

Object::Object()
    : foo(1)
    , bar(2)
{
    stuff();
}

Or leave a blank line?

Object::Object()
    : foo(1)
    , bar(2) {

    stuff();
}

Or maybe make a weird hybrid?

Object::Object()
    : foo(1)
    , bar(2)
    {
    stuff();
}

Or abuse indentation

Object::Object()
: foo(1)
, bar(2) {
    stuff();
}

Object::Object() : foo(1)
                            , bar(2) {
    stuff();
}

In this small example all are pretty but crank a dozen initializers and a moderately long function body and this quickly changes.

OwnerDisplayName: please delete me


问:
How do I recreate DB using EF4 code first for test
I'm using Entity Framework 4 Code First in my .net MVC 2.0 project and I'm having hard times to get my DB sync with my Entities. What I want is a page that I can call, as an exemple : /DB/Recreate, that would drop my current DB and recreate an empty one. Currently in my global.asax I have

```<code>protected override void OnApplicationStarted()
        {
            Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<CorpiqDb>());

            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
            RegisterAllControllersIn(Assembly.GetExecutingAssembly());
        }
</code>```

I try to switch my database initializer in my action but I'm realy not sure, since it should already been initialized, that I'm using the right approach :

```<code>        Database.SetInitializer(new AlwaysRecreateDatabase<CorpiqDb>());
        var bidon = _session.All<Admin>();
        Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<CorpiqDb>());
        bidon = _session.All<Admin>();
</code>```

I don'y realy know how to do this, thank you for the help!

答:
Ok I found a solution :

```<code>var dbContext = new CorpiqDb().Database ;
dbContext.Delete();
dbContext.Initialize();
dbContext.EnsureInitialized();
Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<CorpiqDb>());
</code>```

This will drop my database and create a new one that reflect the latest models, I can even seed the database with some data for my test.

Body:
I'm using Entity Framework 4 Code First in my .net MVC 2.0 project and I'm having hard times to get my DB sync with my Entities. What I want is a page that I can call, as an exemple : /DB/Recreate, that would drop my current DB and recreate an empty one. Currently in my global.asax I have

protected override void OnApplicationStarted()
        {
            Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<CorpiqDb>());

            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
            RegisterAllControllersIn(Assembly.GetExecutingAssembly());
        }

I try to switch my database initializer in my action but I'm realy not sure, since it should already been initialized, that I'm using the right approach :

        Database.SetInitializer(new AlwaysRecreateDatabase<CorpiqDb>());
        var bidon = _session.All<Admin>();
        Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<CorpiqDb>());
        bidon = _session.All<Admin>();

I don'y realy know how to do this, thank you for the help!

Body:
Ok I found a solution :

var dbContext = new CorpiqDb().Database ;
dbContext.Delete();
dbContext.Initialize();
dbContext.EnsureInitialized();
Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<CorpiqDb>());

This will drop my database and create a new one that reflect the latest models, I can even seed the database with some data for my test.


问:
Bitwise NOT of Java BigInteger is Negative
I am trying to perform a bitwise not on a 128 bit BigInteger in Java. I have a 128 bit number which has the first 64 bits set to 1 and the last 64 bits set to 0 (I am playing with IPv6 masks).

```<code>BigInteger b = new BigInteger(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(b.toString(2));
</code>```

This results in the following, if I output it using base 2:

11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

I am trying to flip/reverse all the bits using a bitwise not.

```<code>System.out.println(b.not().toString(2));
</code>```

From my understanding of a bitwise not, I was expecting all the 1's to change to 0's and all the 0's to change to 1's, but I get the following instead:

-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

This also seems to match the documentation of the not() function:

This method returns a negative value if and only if this BigInteger is non-negative

Is it a case of looping through all 128 bits and performing a bitwise not on each separate bit instead?

UPDATE
It probably helps if I try and explain what I was trying to achieve to give some context. I am manipulating IPv6 addresses and was trying to determine if a given IPv6 address was within a subnet or not based on an IPv6 mask.

Based on the responses, I think the following should work:

E.g.
Is 2001:db8:0:0:8:800:200c:417b within 2001:db8::/64?

```<code>BigInteger n = new BigInteger(1, InetAddress.getByName("2001:db8::").getAddress());
BigInteger b = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE).shiftLeft(64);

// First Address in Subnet
BigInteger first = n.and(b);

// Last Address in Subnet (this is where I was having a problem as it was returning a negative number)
BigInteger MASK_128 = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
BigInteger last = first.add(b.xor(MASK_128));

// Convert our test IP into BigInteger
BigInteger ip = new BigInteger(1, InetAddress.getByName("2001:db8:0:0:8:800:200c:417b").getAddress());

// Check if IP is >= first and <= last
if ((first.compareTo(ip) <= 0) && (last.compareTo(ip) >= 0)) {
  // in subnet
}
</code>```

答:
Use

VALUE = 0xFFFFFFFFFFFFFFFF0000000000000000 - this is patern for bit 1...10...0

VALUE = 0x0000000000000000FFFFFFFFFFFFFFFF - this is patern for bit 0...01...1

Just type by hand 16 x "F" and "0" and remember to add "0x"before each pattern.
Define this values as final.

If You want to generate such values you must do
value += 0x1;
value << 1;
For n times. In your case n is 64.

Body:
I am trying to perform a bitwise not on a 128 bit BigInteger in Java. I have a 128 bit number which has the first 64 bits set to 1 and the last 64 bits set to 0 (I am playing with IPv6 masks).

BigInteger b = new BigInteger(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(b.toString(2));

This results in the following, if I output it using base 2:

11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

I am trying to flip/reverse all the bits using a bitwise not.

System.out.println(b.not().toString(2));

From my understanding of a bitwise not, I was expecting all the 1's to change to 0's and all the 0's to change to 1's, but I get the following instead:

-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

This also seems to match the documentation of the not() function:

This method returns a negative value if and only if this BigInteger is non-negative

Is it a case of looping through all 128 bits and performing a bitwise not on each separate bit instead?

UPDATE
It probably helps if I try and explain what I was trying to achieve to give some context. I am manipulating IPv6 addresses and was trying to determine if a given IPv6 address was within a subnet or not based on an IPv6 mask.

Based on the responses, I think the following should work:

E.g.
Is 2001:db8:0:0:8:800:200c:417b within 2001:db8::/64?

BigInteger n = new BigInteger(1, InetAddress.getByName("2001:db8::").getAddress());
BigInteger b = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE).shiftLeft(64);

// First Address in Subnet
BigInteger first = n.and(b);

// Last Address in Subnet (this is where I was having a problem as it was returning a negative number)
BigInteger MASK_128 = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
BigInteger last = first.add(b.xor(MASK_128));

// Convert our test IP into BigInteger
BigInteger ip = new BigInteger(1, InetAddress.getByName("2001:db8:0:0:8:800:200c:417b").getAddress());

// Check if IP is >= first and <= last
if ((first.compareTo(ip) <= 0) && (last.compareTo(ip) >= 0)) {
  // in subnet
}


答:
Pass css property display:none in it like:

```<code><input type="text" name="address_2" style="display:none;" value="<?php echo $address_2; ?>" placeholder="<?php echo $entry_address_2; ?>" id="input-address-2" class="form-control" />
</code>```

It will hide the above input.

Title: How to hide form field in opencart

Body:
Pass css property display:none in it like:

<input type="text" name="address_2" style="display:none;" value="<?php echo $address_2; ?>" placeholder="<?php echo $entry_address_2; ?>" id="input-address-2" class="form-control" />

It will hide the above input.


问:
Change taskbar icon at runtime on deployed app
I would like to change taskbar icon to notify the user when a new message is received like outlook when you receive a new mail.

I already search solution on web and it's all about changing the window icon like this:

```<code>Uri iconUri = new Uri("Resources/envelop.ico", UriKind.Relative);
this.Icon = BitmapFrame.Create(iconUri);
</code>```

It's working well on Visual Studio but I found out that it's not changing my task bar on deployed app because it's a read-only variable. And worse it's change only the top-left attached icon that I didn't want to change anyways.

So is there a way to do it? Outlook did it and Chrome too so there must be a way.

UPDATE

To force the icon refresh on my deployed app I have to pin/unpin my icon taskbar, unfortunately this is a user command only so I can't do this in wpf programmatically without exploiting some dirty manners which would be too unstable.

Actually I'm trying to find a way to refresh Icon cache without doing it for each Windows OS or version.

答:
For me this solution was working.

Created this with code from Write text on bitmap in C#

```<code>    private Icon DrawIcon(Brush brush)
    {
        //https://stackoverflow.com/questions/6311545/c-sharp-write-text-on-bitmap
        Bitmap bmp = new Bitmap(MyNameSpace.Properties.Resources.desktop_windows_48px);

        // Create a rectangle for the entire bitmap
        RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);

        // Create graphic object that will draw onto the bitmap
        Graphics g = Graphics.FromImage(bmp);

        // The smoothing mode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing). One exception is that path gradient brushes do not obey the smoothing mode. Areas filled using a PathGradientBrush are rendered the same way (aliased) regardless of the SmoothingMode property.
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        // The interpolation mode determines how intermediate values between two endpoints are calculated.
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

        // Use this property to specify either higher quality, slower rendering, or lower quality, faster rendering of the contents of this Graphics object.
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

        // This one is important
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

        // Draw the text onto the image
        g.FillRectangle(brush, new Rectangle(2, 4, 20, 12));

        // Flush all graphics changes to the bitmap
        g.Flush();

        Bitmap temp = bmp;

        // Get an Hicon for myBitmap.
        IntPtr Hicon = temp.GetHicon();

        // Create a new icon from the handle.
        Icon newIcon = Icon.FromHandle(Hicon);

        return newIcon;
    }
</code>```

I am also using a NotifyIcon but that does not change alot for you.

```<code>_notifyIcon.Icon = DrawIcon(Brushes.Blue);
MainWindow.Icon =  Imaging.CreateBitmapSourceFromHIcon(_notifyIcon.Icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
</code>```

Lateron I change it like this (might be similar when just changing the icon source.

```<code>    private void App_StateChanged(object sender, StateChangedEventArgs e)
    {
        if(e.State == ApplicationState.Defective)
        {
            //Show window on error !
            ShowMainWindow();
            //(sender as Window).Activate();
        }
        _notifyIcon.Icon = DrawIcon(e.StateBrush);
        MainWindow.Icon = Imaging.CreateBitmapSourceFromHIcon(_notifyIcon.Icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
        _notifyIcon.Visible = true;
    }
</code>```

It looks similar to this:

Default:

On Error:

Hope this is helpful !

Body:
I would like to change taskbar icon to notify the user when a new message is received like outlook when you receive a new mail.

I already search solution on web and it's all about changing the window icon like this:

Uri iconUri = new Uri("Resources/envelop.ico", UriKind.Relative);
this.Icon = BitmapFrame.Create(iconUri);

It's working well on Visual Studio but I found out that it's not changing my task bar on deployed app because it's a read-only variable. And worse it's change only the top-left attached icon that I didn't want to change anyways.

So is there a way to do it? Outlook did it and Chrome too so there must be a way.

UPDATE

To force the icon refresh on my deployed app I have to pin/unpin my icon taskbar, unfortunately this is a user command only so I can't do this in wpf programmatically without exploiting some dirty manners which would be too unstable.

Actually I'm trying to find a way to refresh Icon cache without doing it for each Windows OS or version.

Body:
For me this solution was working.

Created this with code from Write text on bitmap in C#

    private Icon DrawIcon(Brush brush)
    {
        //https://stackoverflow.com/questions/6311545/c-sharp-write-text-on-bitmap
        Bitmap bmp = new Bitmap(MyNameSpace.Properties.Resources.desktop_windows_48px);

        // Create a rectangle for the entire bitmap
        RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);

        // Create graphic object that will draw onto the bitmap
        Graphics g = Graphics.FromImage(bmp);

        // The smoothing mode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing). One exception is that path gradient brushes do not obey the smoothing mode. Areas filled using a PathGradientBrush are rendered the same way (aliased) regardless of the SmoothingMode property.
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        // The interpolation mode determines how intermediate values between two endpoints are calculated.
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

        // Use this property to specify either higher quality, slower rendering, or lower quality, faster rendering of the contents of this Graphics object.
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

        // This one is important
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

        // Draw the text onto the image
        g.FillRectangle(brush, new Rectangle(2, 4, 20, 12));

        // Flush all graphics changes to the bitmap
        g.Flush();

        Bitmap temp = bmp;

        // Get an Hicon for myBitmap.
        IntPtr Hicon = temp.GetHicon();

        // Create a new icon from the handle.
        Icon newIcon = Icon.FromHandle(Hicon);

        return newIcon;
    }

I am also using a NotifyIcon but that does not change alot for you.

_notifyIcon.Icon = DrawIcon(Brushes.Blue);
MainWindow.Icon =  Imaging.CreateBitmapSourceFromHIcon(_notifyIcon.Icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

Lateron I change it like this (might be similar when just changing the icon source.

    private void App_StateChanged(object sender, StateChangedEventArgs e)
    {
        if(e.State == ApplicationState.Defective)
        {
            //Show window on error !
            ShowMainWindow();
            //(sender as Window).Activate();
        }
        _notifyIcon.Icon = DrawIcon(e.StateBrush);
        MainWindow.Icon = Imaging.CreateBitmapSourceFromHIcon(_notifyIcon.Icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
        _notifyIcon.Visible = true;
    }

It looks similar to this:

Default:

On Error:

Hope this is helpful !


问:
Convert hexadecimal string to Blob and display PNG image with AngularJS
I got a web page (I/m using angularjs 1.4.8) and I'm trying to show an image which comes from my GET url request.

Here is the page code (I got a grid and I/m displaying previews if they are applicable):

```<code><div ng-show="message.message == null && message.is_image != null">
    <a href="#" ng-click="downloadFile(message.id_message)">
      <img data-ng-src="data:image/{{message.image_resolution}};base64,{{message.image_preview}}"/>
    </a>
</div>
</code>```

So, I got cassandra DB with this blob field and my Json looks like:

```<code>created_date:"2017-03-31 22:05:42.284Z"
id_message:"e6e2a5cb-ec25-472f-a59b-3f16a3a8afa9"
id_user_link:"47ed65bf-5520-4901-88c8-01980ffbcd4d"
id_user_sent:"3495c2de-c93c-4323-8e48-1fcecbfde625"
image_length:174443
image_name:"5.png"
image_preview:"0x89504e470d0a1a0a0000000d49484452000007800000039a080600000079a04f28000038714944415478daecd9496e55570045d13bfff124d442c654016320c4d4219832046308a132087199c26ba4f1fed65ad29ec0e99e71ec97635392244992244992244992b4f90d23489224499
...
... some other 90 lines of symbols
...
00000108401d8006c0096244906600000000008c2006c0036004b922403300000000004610036001b802549920118000000008230001b800dc09224c9000c000000004118800dc00660499264000600000080200cc0066003b024493200030000004010066003b001589224198001000000200803b001d8002c49920cc000000000108401d8006c0096244906600000000008c2006c0036004b92a4ff95fe0ffc7d46dd1b63a2b10000000049454e44ae426082"
image_resolution:"png"
is_image:1
message:null
</code>```

But I have no images in my web page (only icon of broken link to image):

I researched

Angularjs showing image blob

Display blob image in html with angularjs

AngularJS - Show byte array content as image

but this won't help.I tried some varieties of this code:
page:

```<code><img data-ng-src="data:image/{{message.image_resolution}};base64,{{b64encoded(message.image_preview)}}"/>
</code>```

js:

```<code> $scope.b64encoded = function(image_preview){
        //btoa(String.fromCharCode.apply(null, response.data[0].ClassImage.data));
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|blob):|data:image_preview\//);
        return btoa(String.fromCharCode.apply(null, image_preview));
    }
</code>```

RESOLVED
Finally, that was not the issue about AngularJS or blob - that was a Java issue:
byte[] previewSizeByte = baos.toByteArray(); and I stored this one as blob, so, now I got a text field and my Java code looks like (I decided to use BufferedImage for preview):
String base64String = imgToBase64String(preview, fileFormat);

and

```<code>private String imgToBase64String(BufferedImage preview, String fileFormat) {
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        ImageIO.write(preview, fileFormat, Base64.getEncoder().wrap(os));
        return os.toString(StandardCharsets.ISO_8859_1.name());
    } catch (final IOException ioe) {
        throw new UncheckedIOException(ioe);
    }
}
</code>```

I really appreciate stackoverflow members for their comments and answers, they were extremely helpful

答:
It appears that the CassandraDB is sending the image data as a hexadecimal string. It would be more efficient to send it as a base64 string and it would be easier to use.

Here is a function to convert a hexadecimal string to an image/png Blob and display the image:

angular.module("myApp",[]).controller("myVm", function($scope) {
  var vm = $scope;

  var testHex =
    ["0x89504e470d0a1a0a0000000d494844520000003c00000028040300000050",
       "9584cc0000001b504c5445000000ffffff1f1f1f7f7f7f3f3f3f9f9f9f5f",
       "5f5fdfdfdfbfbfbf2cb790f6000000097048597300000ec400000ec40195",
       "2b0e1b000000b749444154388ded90cf0a83300cc63faaf5394a5defc56c",
       "ee2a0c760e2a3b0b6e3ec7c0175f5aff1e77da657ea40dcd2ff90a010efd",
       "9772a2f3f6ea4b830e121915b1a04e859999066a4b1801562dec544c3d36",
       "cc723506ac9791809538f564af54055c33f8861d76d0cacfd30efc9450c3",
       "b0e20189e28847aac5397458b7e2175d4cde4ed37252cff7d83ce367c849",
       "b56014ecf638fa28bf62cd49b7c3e9a384f86764269cbde5bf665b969230",
       "31adb25feffdd02ff50109f91bbd7897f34a0000000049454e44ae426082"]
    .join('');

  vm.hex = testHex;
  vm.imgUrl = URL.createObjectURL(toPngBlob(testHex));

  function toPngBlob(str){
    var hexStr = str.slice(2);
    var buf = new ArrayBuffer(hexStr.length/2);
    var byteBuf = new Uint8Array(buf);
    for (let i=0; i<hexStr.length; i+=2) {
      byteBuf[i/2] = parseInt(hexStr.slice(i,i+2),16);
    }
    var blob = new Blob([byteBuf], {type: "image/png"});
    return blob;
  };

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//unpkg.com/angular/angular.js"></script>

  <body ng-app="myApp" ng-controller="myVm">
    <h1>Convert hex string to PNG Blob</h1>
    {{hex}}<br>
    {{imgUrl}}<br>
    <img ng-src="{{imgUrl}}">

  </body></code>```

Body:
I got a web page (I/m using angularjs 1.4.8) and I'm trying to show an image which comes from my GET url request.

Here is the page code (I got a grid and I/m displaying previews if they are applicable):

So, I got cassandra DB with this blob field and my Json looks like:

created_date:"2017-03-31 22:05:42.284Z"
id_message:"e6e2a5cb-ec25-472f-a59b-3f16a3a8afa9"
id_user_link:"47ed65bf-5520-4901-88c8-01980ffbcd4d"
id_user_sent:"3495c2de-c93c-4323-8e48-1fcecbfde625"
image_length:174443
image_name:"5.png"
image_preview:"0x89504e470d0a1a0a0000000d49484452000007800000039a080600000079a04f28000038714944415478daecd9496e55570045d13bfff124d442c654016320c4d4219832046308a132087199c26ba4f1fed65ad29ec0e99e71ec97635392244992244992244992b4f90d23489224499
...
... some other 90 lines of symbols
...
00000108401d8006c0096244906600000000008c2006c0036004b922403300000000004610036001b802549920118000000008230001b800dc09224c9000c000000004118800dc00660499264000600000080200cc0066003b024493200030000004010066003b001589224198001000000200803b001d8002c49920cc000000000108401d8006c0096244906600000000008c2006c0036004b92a4ff95fe0ffc7d46dd1b63a2b10000000049454e44ae426082"
image_resolution:"png"
is_image:1
message:null

But I have no images in my web page (only icon of broken link to image):

I researched

Angularjs showing image blob

Display blob image in html with angularjs

AngularJS - Show byte array content as image

but this won't help.I tried some varieties of this code:
page:

js:

 $scope.b64encoded = function(image_preview){
        //btoa(String.fromCharCode.apply(null, response.data[0].ClassImage.data));
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|blob):|data:image_preview\//);
        return btoa(String.fromCharCode.apply(null, image_preview));
    }

RESOLVED
Finally, that was not the issue about AngularJS or blob - that was a Java issue:
byte[] previewSizeByte = baos.toByteArray(); and I stored this one as blob, so, now I got a text field and my Java code looks like (I decided to use BufferedImage for preview):
String base64String = imgToBase64String(preview, fileFormat);

and

private String imgToBase64String(BufferedImage preview, String fileFormat) {
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        ImageIO.write(preview, fileFormat, Base64.getEncoder().wrap(os));
        return os.toString(StandardCharsets.ISO_8859_1.name());
    } catch (final IOException ioe) {
        throw new UncheckedIOException(ioe);
    }
}

I really appreciate stackoverflow members for their comments and answers, they were extremely helpful

Body:
It appears that the CassandraDB is sending the image data as a hexadecimal string. It would be more efficient to send it as a base64 string and it would be easier to use.

Here is a function to convert a hexadecimal string to an image/png Blob and display the image:

angular.module("myApp",[]).controller("myVm", function($scope) {
  var vm = $scope;

  var testHex =
    ["0x89504e470d0a1a0a0000000d494844520000003c00000028040300000050",
       "9584cc0000001b504c5445000000ffffff1f1f1f7f7f7f3f3f3f9f9f9f5f",
       "5f5fdfdfdfbfbfbf2cb790f6000000097048597300000ec400000ec40195",
       "2b0e1b000000b749444154388ded90cf0a83300cc63faaf5394a5defc56c",
       "ee2a0c760e2a3b0b6e3ec7c0175f5aff1e77da657ea40dcd2ff90a010efd",
       "9772a2f3f6ea4b830e121915b1a04e859999066a4b1801562dec544c3d36",
       "cc723506ac9791809538f564af54055c33f8861d76d0cacfd30efc9450c3",
       "b0e20189e28847aac5397458b7e2175d4cde4ed37252cff7d83ce367c849",
       "b56014ecf638fa28bf62cd49b7c3e9a384f86764269cbde5bf665b969230",
       "31adb25feffdd02ff50109f91bbd7897f34a0000000049454e44ae426082"]
    .join('');

  vm.hex = testHex;
  vm.imgUrl = URL.createObjectURL(toPngBlob(testHex));

  function toPngBlob(str){
    var hexStr = str.slice(2);
    var buf = new ArrayBuffer(hexStr.length/2);
    var byteBuf = new Uint8Array(buf);
    for (let i=0; i<hexStr.length; i+=2) {
      byteBuf[i/2] = parseInt(hexStr.slice(i,i+2),16);
    }
    var blob = new Blob([byteBuf], {type: "image/png"});
    return blob;
  };

});

<script src="//unpkg.com/angular/angular.js"></script>

  <body ng-app="myApp" ng-controller="myVm">
    <h1>Convert hex string to PNG Blob</h1>
    {{hex}}<br>
    {{imgUrl}}<br>
    <img ng-src="{{imgUrl}}">

  </body>


问:
how to create website using Django
I have one Django App. I want to get this app on World Wide Web.
Can anyone please help me with steps.
Like Some server addition(e.g. Apache or Nginx),Configuration of server,Integrating with Django,Web Hosting,etc.

Thanks

答: If you don't want the hassle of setting up a server environment all by yourself, you can also choose a PaaS provider like Heroku which supports Django applications out of the box. Hosting will cost more, but you will save time deploying your apps. </p>

Title: how to create website using Django


问:
How can I safely reinstall Docker without removing volumes?
I have an issue with my docker installation in which DNS resolution is not working within my containers. How can I safely reinstall docker on Ubuntu 16.04 without removing existing volumes?</p>

答:
It turns out that when uninstalling docker using apt, the /var/lib/docker directory remains untouched, and the volumes will stay intact.

You can simply run apt-get remove docker-ce to uninstall docker without removing your volumes.


问:
preg_replace is processing a function as a property
I am trying to create a template system for a web site I am working on. I am trying to use preg_replace to call a function to process data that is surrounded by certain tags. For example, process('date') would return today's date, and is put in the code as $date$. I am using preg_replace to find the strings I need to modify, but I can not call the function - PHP seems to think that the function is a property instead.

This is the code I am using:

```<code>$view = preg_replace("/\$_([a-zA-Z0-9_]+)_\$/e", "$this->process('\\1')", $view);
</code>```

This is the error I get:

Notice: Undefined property: ClassName::$process in /location/ClassName.class.php on line X

I hope I explained this sufficiently. How do I get preg_replace to execute process as a method, instead of trying to display it as a property?

答: I would suggest using preg_replace_callback instead of preg_replace seeing as preg_replace_callback is designed for what you are actually trying to do. A possible issue you could be having is scope/function accessibility. If your code that is calling preg_replace doesn't have access to the function you are trying to call, then you could be getting this error since PHP can't find the function and might be defaulting to treating it as an parameter. If the function isn't in the same file as this preg_replace, try putting it there to see if it changes anything.</p>

Body:
I am trying to create a template system for a web site I am working on. I am trying to use preg_replace to call a function to process data that is surrounded by certain tags. For example, process('date') would return today's date, and is put in the code as $date$. I am using preg_replace to find the strings I need to modify, but I can not call the function - PHP seems to think that the function is a property instead.

This is the code I am using:

$view = preg_replace("/\$_([a-zA-Z0-9_]+)_\$/e", "$this->process('\\1')", $view);

This is the error I get:

Notice: Undefined property: ClassName::$process in /location/ClassName.class.php on line X

I hope I explained this sufficiently. How do I get preg_replace to execute process as a method, instead of trying to display it as a property?


问:
android JSON upload images collection dose not work
I'm trying to upload some of images after selecting it from my UploadActivity.

```<code>    public static  int count;
    private Bitmap[] thumbnails;
    private boolean[] thumbnailsselection;
    private String[] arrPath;
    private ImageAdapter imageAdapter;
    private static final int PICK_FROM_CAMERA = 1;
    ArrayList<String> IPath = new ArrayList<String>();
    public static Uri uri;
    TextView msgLoading;
    //ProgressBar pBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        msgLoading = (TextView) findViewById(R.id.msgLoading);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                final Cursor imagecursor = getImageCursor();

                GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
                imageAdapter = new ImageAdapter();
                imagegrid.setAdapter(imageAdapter);
                imagecursor.close();
                msgLoading.setVisibility(View.GONE);
            }
        },100);

        final Button uploadBtn = (Button) findViewById(R.id.uploadDONE);
        uploadBtn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                final int len = thumbnailsselection.length;
                int cnt = 0;
                String  selectImages = "";
                for (int i = 0; i < len; i++) {
                    if (thumbnailsselection[i]) {
                        cnt++;
                        selectImages = arrPath[i];
                        IPath.add(selectImages);
                    }
                }

                if (cnt == 0) {
                    Toast.makeText(getApplicationContext(),
                            "Please select at least one image",
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "You've selected Total " + cnt + " image(s).",
                            Toast.LENGTH_LONG).show();
                    Log.i("SelectedImages", String.valueOf(selectImages.toCharArray()));

                    Intent intentMessage = new Intent(UploadActivity.this,
                            ImagesForAds.class);
                    intentMessage.putStringArrayListExtra("IMAGE", IPath);
                    startActivity(intentMessage);
                }
            }
        });
    }

    @NonNull
    private Cursor getImageCursor() {
        final String[] columns = { MediaStore.Images.Media.DATA,
                MediaStore.Images.Media._ID };
        final String orderBy = MediaStore.Images.Media._ID;
        final Cursor imagecursor = managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
                null, orderBy);
        final int image_column_index = imagecursor
                .getColumnIndex(MediaStore.Images.Media._ID);
        this.count = imagecursor.getCount();
        this.thumbnails = new Bitmap[this.count];
        this.arrPath = new String[this.count];
        this.thumbnailsselection = new boolean[this.count];
        for (int i = 0; i < this.count; i++) {
            imagecursor.moveToPosition(i);
            int id = imagecursor.getInt(image_column_index);
            int dataColumnIndex = imagecursor
                    .getColumnIndex(MediaStore.Images.Media.DATA);
            thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
                    getApplicationContext().getContentResolver(), id,
                    MediaStore.Images.Thumbnails.MICRO_KIND, null);
            arrPath[i] = imagecursor.getString(dataColumnIndex);
        }
        return imagecursor;
    }

    public class ImageAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public ImageAdapter() {
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public int getCount() {
            return count;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.galleryitem, null);
                holder.imageview = (ImageView) convertView
                        .findViewById(R.id.thumbImage);
                holder.checkbox = (CheckBox) convertView
                        .findViewById(R.id.itemCheckBox);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.checkbox.setId(position);
            holder.imageview.setId(position);
            holder.checkbox.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    CheckBox cb = (CheckBox) v;
                    int id = cb.getId();
                    if (thumbnailsselection[id]) {
                        cb.setChecked(false);
                        thumbnailsselection[id] = false;
                    } else {
                        cb.setChecked(true);
                        thumbnailsselection[id] = true;
                    }
                }
            });

             holder.imageview.setOnClickListener(new View.OnClickListener() {

             public void onClick(View v) {
             // TODO Auto-generated method stub
             int id = v.getId();
             Intent intent = new Intent();
             intent.setAction(Intent.ACTION_VIEW);
             intent.setDataAndType(Uri.parse("file://" + arrPath[id]),
             "image/*");
             startActivity(intent);
             }
             });

            holder.imageview.setImageBitmap(thumbnails[position]);
            holder.checkbox.setChecked(thumbnailsselection[position]);
            holder.id = position;
            return convertView;
        }
    }

    class ViewHolder {
        ImageView imageview;
        CheckBox checkbox;
        int id;
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        Intent i = new Intent(UploadActivity.this, ImagesForAds.class);
        UploadActivity.this.finish();
        startActivity(i);
        super.onBackPressed();
    }
</code>```

and it's worked fine, I can back data to my main activity as below :

```<code>b = getIntent().getExtras();
if (b != null) {
        ImgData = b.getStringArrayList("IMAGE");
        for (int i = 0; i < ImgData.size(); i++) {
            map.add(ImgData.get(i).toString());

        }

    }
</code>```

now it's ok... I need to upload those Images that I selected, here is my asyncTask:

```<code>public class ImageUploadTask extends AsyncTask<String, Void, String> {

    String sResponse = null;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog = ProgressDialog.show(ImagesForAds.this, "Uploading",
                "Please wait...", true);
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        try {

            String url = "myLink";
            int i = Integer.parseInt(params[0]);
            Bitmap bitmap = decodeFile(map.get(i));
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            entity = new MultipartEntity();

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();

            //entity.addPart("user_id", new StringBody("199"));
            //entity.addPart("club_id", new StringBody("10"));
            entity.addPart("images", new ByteArrayBody(data,
                    "image/jpeg", params[1]));

            Log.i(TAG, "array map: " + map.get(i));

            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost,
                    localContext);
            sResponse = EntityUtils.getContentCharSet(response.getEntity());

            System.out.println("sResponse : " + sResponse);
        } catch (Exception e) {
            if (dialog.isShowing())
                dialog.dismiss();
            Log.e(e.getClass().getName(), e.getMessage(), e);

        }
        return sResponse;
    }

    @Override
    protected void onPostExecute(String sResponse) {
        try {
            if (dialog.isShowing())
                dialog.dismiss();

            if (sResponse != null) {
                Toast.makeText(getApplicationContext(),
                        sResponse + " Photo uploaded successfully",
                        Toast.LENGTH_SHORT).show();
                count++;
                if (count < map.size()) {
                    new ImageUploadTask().execute(count + "", "hm" + count
                            + ".jpg");
                }
            }

        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }

    }
}
</code>```

and here how I invoke it :

```<code>int count  = 0;
new ImageUploadTask().execute(count + "", "pk" + count + ".jpg");
</code>```

The issue with AsyncTask.. it's upload only 1 image, how I can upload all images I have selected ?

答:
This is your flaw :

```<code>        if (count < map.size()) {
            new ImageUploadTask().execute(count + "", "hm" + count
                    + ".jpg");
        }
</code>```

not a good idea to create a new ImageUploadTask inside ImageUploadTask.
move your for loop inside doInBackground() and for updating user use publishProgress() and catch that event inside onProgressUpdate.

Read more about AsyncTask : https://developer.android.com/reference/android/os/AsyncTask.html

Body:
I'm trying to upload some of images after selecting it from my UploadActivity.

    public static  int count;
    private Bitmap[] thumbnails;
    private boolean[] thumbnailsselection;
    private String[] arrPath;
    private ImageAdapter imageAdapter;
    private static final int PICK_FROM_CAMERA = 1;
    ArrayList<String> IPath = new ArrayList<String>();
    public static Uri uri;
    TextView msgLoading;
    //ProgressBar pBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        msgLoading = (TextView) findViewById(R.id.msgLoading);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                final Cursor imagecursor = getImageCursor();

                GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
                imageAdapter = new ImageAdapter();
                imagegrid.setAdapter(imageAdapter);
                imagecursor.close();
                msgLoading.setVisibility(View.GONE);
            }
        },100);

        final Button uploadBtn = (Button) findViewById(R.id.uploadDONE);
        uploadBtn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                final int len = thumbnailsselection.length;
                int cnt = 0;
                String  selectImages = "";
                for (int i = 0; i < len; i++) {
                    if (thumbnailsselection[i]) {
                        cnt++;
                        selectImages = arrPath[i];
                        IPath.add(selectImages);
                    }
                }

                if (cnt == 0) {
                    Toast.makeText(getApplicationContext(),
                            "Please select at least one image",
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "You've selected Total " + cnt + " image(s).",
                            Toast.LENGTH_LONG).show();
                    Log.i("SelectedImages", String.valueOf(selectImages.toCharArray()));

                    Intent intentMessage = new Intent(UploadActivity.this,
                            ImagesForAds.class);
                    intentMessage.putStringArrayListExtra("IMAGE", IPath);
                    startActivity(intentMessage);
                }
            }
        });
    }

    @NonNull
    private Cursor getImageCursor() {
        final String[] columns = { MediaStore.Images.Media.DATA,
                MediaStore.Images.Media._ID };
        final String orderBy = MediaStore.Images.Media._ID;
        final Cursor imagecursor = managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
                null, orderBy);
        final int image_column_index = imagecursor
                .getColumnIndex(MediaStore.Images.Media._ID);
        this.count = imagecursor.getCount();
        this.thumbnails = new Bitmap[this.count];
        this.arrPath = new String[this.count];
        this.thumbnailsselection = new boolean[this.count];
        for (int i = 0; i < this.count; i++) {
            imagecursor.moveToPosition(i);
            int id = imagecursor.getInt(image_column_index);
            int dataColumnIndex = imagecursor
                    .getColumnIndex(MediaStore.Images.Media.DATA);
            thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
                    getApplicationContext().getContentResolver(), id,
                    MediaStore.Images.Thumbnails.MICRO_KIND, null);
            arrPath[i] = imagecursor.getString(dataColumnIndex);
        }
        return imagecursor;
    }

    public class ImageAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public ImageAdapter() {
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public int getCount() {
            return count;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.galleryitem, null);
                holder.imageview = (ImageView) convertView
                        .findViewById(R.id.thumbImage);
                holder.checkbox = (CheckBox) convertView
                        .findViewById(R.id.itemCheckBox);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.checkbox.setId(position);
            holder.imageview.setId(position);
            holder.checkbox.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    CheckBox cb = (CheckBox) v;
                    int id = cb.getId();
                    if (thumbnailsselection[id]) {
                        cb.setChecked(false);
                        thumbnailsselection[id] = false;
                    } else {
                        cb.setChecked(true);
                        thumbnailsselection[id] = true;
                    }
                }
            });

             holder.imageview.setOnClickListener(new View.OnClickListener() {

             public void onClick(View v) {
             // TODO Auto-generated method stub
             int id = v.getId();
             Intent intent = new Intent();
             intent.setAction(Intent.ACTION_VIEW);
             intent.setDataAndType(Uri.parse("file://" + arrPath[id]),
             "image/*");
             startActivity(intent);
             }
             });

            holder.imageview.setImageBitmap(thumbnails[position]);
            holder.checkbox.setChecked(thumbnailsselection[position]);
            holder.id = position;
            return convertView;
        }
    }

    class ViewHolder {
        ImageView imageview;
        CheckBox checkbox;
        int id;
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        Intent i = new Intent(UploadActivity.this, ImagesForAds.class);
        UploadActivity.this.finish();
        startActivity(i);
        super.onBackPressed();
    }

and it's worked fine, I can back data to my main activity as below :

b = getIntent().getExtras();
if (b != null) {
        ImgData = b.getStringArrayList("IMAGE");
        for (int i = 0; i < ImgData.size(); i++) {
            map.add(ImgData.get(i).toString());

        }

    }

now it's ok... I need to upload those Images that I selected, here is my asyncTask:

public class ImageUploadTask extends AsyncTask<String, Void, String> {

    String sResponse = null;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog = ProgressDialog.show(ImagesForAds.this, "Uploading",
                "Please wait...", true);
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        try {

            String url = "myLink";
            int i = Integer.parseInt(params[0]);
            Bitmap bitmap = decodeFile(map.get(i));
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            entity = new MultipartEntity();

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();

            //entity.addPart("user_id", new StringBody("199"));
            //entity.addPart("club_id", new StringBody("10"));
            entity.addPart("images", new ByteArrayBody(data,
                    "image/jpeg", params[1]));

            Log.i(TAG, "array map: " + map.get(i));

            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost,
                    localContext);
            sResponse = EntityUtils.getContentCharSet(response.getEntity());

            System.out.println("sResponse : " + sResponse);
        } catch (Exception e) {
            if (dialog.isShowing())
                dialog.dismiss();
            Log.e(e.getClass().getName(), e.getMessage(), e);

        }
        return sResponse;
    }

    @Override
    protected void onPostExecute(String sResponse) {
        try {
            if (dialog.isShowing())
                dialog.dismiss();

            if (sResponse != null) {
                Toast.makeText(getApplicationContext(),
                        sResponse + " Photo uploaded successfully",
                        Toast.LENGTH_SHORT).show();
                count++;
                if (count < map.size()) {
                    new ImageUploadTask().execute(count + "", "hm" + count
                            + ".jpg");
                }
            }

        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }

    }
}

and here how I invoke it :

int count  = 0;
new ImageUploadTask().execute(count + "", "pk" + count + ".jpg");

The issue with AsyncTask.. it's upload only 1 image, how I can upload all images I have selected ?

Body:
This is your flaw :

        if (count < map.size()) {
            new ImageUploadTask().execute(count + "", "hm" + count
                    + ".jpg");
        }

not a good idea to create a new ImageUploadTask inside ImageUploadTask.
move your for loop inside doInBackground() and for updating user use publishProgress() and catch that event inside onProgressUpdate.

Read more about AsyncTask : https://developer.android.com/reference/android/os/AsyncTask.html


问:
How to view form from source code in IntelliJ IDEA
I have just started working on Java Swing project. As an IDE I am using IntelliJ IDEA from JetBrains.

In the project I can see the .java files related to GUI.

Do you know how I can view these files in GUI Designer? Or Generate output of  these files in GUI Designer in IntelliJ IDEA or any other IDE.

I googled it but couldn't find anything.

答:
If you have A swing project with a GUI in it then you should see .form files next to the class it is bound to like this: Class bound to a swing form file

Double clicking this .form should open the GUI designer. If you want to create a class with a GUI tied to it then use: Right click > New > GUI Form


问:
Using SJCL library in Angular2
In my app i would like to use "Stanford Javascript Crypto Library" which has a typing and i also see https://github.com/Evgenus/sjcl-typescript-definitions.

I dont understand how i can use it in my project. How can i use the command
sjcl.encrypt("password", "data") in my project.

i am using angular 4, angular-cli beta 2

i have run npm install --save-dev @types/sjcl

tsconfig.app.json

```<code>{
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": [ "sjcl" ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ],
  "extends": "../tsconfig.json"
}
</code>```

答:
You need to install sjcl package: npm install --save sjcl

With types (not necessary): npm install --save sjcl @types/sjcl

Then add import in your code where you want to use sjcl:

```<code>import * as sjcl from 'sjcl';
</code>```

You don't need to add sjcl into tsconfig.app.json file.

Important! Also if you look into type definitions you will see they were written for sjcl v1.0.1, last version of sjcl is 1.0.6 so you might get type errors for some functions.

Title: Using SJCL library in Angular2

Body:
In my app i would like to use "Stanford Javascript Crypto Library" which has a typing and i also see https://github.com/Evgenus/sjcl-typescript-definitions.

I dont understand how i can use it in my project. How can i use the command
sjcl.encrypt("password", "data") in my project.

i am using angular 4, angular-cli beta 2

i have run npm install --save-dev @types/sjcl

tsconfig.app.json

{
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": [ "sjcl" ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ],
  "extends": "../tsconfig.json"
}

Body:
You need to install sjcl package: npm install --save sjcl

With types (not necessary): npm install --save sjcl @types/sjcl

Then add import in your code where you want to use sjcl:

import * as sjcl from 'sjcl';

You don't need to add sjcl into tsconfig.app.json file.

Important! Also if you look into type definitions you will see they were written for sjcl v1.0.1, last version of sjcl is 1.0.6 so you might get type errors for some functions.


问:
Open file from documents on Android Nougat
I'm using file helper class from this post https://stackoverflow.com/a/20559175/2281821 but it doesn't working properly in each case. I'm using Intent chooseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT); to start file picker. I have Android Nougat and I'm receiving from onActivityResult uri: content://com.android.externalstorage.documents/document/home%3Aimage.png
What does this home: means? How can I get access to this file? I was trying with Environment.getExternalStorageDirectory() and System.getenv("EXTERNAL_STORAGE") but I can't get acess.

答:
Following code can be used to get document path:

```<code>Intent galleryIntent = new Intent();
        galleryIntent .setType("image/*");
        galleryIntent .setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(galleryIntent , getString(R.string.app_name)),REQUEST_CODE);
</code>```

OnActivityResult():

```<code>@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                Uri uri  = data.getData();
            }
        }

    }
</code>```

You can use "uri" variable value to get bitmap. If you want to open document other image also then remove following line:

```<code>galleryIntent .setType("image/*");
</code>```

Body:
Following code can be used to get document path:

Intent galleryIntent = new Intent();
        galleryIntent .setType("image/*");
        galleryIntent .setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(galleryIntent , getString(R.string.app_name)),REQUEST_CODE);

OnActivityResult():

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                Uri uri  = data.getData();
            }
        }

    }

You can use "uri" variable value to get bitmap. If you want to open document other image also then remove following line:

galleryIntent .setType("image/*");


问:
SharePoint list template repackaged, forms now unavailable ("cannot get ghost document")
I had a SharePoint solution with a number of features packaged inside.  I can't list them here, but it looked something like this:

Features (Scope):

(Site) MyDocument Content Type

(Site) Log List Item Content Type

(Site) Task List Item Content Type

(Web) MyDocument List Template

(Web) MyDocument List Instance

(Web) Log List Template

(Web) Log List Instance

(Web) Task List Template

(Web) Task List Instance

These features have been deployed already, but for business reasons, I had to repackage these items.  In doing so, I combined some of these features, and the new list looks something like this

New Features:

(Site) Content Types (MyDocument, Log List Item, Task List Item)

*(Web) MyDocument List Template & Instance

*(Web) Log List Template & Instance

*(Web) Task List Template & Instance

(Web) Custom Lists Rollup Feature

The asterisk (*) indicates a hidden feature.  Now, in order to update my features, I had to retract the old solution and deploy the new one.  In doing so, the list instances became broken because the list templates' owning features were no longer installed.  I changed the feature IDs of the list features in the new solution to match the IDs of the ones in the old solution so the existing list instances would work again.  That seemed to just fine....BUT: the view forms for the list instances no longer work.  When I browse to the URL of the AllItems.aspx form, for example, SharePoint gives me a 404 error.  I've tried to open the file in SharePoint Designer, and get a SOAP error indicating the file no longer exists (although SPD shows it in the tree hierarchy on the left).

As far as I can tell, the only indication from SharePoint regarding what might be wrong is an entry in the log file reading like this:

Cannot get ghost document: Features\MyDocumentListTemplate\MyDocumentListTemplate\AllItems.aspx

I'm suspicious of the changed feature IDs, but I really am at a bit of a loss as to what might have happened to make these forms disappear.

Anyone else have an idea?

答:
Looks similar to SharePoint deployment, ghosted file returns 404 and http://johnnliu.spaces.live.com/blog/cns!90A843AB92E99F!446.entry.

Check all your paths first in your feature to make sure they're correct. After that, I'd try deactivating your feature, making sure in SharePoint designer that there aren't any orphaned files from your feature lying around (deleting them if there are), and then reactivating.


问:
Maintain cookbook version for internal use
What is the best approach to maintain cookbook version for internal use - this is not public cookbooks.

With every new provision increase cookbook version - in that case new stuff are applied to the node

Work with single version of cookbook - on new provision delete the previous version and upload again. When there are same major features - then increase the version.

答: Follow semver and treat all cookbooks same way (public, private). It's just a good habit. Internal cookbooks may require rollback (sometimes) and proper version management as well as public ones. I don't see any reason for having single version except extreme laziness.</p>


问:
Forward to a servlet from another servlet or from a filter
Usually I forward to a jsp or to a mapped URL from a servlet, and internet is full of such examples. But I need to forward a request to an internal servlet. For example by using its full class name, without mapping that servlet to an URL. How to forward a request to an internal servlet from another servlet, or from a filter?</p>

答:
The method you want is RequestDispatcher   getNamedDispatcher(String name); that  returns a RequestDispatcher object that acts as a wrapper for the named servlet.

And the javadoc for ServletConfig.getServletName() says:

The name may be provided via server administration, assigned in the web application deployment descriptor, or for an unregistered (and thus unnamed) servlet instance it will be the servlet's class name.

You you just have to do:

```<code>getServletContext().getNamedDispatcher("full.class.name.for.new.servlet");
</code>```

Body:
The method you want is RequestDispatcher   getNamedDispatcher(String name); that  returns a RequestDispatcher object that acts as a wrapper for the named servlet.

And the javadoc for ServletConfig.getServletName() says:

The name may be provided via server administration, assigned in the web application deployment descriptor, or for an unregistered (and thus unnamed) servlet instance it will be the servlet's class name.

You you just have to do:

getServletContext().getNamedDispatcher("full.class.name.for.new.servlet");


问:
Server Disconnected due to error: Timeout
I am having issue when using matchmaker whereby my client kicked off the server approximately 50sec and every time got an error:

Server client disconnect error:1 UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate() OnDisconnectError error:6 UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()

When I googled someone said upgrade to 5.4.2p3 version doing so, I got the below error:

Server Disconnected due to error: Timeout UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()

I have seen so many links regarding this error but no one put correct solution to overcome this issue  Could anyone help me to figure out this issue.

答: It is possible that there is something else hosting on that same port which is overriding your server. Try changing your server port.</p>


问:
Syntax error in the second input onwards lex and yacc
I have a lex and yacc file to generate the abstract syntax tree for a given input. It works fine for the first lex input and then shows a yyerror() syntax error for the second input. (The input is right)

```<code>%{
    #include<stdio.h>
    #include<math.h>
    #include<string.h>
    int yylex(void);
    #include "y.tab.h"
    struct tree
    {
        char *val;
        struct tree* left;
        struct tree* right;
    };
    struct tree* make(struct tree* left, char * , struct tree* right);
    void display(struct tree* );
%}

%union
{
    struct tree * node;
    char * sexy;
}

%token<sexy> INTEGER
%type<node> expr
%type<node> term
%type<sexy> factor

%%
line :
    expr '\n' {display($1);}
    | '\n'

expr :
    expr '+' term { $$ = make($1,"+",$3);}
    | expr '-' term { $$ = make($1,"-",$3);}
    | term { $$ = $1; }

term :
    term '*' factor { $$ = make($1,"*",$3);}
    | term '/' factor{ $$ = make($1,"/",$3);}
    | factor { $$ = $1 ;}

factor :
    '(' expr ')'  { $$ = $2; }
    | INTEGER { $$ = make(NULL,$1,NULL);}
%%

struct tree* make (struct tree* lft, char * value , struct tree* rght)
{
    struct tree *temp=(struct tree*)malloc(sizeof(struct tree));
    char *str = malloc(strlen(value)+1);
    strcpy(str,value);
    temp->val=str;
    temp->right=rght;
    temp->left=lft;
    return (temp);
}

void display(struct tree * dis)
{
    int i;
    printf("Current node is : %s\n",dis->val);
    if(dis->left)
        printf("Left child is : %s\n",dis->left->val);
    if(dis->right)
        printf("Right child is : %s\n\n",dis->right->val);
    if(dis->left)
        display(dis->left);
    else
        printf("Left child is empty\n");
    if(dis->right)
        display(dis->right);
    else
        printf("Right child is empty\n\n");
}
</code>```

Lex code given below

```<code>%{
        #include<stdio.h>
        #include "y.tab.h"
        int number=0,i=0;
    %}
    digit [0-9]
    letter [a-zA-z]
    id {letter}({letter}|{digit})*

    %%
    {digit}+ {yylval.sexy = yytext; return INTEGER;}
    [+-/*] {return *yytext;}
    "(" {return *yytext;}
    ")" {return *yytext;}
    \n {return *yytext;}
    %%

    void yyerror(char *str)
    {
     fprintf(stderr, "%s\n", str);
    }

    int main()
    {
        yyparse();
        return(0);
    }
</code>```

答:
Add another grammar rule in YACC to accommodate multiple input lines</p>

```<code>program :
    line program
    | line
</code>```

Body:
I have a lex and yacc file to generate the abstract syntax tree for a given input. It works fine for the first lex input and then shows a yyerror() syntax error for the second input. (The input is right)

%{
    #include<stdio.h>
    #include<math.h>
    #include<string.h>
    int yylex(void);
    #include "y.tab.h"
    struct tree
    {
        char *val;
        struct tree* left;
        struct tree* right;
    };
    struct tree* make(struct tree* left, char * , struct tree* right);
    void display(struct tree* );
%}

%union
{
    struct tree * node;
    char * sexy;
}

%token<sexy> INTEGER
%type<node> expr
%type<node> term
%type<sexy> factor

%%
line :
    expr '\n' {display($1);}
    | '\n'

expr :
    expr '+' term { $$ = make($1,"+",$3);}
    | expr '-' term { $$ = make($1,"-",$3);}
    | term { $$ = $1; }

term :
    term '*' factor { $$ = make($1,"*",$3);}
    | term '/' factor{ $$ = make($1,"/",$3);}
    | factor { $$ = $1 ;}

factor :
    '(' expr ')'  { $$ = $2; }
    | INTEGER { $$ = make(NULL,$1,NULL);}
%%

struct tree* make (struct tree* lft, char * value , struct tree* rght)
{
    struct tree *temp=(struct tree*)malloc(sizeof(struct tree));
    char *str = malloc(strlen(value)+1);
    strcpy(str,value);
    temp->val=str;
    temp->right=rght;
    temp->left=lft;
    return (temp);
}

void display(struct tree * dis)
{
    int i;
    printf("Current node is : %s\n",dis->val);
    if(dis->left)
        printf("Left child is : %s\n",dis->left->val);
    if(dis->right)
        printf("Right child is : %s\n\n",dis->right->val);
    if(dis->left)
        display(dis->left);
    else
        printf("Left child is empty\n");
    if(dis->right)
        display(dis->right);
    else
        printf("Right child is empty\n\n");
}

Lex code given below

%{
        #include<stdio.h>
        #include "y.tab.h"
        int number=0,i=0;
    %}
    digit [0-9]
    letter [a-zA-z]
    id {letter}({letter}|{digit})*

    %%
    {digit}+ {yylval.sexy = yytext; return INTEGER;}
    [+-/*] {return *yytext;}
    "(" {return *yytext;}
    ")" {return *yytext;}
    \n {return *yytext;}
    %%

    void yyerror(char *str)
    {
     fprintf(stderr, "%s\n", str);
    }

    int main()
    {
        yyparse();
        return(0);
    }

Body:
Add another grammar rule in YACC to accommodate multiple input lines

program :
    line program
    | line


问:
How to hide form field in opencart
I am new to opencart, i want to hide Address2 From registration form.
I tried more but not working.</p>

```<code>   <div class="form-group">
        <label class="col-sm-2 control-label" for="input-address-2"><?php echo $entry_address_2; ?></label>
        <div class="col-sm-10">
          <input type="text" name="address_2" value="<?php echo $address_2; ?>" placeholder="<?php echo $entry_address_2; ?>" id="input-address-2" class="form-control" />
        </div>
      </div>
</code>```

答:
```<code><div class="form-group" style="display:none;">
    <label class="col-sm-2 control-label" for="input-address-2"><?php echo $entry_address_2; ?></label>
    <div class="col-sm-10">
      <input type="text" name="address_2" value="<?php echo $address_2; ?>" placeholder="<?php echo $entry_address_2; ?>" id="input-address-2" class="form-control" />
    </div>
  </div>
</code>```

you can write display:none; in your div.

Title: How to hide form field in opencart

Body:
I am new to opencart, i want to hide Address2 From registration form.
I tried more but not working.

        <?php echo $entry_address_2; ?>

          <input type="text" name="address_2" value="<?php echo $address_2; ?>" placeholder="<?php echo $entry_address_2; ?>" id="input-address-2" class="form-control" />

Body:
<div class="form-group" style="display:none;">
    <label class="col-sm-2 control-label" for="input-address-2"><?php echo $entry_address_2; ?></label>
    <div class="col-sm-10">
      <input type="text" name="address_2" value="<?php echo $address_2; ?>" placeholder="<?php echo $entry_address_2; ?>" id="input-address-2" class="form-control" />
    </div>
  </div>

you can write display:none; in your div.


问:
VBA identify first and last rows with data
I want first and last rows with non-blank cells.
My last row works fine, the first row is bust. Suggestions appreciated.</p>

```<code>Sub idDataRange()

Dim firstRow As Long
Dim lastRow As Long

Sheets("fileNames").Select

' this has been adapted from a Stack overflow answer. lastRow unedited
' first row I changed Up to Down = NOT the solution!
With ActiveSheet
    firstRow = .Range("B" & .Rows.Count).End(xlDown).row
    lastRow = .Range("B" & .Rows.Count).End(xlUp).row
    End With

    MsgBox "the first row is " & firstRow
    MsgBox "last row is " & lastRow

End Sub
</code>```

答:
Using Find:

Edit:  Doesn't appear to find the first cell if it's A1.

       I've added .Cells(.Rows.Count, .Columns.Count) to the two Find rows.  It will still muck up if the last cell on the sheet is populated - but in 19 years I've never filled an entire sheet with data.

```<code>Sub test()

    Dim rLastCell As Range

    MsgBox LastCell(Sheet1).Address 'Last Cell
    MsgBox LastCell(Sheet1, 1).Address 'First Cell.

End Sub

'---------------------------------------------------------------------------------------
' Arguments : Direction = 2 :Find Last Cell, 1 :Find First Cell
'---------------------------------------------------------------------------------------
Public Function LastCell(wrkSht As Worksheet, Optional Direction As Long = 2) As Range

    Dim lLastCol As Long, lLastRow As Long

    On Error Resume Next

    With wrkSht
        lLastCol = .Cells.Find("*", .Cells(.Rows.Count, .Columns.Count), , , xlByColumns, Direction).Column
        lLastRow = .Cells.Find("*", .Cells(.Rows.Count, .Columns.Count), , , xlByRows, Direction).Row

        If lLastCol = 0 Then lLastCol = 1
        If lLastRow = 0 Then lLastRow = 1

        Set LastCell = wrkSht.Cells(lLastRow, lLastCol)
    End With
    On Error GoTo 0

End Function
</code>```

Body:
I want first and last rows with non-blank cells.
My last row works fine, the first row is bust. Suggestions appreciated.

Sub idDataRange()

Dim firstRow As Long
Dim lastRow As Long

Sheets("fileNames").Select

' this has been adapted from a Stack overflow answer. lastRow unedited
' first row I changed Up to Down = NOT the solution!
With ActiveSheet
    firstRow = .Range("B" & .Rows.Count).End(xlDown).row
    lastRow = .Range("B" & .Rows.Count).End(xlUp).row
    End With

    MsgBox "the first row is " & firstRow
    MsgBox "last row is " & lastRow

End Sub

Body:
Using Find:

Edit:  Doesn't appear to find the first cell if it's A1.

       I've added .Cells(.Rows.Count, .Columns.Count) to the two Find rows.  It will still muck up if the last cell on the sheet is populated - but in 19 years I've never filled an entire sheet with data.

Sub test()

    Dim rLastCell As Range

    MsgBox LastCell(Sheet1).Address 'Last Cell
    MsgBox LastCell(Sheet1, 1).Address 'First Cell.

End Sub

'---------------------------------------------------------------------------------------
' Arguments : Direction = 2 :Find Last Cell, 1 :Find First Cell
'---------------------------------------------------------------------------------------
Public Function LastCell(wrkSht As Worksheet, Optional Direction As Long = 2) As Range

    Dim lLastCol As Long, lLastRow As Long

    On Error Resume Next

    With wrkSht
        lLastCol = .Cells.Find("*", .Cells(.Rows.Count, .Columns.Count), , , xlByColumns, Direction).Column
        lLastRow = .Cells.Find("*", .Cells(.Rows.Count, .Columns.Count), , , xlByRows, Direction).Row

        If lLastCol = 0 Then lLastCol = 1
        If lLastRow = 0 Then lLastRow = 1

        Set LastCell = wrkSht.Cells(lLastRow, lLastCol)
    End With
    On Error GoTo 0

End Function


问:
Remove special characters in excel vba
I am using this function to remove all supposed special character but still few special characters like "Ø" or "é" and all similar characters are still there How to handle this also in below given function.

What is in my mind is that to also create a string of those special characters like MyStr and to remove them.

Please suggest.

```<code> Function ReplaceSplChars(TempStr As String) As String

Dim counter As Long, Position As Long
Dim MyStr As String, SplStr As String

MyStr = " 1234567890abcdefghijklmnopqrstuvwxyz.@"
Position = 1

For counter = 1 To Len(TempStr)
    SplStr = Mid(LCase(TempStr), Position, 1)

    If Not InStr(MyStr, SplStr) > 0 Then

        If SplStr = "-" Or SplStr = "_" Or SplStr = "'" Or SplStr = "/" Or SplStr = "," Then
            TempStr = Replace(TempStr, SplStr, " ", , 1)
            SplCharCount = SplCharCount + 1
            Position = Position + 1
        Else
            TempStr = Replace(TempStr, SplStr, "", , 1)
            SplCharCount = SplCharCount + 1
        End If
    Else
       Position = Position + 1
    End If

Next counter
ReplaceSplChars = TempStr
 End Function
</code>```

答:
A rexp takes the hard work out of it.

test the code

```<code>Sub EddieBetts()
MsgBox ReplaceSplChars(" 12345Ø67890abcdefghijklmnopqrstéuvwxyz.@")
End Sub
</code>```

Pattern below excludes anything that is not

alphanumeric (\w)

space (\s)

@

code

```<code> Function ReplaceSplChars(strIn As String) As String
 Dim objRegex As Object
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
        .Pattern = "[^\w\s@]+"
        .Global = True
    ReplaceSplChars = Application.Trim(.Replace(strIn, vbNullString))
    End With
 End Function
</code>```

Title: Remove special characters in excel vba

Body:
I am using this function to remove all supposed special character but still few special characters like "Ø" or "é" and all similar characters are still there How to handle this also in below given function.

What is in my mind is that to also create a string of those special characters like MyStr and to remove them.

Please suggest.

 Function ReplaceSplChars(TempStr As String) As String

Dim counter As Long, Position As Long
Dim MyStr As String, SplStr As String

MyStr = " 1234567890abcdefghijklmnopqrstuvwxyz.@"
Position = 1

For counter = 1 To Len(TempStr)
    SplStr = Mid(LCase(TempStr), Position, 1)

    If Not InStr(MyStr, SplStr) > 0 Then

        If SplStr = "-" Or SplStr = "_" Or SplStr = "'" Or SplStr = "/" Or SplStr = "," Then
            TempStr = Replace(TempStr, SplStr, " ", , 1)
            SplCharCount = SplCharCount + 1
            Position = Position + 1
        Else
            TempStr = Replace(TempStr, SplStr, "", , 1)
            SplCharCount = SplCharCount + 1
        End If
    Else
       Position = Position + 1
    End If

Next counter
ReplaceSplChars = TempStr
 End Function

Body:
A rexp takes the hard work out of it.

test the code

Sub EddieBetts()
MsgBox ReplaceSplChars(" 12345Ø67890abcdefghijklmnopqrstéuvwxyz.@")
End Sub

Pattern below excludes anything that is not

alphanumeric (\w)

space (\s)

@

code

 Function ReplaceSplChars(strIn As String) As String
 Dim objRegex As Object
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
        .Pattern = "[^\w\s@]+"
        .Global = True
    ReplaceSplChars = Application.Trim(.Replace(strIn, vbNullString))
    End With
 End Function