问:
Using self.rect.centerx in pygame to move character at random
Currently I cannot get the chracater to move with each iteration of the if statement like he should. Every second the character should move 100 pixels but just moves once at the beginning of the cycle. When I include the statement self.rect.centerx = (WIDTH*3/4) the character doesn't move at all from his postion. When I don't include self.rect.centerx = (WIDTH*3/4) the chracter jumps to the other side of the screen. I cannot move my rect statement around much or I will get an error saying rect is not an attribute of TRUMP class. Please advise.  </p>

```<code>class TRUMP(pg.sprite.Sprite):
    def __init__(self, game):
    pg.sprite.Sprite.__init__(self)
    self.game = game
    self.current_frame2 = 0
    self.last_update2 = 0
    self.load_images()
    self.update()
    self.image = self.TRUMP_fingers_l

    self.rect = self.image.get_rect()
    self.rect.center = (WIDTH *3/4), (589)
    self.rect.centerx = (WIDTH*3/4)
    self.rect.centery = 589
    self.pos = vec((WIDTH/2), (HEIGHT/2))
    self.vel = vec(0, 0)
    self.acc = vec(0, 0)

    self.screen = pg.display.set_mode((WIDTH, HEIGHT))
    self.clock = pg.time.Clock()

 def update(self):
    now = pg.time.get_ticks()
    if now - self.last_update2 > 1000:
    self.last_update2 = now
    self.current_frame2 = (self.current_frame2 + 1) % len(self.TRUMP_walk_cycle)
    self.image = self.TRUMP_walk_cycle[self.current_frame2]
    self.rect = self.image.get_rect()
    self.rect.centerx = (WIDTH*3/4)
    self.rect.centerx -= 100
    print(self.rect.centerx)
    self.rect.centery = 589
</code>```

答:
You're creating a new rect at 0, 0 (self.rect = self.image.get_rect()) and then use the exact same values to change it's position every update. What you can do is use the previous rect's position, initialize the new rect and then increment the position. Like so:

```<code>def update(self):
    now = pygame.time.get_ticks()
    if now - self.last_update > 250:
        self.last_update = now
        self.current_frame = (self.current_frame + 1) % len(self.TRUMP_walk_cycle)
        self.image = self.TRUMP_walk_cycle[self.current_frame]
        self.rect = self.image.get_rect(center=self.rect.center)
        self.rect.centerx -= 30
</code>```

If your images are the same sizes you don't even have to create a new rectangle. You could just use your old:

```<code>def update(self):
    now = pygame.time.get_ticks()
    if now - self.last_update > 250:
        self.last_update = now
        self.current_frame = (self.current_frame + 1) % len(self.TRUMP_walk_cycle)
        self.image = self.TRUMP_walk_cycle[self.current_frame]
        self.rect.centerx -= 30
</code>```

Body:
Currently I cannot get the chracater to move with each iteration of the if statement like he should. Every second the character should move 100 pixels but just moves once at the beginning of the cycle. When I include the statement self.rect.centerx = (WIDTH*3/4) the character doesn't move at all from his postion. When I don't include self.rect.centerx = (WIDTH*3/4) the chracter jumps to the other side of the screen. I cannot move my rect statement around much or I will get an error saying rect is not an attribute of TRUMP class. Please advise.

class TRUMP(pg.sprite.Sprite):
    def __init__(self, game):
    pg.sprite.Sprite.__init__(self)
    self.game = game
    self.current_frame2 = 0
    self.last_update2 = 0
    self.load_images()
    self.update()
    self.image = self.TRUMP_fingers_l

    self.rect = self.image.get_rect()
    self.rect.center = (WIDTH *3/4), (589)
    self.rect.centerx = (WIDTH*3/4)
    self.rect.centery = 589
    self.pos = vec((WIDTH/2), (HEIGHT/2))
    self.vel = vec(0, 0)
    self.acc = vec(0, 0)

    self.screen = pg.display.set_mode((WIDTH, HEIGHT))
    self.clock = pg.time.Clock()

 def update(self):
    now = pg.time.get_ticks()
    if now - self.last_update2 > 1000:
    self.last_update2 = now
    self.current_frame2 = (self.current_frame2 + 1) % len(self.TRUMP_walk_cycle)
    self.image = self.TRUMP_walk_cycle[self.current_frame2]
    self.rect = self.image.get_rect()
    self.rect.centerx = (WIDTH*3/4)
    self.rect.centerx -= 100
    print(self.rect.centerx)
    self.rect.centery = 589

Body:
You're creating a new rect at 0, 0 (self.rect = self.image.get_rect()) and then use the exact same values to change it's position every update. What you can do is use the previous rect's position, initialize the new rect and then increment the position. Like so:

def update(self):
    now = pygame.time.get_ticks()
    if now - self.last_update > 250:
        self.last_update = now
        self.current_frame = (self.current_frame + 1) % len(self.TRUMP_walk_cycle)
        self.image = self.TRUMP_walk_cycle[self.current_frame]
        self.rect = self.image.get_rect(center=self.rect.center)
        self.rect.centerx -= 30

If your images are the same sizes you don't even have to create a new rectangle. You could just use your old:

def update(self):
    now = pygame.time.get_ticks()
    if now - self.last_update > 250:
        self.last_update = now
        self.current_frame = (self.current_frame + 1) % len(self.TRUMP_walk_cycle)
        self.image = self.TRUMP_walk_cycle[self.current_frame]
        self.rect.centerx -= 30


来源: stackexchange

问:
Easy way to filter elements from a collection in Java?
I want to write a method that removes all elements from a collection that follow a certain pattern. In functional languages, I would use filter() with a lambda expression. However, in Java, it seems I'm stuck with this:

```<code>public void removeAllBlueCars() {
    LinkedList<Car> carsToRemove = new LinkedList<Car>();
    for (Car c : cars) {
        if (c.getCarColor() == Color.BLUE) {
            carsToRemove.add(c);
        }
    }
    cars.removeAll(carsToRemove );
}
</code>```

Removing elements directly causes a ConcurrentModificationException. Is there a better way to do this without resorting to Google Collections?

答:
Here is the Android way to implement a generic solution for this:

Usage:

Remove all null strings from my list

```<code>    LinkedList<String> list = ...
    ListUtils.filter(list, new ListUtils.Filter<String>() {
        @Override
        public boolean keepItem(String item) {
            return item != null;
        }
    });
</code>```

Source:

```<code>public class ListUtils {
    public interface Filter<T>{
        boolean keepItem(T item);
    }

    public static <T> void filter(@NonNull List<T> items, @NonNull Filter<T> filter) {
        for (Iterator<T> iterator = items.iterator(); iterator.hasNext();){
            if(!filter.keepItem(iterator.next())){
                iterator.remove();
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to write a method that removes all elements from a collection that follow a certain pattern. In functional languages, I would use filter() with a lambda expression. However, in Java, it seems I'm stuck with this:

public void removeAllBlueCars() {
    LinkedList<Car> carsToRemove = new LinkedList<Car>();
    for (Car c : cars) {
        if (c.getCarColor() == Color.BLUE) {
            carsToRemove.add(c);
        }
    }
    cars.removeAll(carsToRemove );
}

Removing elements directly causes a ConcurrentModificationException. Is there a better way to do this without resorting to Google Collections?

Body:
Here is the Android way to implement a generic solution for this:

Usage:

Remove all null strings from my list

    LinkedList<String> list = ...
    ListUtils.filter(list, new ListUtils.Filter<String>() {
        @Override
        public boolean keepItem(String item) {
            return item != null;
        }
    });

Source:

public class ListUtils {
    public interface Filter<T>{
        boolean keepItem(T item);
    }

    public static <T> void filter(@NonNull List<T> items, @NonNull Filter<T> filter) {
        for (Iterator<T> iterator = items.iterator(); iterator.hasNext();){
            if(!filter.keepItem(iterator.next())){
                iterator.remove();
            }
        }
    }
}

ContentLicense: CC BY-SA 3.0


问:
JSON object map to another JSON object to alternative key names
I have a web service that accept JSON in a specific format. However, I'm given a JSON of values but with different key names.

I know it's inefficient at the moment since it's just simply projecting data from one to another.

All I need to do is convert this:

```<code>var json1 = { key1: "Value1", key2: "Value2", key3: "Value3" };
</code>```

to

```<code>var json2 = { state: "Value1", city: "Value2, zipcode: "Value3" };
</code>```

I looked into $.map but I'm not really sure how to use it in this case.

答:
You can use "map":</p>

```<code>json2 = json1.map( (address) => {
            return {
                state: address.key1,
                city: address.key2,
                zip: address.key3
            }
        });
</code>```

Body:
I have a web service that accept JSON in a specific format. However, I'm given a JSON of values but with different key names.

I know it's inefficient at the moment since it's just simply projecting data from one to another.

All I need to do is convert this:

var json1 = { key1: "Value1", key2: "Value2", key3: "Value3" };

to

var json2 = { state: "Value1", city: "Value2, zipcode: "Value3" };

I looked into $.map but I'm not really sure how to use it in this case.

Body:
You can use "map":

json2 = json1.map( (address) => {
            return {
                state: address.key1,
                city: address.key2,
                zip: address.key3
            }
        });


问:
Cannot view code coverage on angular-cli new project
I'm trying to figure out how to get code coverage working with @angular/cli but so far i'm not having much luck.

I started a new project using angular CLI. Basically all i did was ng new test-coverage and once everything was installed in my new project folder, I did a ng test --code-coverage. The tests were run successfully but nothing resembling code coverage was displayed in the browser.

Am I missing some dependencies or something else? Any help will be appreciated.

EDIT:
R. Richards and Rachid Oussanaa were right, the file does get generated and I can access it by opening the index.html.

Now i'm wondering, is there a way I could integrate that into a node command so that the file opens right after the tests are run?

答:
here's what you can do:

install opn-cli which is a cli for the popular  opn package which is a cross-platform tool used to open files in their default apps.

npm install -D opn-cli   -D to install as dev dependency.

in package.json add a script under scripts as follows

```<code>"scripts": {
    ...
    "test-coverage": "ng test --code-coverage --single-run && opn ./coverage/index.html"
}
</code>```

now run npm run test-coverage
this will run the script we defined. here is an explanation of that script:

ng test --code-coverage --single-run will run tests, with coverage, only ONCE, hence --single-run

&& basically executes the second command if the first succeeds

opn ./coverage/index.html will open the file regardless of platform.

Body:
here's what you can do:

install opn-cli which is a cli for the popular  opn package which is a cross-platform tool used to open files in their default apps.

npm install -D opn-cli   -D to install as dev dependency.

in package.json add a script under scripts as follows

"scripts": {
    ...
    "test-coverage": "ng test --code-coverage --single-run && opn ./coverage/index.html"
}

now run npm run test-coverage
this will run the script we defined. here is an explanation of that script:

ng test --code-coverage --single-run will run tests, with coverage, only ONCE, hence --single-run

&& basically executes the second command if the first succeeds

opn ./coverage/index.html will open the file regardless of platform.


问:
Execute a for loop in parallel instead of sequential order when underlying method returns void
I have a class in which my add method is being called by multiple threads to populate clientidToTimestampHolder LinkedBlockingQueue. And then in the same below class, I start a background thread which runs every 30 milliseconds and calls a processData() method which drains clientidToTimestampHolder to List of Map and then I iterate that List to send data to different service by calling appropriate method.

I can get same userid many times with different timestamp so that is why I am using LinkedBlockingQueue with map.

```<code>public class Handler {
  private final ScheduledExecutorService executorService = Executors
      .newSingleThreadScheduledExecutor();
  private final LinkedBlockingQueue<Map.Entry<String, Long>> clientidToTimestampHolder =
      new LinkedBlockingQueue<>();

  private static class Holder {
    private static final Handler INSTANCE = new Handler();
  }

  public static Handler getInstance() {
    return Holder.INSTANCE;
  }

  private Handler() {
    executorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        processData();
      }
    }, 0, 30, TimeUnit.MILLISECONDS);
  }

  // called by multiple threads to populate clientidToTimestampHolder map
  public void add(final String clientid, final Long timestamp) {
    clientidToTimestampHolder.offer(Maps.immutableEntry(clientid, timestamp));
  }

  // called by single background thread every 30 milliseconds
  public void processData() {
    final List<Map.Entry<String, Long>> entries = new ArrayList<>();
    clientidToTimestampHolder.drainTo(entries);
    for (Map.Entry<String, Long> entry : entries) {
      String clientid = entry.getKey();
      long timestamp = entry.getValue();
      boolean isUpdated = isUpdatedClient(clientid, timestamp);
      if (!isUpdated) {
        updateClient(String.valueOf(clientid));
      }
    }
  }
}
</code>```

Is my above code thread safe and there is no race condition? Since add method will be called from multiple threads and then I have a single background thread which runs every 30 milliseconds to calls processData() method which extracts data from clientidToTimestampHolder LinkedBlockingQueue.

Because right now it looks like under heavy load, my processData() method might be missing few entries which got added through add method. I added few logs in my add method which printed out the clientid but somehow that same clientid didn't got printed out in the logs I added in isUpdatedClient method so making it suspicious to me somehow.

I am working with Java 7.

答:
I would do it in the following way:

Create a Class which incapsulates some data which you need to process. And the logic of processing. In this case it may be like a ClientProcessor class with Client field

I don't see why you need some 3rd party executor implementations, so I'll use Java Executors. However, with another implementations approach will be similar.

Create needed amount of ClientProcessor objects by reading them from source / using some factory -> and submit these tasks to the executor.

Below is a simple example:

```<code>public class Client {
    private String id;
    private String timeStamp;

    public Client(String id, String timeStamp) {
        this.id = id;
        this.timeStamp = timeStamp;
    }

    public String getId() {
        return id;
    }

    public String getTimeStamp() {
        return timeStamp;
    }
}
</code>```

ClientProcessor:

```<code>public class ClientProcessor implements Runnable{

    private Client client;

    public ClientProcessor(Client client) {
        super();
        this.client = client;
    }

    @Override
    public void run() {

        // do anything needed with the Client field
        System.out.println(client);
    }
}
</code>```

Main

```<code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {
    public Main() throws InterruptedException {

        ExecutorService executor = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 5; i++) {
            executor.submit(new ClientProcessor(new Client("id" + i, "timestamp_" + i)));
        }

        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.SECONDS);
    }
}
</code>```

Body:
I have a class in which my add method is being called by multiple threads to populate clientidToTimestampHolder LinkedBlockingQueue. And then in the same below class, I start a background thread which runs every 30 milliseconds and calls a processData() method which drains clientidToTimestampHolder to List of Map and then I iterate that List to send data to different service by calling appropriate method.

I can get same userid many times with different timestamp so that is why I am using LinkedBlockingQueue with map.

public class Handler {
  private final ScheduledExecutorService executorService = Executors
      .newSingleThreadScheduledExecutor();
  private final LinkedBlockingQueue<Map.Entry<String, Long>> clientidToTimestampHolder =
      new LinkedBlockingQueue<>();

  private static class Holder {
    private static final Handler INSTANCE = new Handler();
  }

  public static Handler getInstance() {
    return Holder.INSTANCE;
  }

  private Handler() {
    executorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        processData();
      }
    }, 0, 30, TimeUnit.MILLISECONDS);
  }

  // called by multiple threads to populate clientidToTimestampHolder map
  public void add(final String clientid, final Long timestamp) {
    clientidToTimestampHolder.offer(Maps.immutableEntry(clientid, timestamp));
  }

  // called by single background thread every 30 milliseconds
  public void processData() {
    final List<Map.Entry<String, Long>> entries = new ArrayList<>();
    clientidToTimestampHolder.drainTo(entries);
    for (Map.Entry<String, Long> entry : entries) {
      String clientid = entry.getKey();
      long timestamp = entry.getValue();
      boolean isUpdated = isUpdatedClient(clientid, timestamp);
      if (!isUpdated) {
        updateClient(String.valueOf(clientid));
      }
    }
  }
}

Is my above code thread safe and there is no race condition? Since add method will be called from multiple threads and then I have a single background thread which runs every 30 milliseconds to calls processData() method which extracts data from clientidToTimestampHolder LinkedBlockingQueue.

Because right now it looks like under heavy load, my processData() method might be missing few entries which got added through add method. I added few logs in my add method which printed out the clientid but somehow that same clientid didn't got printed out in the logs I added in isUpdatedClient method so making it suspicious to me somehow.

I am working with Java 7.

Body:
I would do it in the following way:

Create a Class which incapsulates some data which you need to process. And the logic of processing. In this case it may be like a ClientProcessor class with Client field

I don't see why you need some 3rd party executor implementations, so I'll use Java Executors. However, with another implementations approach will be similar.

Create needed amount of ClientProcessor objects by reading them from source / using some factory -> and submit these tasks to the executor.

Below is a simple example:

public class Client {
    private String id;
    private String timeStamp;

    public Client(String id, String timeStamp) {
        this.id = id;
        this.timeStamp = timeStamp;
    }

    public String getId() {
        return id;
    }

    public String getTimeStamp() {
        return timeStamp;
    }
}

ClientProcessor:

public class ClientProcessor implements Runnable{

    private Client client;

    public ClientProcessor(Client client) {
        super();
        this.client = client;
    }

    @Override
    public void run() {

        // do anything needed with the Client field
        System.out.println(client);
    }
}

Main

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {
    public Main() throws InterruptedException {

        ExecutorService executor = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 5; i++) {
            executor.submit(new ClientProcessor(new Client("id" + i, "timestamp_" + i)));
        }

        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.SECONDS);
    }
}


问:
How to remove dependency on System.Web.Mvc within domain model assembly containing POCOs
I have an assembly generated using POCO template using Entity Framework (e.g. "Company.Models.dll").Besides generated POCOs I also have "follow up" partial classes that define meta data using System.ComponentModel.DataAnnotations.
So for example Company.Models.Customer is auto-generated (in separate folder) and then I have partial class with same namespace. Within this partial class I define inner class for metadata...For example:

```<code>using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Company.Models
{
    [MetadataType(typeof (CustomerMetaData))]
    public partial class Customer
    {
        public override string ToString()
        {
            return String.Format("Id: {0}, Name: {1}", Id, Name);
        }

        //[Bind(Exclude = "Id")]
        public class CustomerMetaData
        {
            [ScaffoldColumn(false)]
            public int Id { get; set; }

            [DisplayName("Name")]
            [Required(ErrorMessage = "Customer Name is required.")]
            [StringLength(100, ErrorMessage = "Customer name cannot exceed 100 characters.", MinimumLength = 2)]
            public string Name { get; set; }
        }
    }
}
</code>```

The issue I am having is that I now want to use this assembly in my MVC project and want to use MVC specific attributes (like the commented out Bind attribute above).However, doing so requires making my Company.Models.dll dependent on System.Web.Mvc.dll.

I would like to avoid this at all costs if possible but how?

So far I am aware of 2 possible solutions and am asking community for their opinions or better approaches...

Solution 1

This solution has been discussed here: Using Data Annotations on POCO's with MVC for Remote Validation The "trick" was to use ViewModels and map (either mannually or using AutoMapper) POCOs to MVC project specific ViewModels. Then apply all necessary attributes to ViewModels instead of domain model POCOs. While this makes sense for large projects it is a bit overkill for small simple solutions...

Solution 2

Use Bind attribute in Controller action parameters (as seen on some http://www.asp.net/mvc tutorials). For example:

```<code>//
// POST: /Customer/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="Id")]Customer customerToCreate)
{
        if (!ModelState.IsValid)
        return View();

        // TODO: Add insert logic here
    return RedirectToAction("Index");
    }
</code>```

Using this solution would allow to skip dependency on System.Web.Mvc from my POCO dll at the cost of having to remember to insert Bind attribute on all relevant Controller actions.
Also, if I have multiple ASP.NET MVC projects the issue gets worse...

So, is there another way? ;)

答:
I'd suggest that your POCO entities do not contain any UI-specific code. Ideally they wouldn't contain any code specific to data persistence either but EF makes this tricky.

The first solution is definitely best solution to use in order to make your application more scalable and to better separate out your concerns.

Another solution could be to create your own domain attributes (MyRequiredAttribute, MyStringLengthAttribute etc.) and place these in your core assembly. You could then create a custom metadata provider to have MVC recognise these attributes. Here's an example of how to create this: http://bradwilson.typepad.com/blog/2009/10/enterprise-library-validation-example-for-aspnet-mvc-2.html

Body:
I have an assembly generated using POCO template using Entity Framework (e.g. "Company.Models.dll").Besides generated POCOs I also have "follow up" partial classes that define meta data using System.ComponentModel.DataAnnotations.
So for example Company.Models.Customer is auto-generated (in separate folder) and then I have partial class with same namespace. Within this partial class I define inner class for metadata...For example:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Company.Models
{
    [MetadataType(typeof (CustomerMetaData))]
    public partial class Customer
    {
        public override string ToString()
        {
            return String.Format("Id: {0}, Name: {1}", Id, Name);
        }

        //[Bind(Exclude = "Id")]
        public class CustomerMetaData
        {
            [ScaffoldColumn(false)]
            public int Id { get; set; }

            [DisplayName("Name")]
            [Required(ErrorMessage = "Customer Name is required.")]
            [StringLength(100, ErrorMessage = "Customer name cannot exceed 100 characters.", MinimumLength = 2)]
            public string Name { get; set; }
        }
    }
}

The issue I am having is that I now want to use this assembly in my MVC project and want to use MVC specific attributes (like the commented out Bind attribute above).However, doing so requires making my Company.Models.dll dependent on System.Web.Mvc.dll.

I would like to avoid this at all costs if possible but how?

So far I am aware of 2 possible solutions and am asking community for their opinions or better approaches...

Solution 1

This solution has been discussed here: Using Data Annotations on POCO's with MVC for Remote Validation The "trick" was to use ViewModels and map (either mannually or using AutoMapper) POCOs to MVC project specific ViewModels. Then apply all necessary attributes to ViewModels instead of domain model POCOs. While this makes sense for large projects it is a bit overkill for small simple solutions...

Solution 2

Use Bind attribute in Controller action parameters (as seen on some http://www.asp.net/mvc tutorials). For example:

//
// POST: /Customer/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="Id")]Customer customerToCreate)
{
        if (!ModelState.IsValid)
        return View();

        // TODO: Add insert logic here
    return RedirectToAction("Index");
    }

Using this solution would allow to skip dependency on System.Web.Mvc from my POCO dll at the cost of having to remember to insert Bind attribute on all relevant Controller actions.
Also, if I have multiple ASP.NET MVC projects the issue gets worse...

So, is there another way? ;)


问:
Why layout is disturbing even using width in dp Android
I have created a demo application in Android using Nexus 9 2048 X 1536
I have added an EditText and assign width as 1000dp it is working fine in Nexus 9 Emulator. But When I change the Emulator as Nexus 5X 1080 X 1920 to test the dp purpose, Then the EditText goes out of the layout and shown about half of it.

Why it is happening even I assign the width in dp. It should adjust the width by screen-resolution.

答:
You have a few alternatives:

1) The right and recommended one is to make different layouts for different screens. For this alternative see Supporting multiple screens

2) Another alternative I used to use before ConstraintLayout was to make everything proportional. When the app starts I take the meassurement of the Display and layout everything based on that. This is done mostly programatically not using the xml layout file.

3) Use the new ConstraintLayout from the support library. Using this layout you can constraint your widgest relative to each other and or to guidelines you can add to your layout to delimit sections of it. Your widgets that need to adapt will mostly have a width of 0dp or wrap_content and the constraints will take care of resizig them accordingly.

Using ConstraintLayout


问:
How to configure VS 2017 offline installer/layout so that it doesn't need an internet connection at all?
I was able to create an offline installer with a command line like:

```<code>vs_enterprise__873301792.1489161815.exe --layout %CD%\vs2017offline --lang en-US
</code>```

I got about 20 GB out of this (1901 files).

but, as it is already known, the Visual Studio installer needs an internet connection at least to initialize, even with such an offline layout.
(But it doesn't need to download the packages already existing in the layout/image, so it saves really download volume.)

In the MS web documentation for VS more parameters are mentioned:
https://learn.microsoft.com/en-us/visualstudio/install/use-command-line-parameters-to-install-visual-studio

AFAIK, nobody figured out how to use them to guarantee really an offline install without internet connection (it seems quite likely to me that channel and/or catalog have to be redirected for hindering VS installer to go online).

Has anyone?

Here are the parameters, which I mean:

--channelId     Optional: The ID of the channel for the instance that will be installed. This is required for the install command, ignored for other commands if --installPath is specified.

--channelUri   Optional: The URI of the channel manifest. This can be used for the install command; it is ignored for other commands.

--installChannelUri    Optional: The URI of the channel manifest to use for the installation. The URI specified by --channelUri (which must be specified when --installChannelUri is specified) will be used to detect updates. If updates are not desired, --channelUri must be specified without an argument. This can be used for the install command; it is ignored for other commands.

--installCatalogUri  Optional: The URI of the catalog manifest to use for the installation. If specified, the channel manager will attempt to download the catalog manifest from this URI before using the URI in the install channel manifest. This parameter is used to support offline install, where the layout cache will be created with the product catalog already downloaded. This can be used for the install command; it is ignored for other commands.

In the layout directory, there exist files like catalog.json, channelmanifest.json, response.json, vs_installer_version.json among others. Any idea?

答:
You don't need to do anything special for the offline installer to work without any Internet connection. Even though channelURI in <offline folder>\Response.json points online, it will not try to update the component list or something each time, you need to explicitly request an update for that.

The only thing you need to make sure is to select a language that you have downloaded files for on the "Language packs" tab when selecting components -- otherwise, it will try to download the missing bits.

The installer will still try to access the Net

to post telemetry to https://dc.services.visualstudio.com/v2/track and https://vortex.data.microsoft.com/collect/v1 from Microsoft.VisualStudio.Telemetry.Net35.dll that's a part of the installer

to retrieve CRLs for relevant signing certificates from https://crl.microsoft.com

but both are optional, the installer won't fail it it can't do either -- I've just successfully installed stuff with a disabled network connection.

Body:
I was able to create an offline installer with a command line like:

vs_enterprise__873301792.1489161815.exe --layout %CD%\vs2017offline --lang en-US

I got about 20 GB out of this (1901 files).

but, as it is already known, the Visual Studio installer needs an internet connection at least to initialize, even with such an offline layout.
(But it doesn't need to download the packages already existing in the layout/image, so it saves really download volume.)

In the MS web documentation for VS more parameters are mentioned:
https://learn.microsoft.com/en-us/visualstudio/install/use-command-line-parameters-to-install-visual-studio

AFAIK, nobody figured out how to use them to guarantee really an offline install without internet connection (it seems quite likely to me that channel and/or catalog have to be redirected for hindering VS installer to go online).

Has anyone?

Here are the parameters, which I mean:

--channelId     Optional: The ID of the channel for the instance that will be installed. This is required for the install command, ignored for other commands if --installPath is specified.

--channelUri   Optional: The URI of the channel manifest. This can be used for the install command; it is ignored for other commands.

--installChannelUri    Optional: The URI of the channel manifest to use for the installation. The URI specified by --channelUri (which must be specified when --installChannelUri is specified) will be used to detect updates. If updates are not desired, --channelUri must be specified without an argument. This can be used for the install command; it is ignored for other commands.

--installCatalogUri  Optional: The URI of the catalog manifest to use for the installation. If specified, the channel manager will attempt to download the catalog manifest from this URI before using the URI in the install channel manifest. This parameter is used to support offline install, where the layout cache will be created with the product catalog already downloaded. This can be used for the install command; it is ignored for other commands.

In the layout directory, there exist files like catalog.json, channelmanifest.json, response.json, vs_installer_version.json among others. Any idea?


问:
How to run autoplay video and mute the sound?
How to run autoplay video and mute the sound for owl carousel 2?

My code - https://jsfiddle.net/ufqp8Lku/

$('.owl-carousel').owlCarousel({
  items: 1,
  merge: true,
  loop: true,
  margin: 10,
  video: true,
  lazyLoad: true,
  center: true,
  responsive: {
    480: {
      items: 1
    },
    600: {
      items: 1
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.owl-carousel,
.owl-carousel .item-video {
  height: 300px;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.min.css" rel="stylesheet" />

```

答:
Call the jQuery function play() in the callback afterAction:

```<code>afterAction: function(current) {
        current.find('video').get(0).play();
    }
</code>```

Or even this:

```<code>(function($) {
    $(document).ready(function() {
        setTimeout(
            function() {
                $(".active .owl-video-play-icon").trigger("click");
            }, 1000);
    });
    $(document).on('click', '.owl-dot', function() {
        if ($('.owl-item.active').hasClass('owl-video-playing')) {} else {
            setTimeout(
                function() {
                    $(".active .owl-video-play-icon").trigger("click");
                }, 1000);
        }
    });
})(jQuery);
</code>```

Example:

http://codepen.io/vishpatel93/pen/gmqzQv

ContentLicense: CC BY-SA 4.0

Body:
How to run autoplay video and mute the sound for owl carousel 2?

My code - https://jsfiddle.net/ufqp8Lku/

$('.owl-carousel').owlCarousel({
  items: 1,
  merge: true,
  loop: true,
  margin: 10,
  video: true,
  lazyLoad: true,
  center: true,
  responsive: {
    480: {
      items: 1
    },
    600: {
      items: 1
    }
  }
})

.owl-carousel,
.owl-carousel .item-video {
  height: 300px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.min.css" rel="stylesheet" />

Body:
Call the jQuery function play() in the callback afterAction:

afterAction: function(current) {
        current.find('video').get(0).play();
    }

Or even this:

(function($) {
    $(document).ready(function() {
        setTimeout(
            function() {
                $(".active .owl-video-play-icon").trigger("click");
            }, 1000);
    });
    $(document).on('click', '.owl-dot', function() {
        if ($('.owl-item.active').hasClass('owl-video-playing')) {} else {
            setTimeout(
                function() {
                    $(".active .owl-video-play-icon").trigger("click");
                }, 1000);
        }
    });
})(jQuery);

Example:

http://codepen.io/vishpatel93/pen/gmqzQv


问:
Android firebase create and display username
I am using Firebase user sign up method with email and password. While creating a new user I also store information such username that later on needs to be displayed in app profile page.

How could I retrieve the username of currently logged in person ?

Thank you in advance

```<code>private void registration(){

    final String email = Email.getText().toString().toString().trim();
    final String password = Password.getText().toString().trim();
    final String username = Username.getText().toString().trim();
    final String age = Age.getText().toString().trim();
    final String userID = userAuth.getCurrentUser().getUid();

    if (!TextUtils.isEmpty(email)&& !TextUtils.isEmpty(password)&& !TextUtils.isEmpty(username)&& !TextUtils.isEmpty(age)){

        showProgress.setMessage("Registration in progress...");
        showProgress.show();

        userAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if(task.isSuccessful()) {

                    String user_id = userAuth.getCurrentUser().getUid();
                    DatabaseReference current_user_db = DatbaseOfUsers.child(user_id);
                    current_user_db.child("email").setValue(email);
                    current_user_db.child("username").setValue(username);
                    current_user_db.child("Age").setValue(age);
                    current_user_db.child("uID").setValue(userID);

                    showProgress.dismiss();

                    //After user is created main screen intent is called
                    Intent mainpage = new Intent(RegisterActivity.this, MainPageActivity.class);
                    mainpage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(mainpage);
                }

                else if(!task.isSuccessful()){
                    showProgress.dismiss();
                    Toast.makeText(RegisterActivity.this,"Error While Register",Toast.LENGTH_LONG).show();
                }
            }

        });

    }

    else{
        showProgress.dismiss();
        Toast.makeText(RegisterActivity.this,"Please Enter All Required Fields",Toast.LENGTH_LONG).show();
    }
</code>```

答:
You can send request to Users with current user's uid.

```<code>FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();

mDatabase.child("Users").orderByChild(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
</code>```

In onDataChange returns value you are looking as dataSnapshot. Then cast it to your model, get the want ever you want.

Body:
I am using Firebase user sign up method with email and password. While creating a new user I also store information such username that later on needs to be displayed in app profile page.

How could I retrieve the username of currently logged in person ?

Thank you in advance

private void registration(){

    final String email = Email.getText().toString().toString().trim();
    final String password = Password.getText().toString().trim();
    final String username = Username.getText().toString().trim();
    final String age = Age.getText().toString().trim();
    final String userID = userAuth.getCurrentUser().getUid();

    if (!TextUtils.isEmpty(email)&& !TextUtils.isEmpty(password)&& !TextUtils.isEmpty(username)&& !TextUtils.isEmpty(age)){

        showProgress.setMessage("Registration in progress...");
        showProgress.show();

        userAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if(task.isSuccessful()) {

                    String user_id = userAuth.getCurrentUser().getUid();
                    DatabaseReference current_user_db = DatbaseOfUsers.child(user_id);
                    current_user_db.child("email").setValue(email);
                    current_user_db.child("username").setValue(username);
                    current_user_db.child("Age").setValue(age);
                    current_user_db.child("uID").setValue(userID);

                    showProgress.dismiss();

                    //After user is created main screen intent is called
                    Intent mainpage = new Intent(RegisterActivity.this, MainPageActivity.class);
                    mainpage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(mainpage);
                }

                else if(!task.isSuccessful()){
                    showProgress.dismiss();
                    Toast.makeText(RegisterActivity.this,"Error While Register",Toast.LENGTH_LONG).show();
                }
            }

        });

    }

    else{
        showProgress.dismiss();
        Toast.makeText(RegisterActivity.this,"Please Enter All Required Fields",Toast.LENGTH_LONG).show();
    }

Body:
You can send request to Users with current user's uid.

FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();

mDatabase.child("Users").orderByChild(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

In onDataChange returns value you are looking as dataSnapshot. Then cast it to your model, get the want ever you want.


问:
how to auto increment a number everytime when a button is clicked on other page using javascript
I have a form created using HTML and CSS, this form is not for submitting any data in fact it's only for printing purposes.

This form has an input field at top left corner to put a unique 6 digit number to uniquely identify each form.

On the homepage, there is a button link to that form page and I want to increment that serial no which is by default 000000 every time a link button to this form page is clicked.

index.html:

```<code><a href="pages/form-1.html"></a>
</code>```

form-1.html:

```<code><input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
</code>```

答:
A really simple way to do this is by using jQuery. Use the click event listener with the button link which will listen to every clicks made to that button, and increment the value with each clicks. With the starting value as 000000, store the incremented value into a variable and then use that variable on a desired page.

FOR EXAMPLE:

Consider that you have this button on the home.html page:

```<code><a href="formpage.html" id="linkcounter">BUTTON</a>
</code>```

Now, using jQuery - listen to the click events from this link and store the incremented values on variable like this:

```<code>var count = 0,
    default = '000000';
$('#linkcounter').click(function(e) {
    e.preventDefault();
    count++;
    var ctxt = '' + count;
    var incrementval = pad.substr(0, pad.length - ctxt.length) + ctxt;
});

// store the value into the local storage of DOM for the current session. this is done to retain the variable value even after a page is refreshed.
var incrementvallocal = incrementval;
localStorage.setItem("incrementvalueper", incrementvallocal);
</code>```

The incremented value stored in the variable incrementval is sent to the localstorage. Now just use the value of this variable on desired page(in this example it is formpage.html).

If you want to set the placeholder text on the form page which has an input field like this:

```<code><input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
</code>```

by the incremented value, then use this jQuery code:

```<code>// get incremented value from the local storage of DOM.
var getincval = localStorage.getItem("incrementvalueper");

$(document).ready(function(){
  $('.serial-no').attr("placeholder", getincval);
});
</code>```

This code uses the value of the variable getincval(which has the incremented click value) and sets it to the placeholder text of the input element which has the class .serial-no.

Let me know if this helps. :)

Body:
I have a form created using HTML and CSS, this form is not for submitting any data in fact it's only for printing purposes.

This form has an input field at top left corner to put a unique 6 digit number to uniquely identify each form.

On the homepage, there is a button link to that form page and I want to increment that serial no which is by default 000000 every time a link button to this form page is clicked.

index.html:

form-1.html:

<input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">

Body:
A really simple way to do this is by using jQuery. Use the click event listener with the button link which will listen to every clicks made to that button, and increment the value with each clicks. With the starting value as 000000, store the incremented value into a variable and then use that variable on a desired page.

FOR EXAMPLE:

Consider that you have this button on the home.html page:

<a href="formpage.html" id="linkcounter">BUTTON</a>

Now, using jQuery - listen to the click events from this link and store the incremented values on variable like this:

var count = 0,
    default = '000000';
$('#linkcounter').click(function(e) {
    e.preventDefault();
    count++;
    var ctxt = '' + count;
    var incrementval = pad.substr(0, pad.length - ctxt.length) + ctxt;
});

// store the value into the local storage of DOM for the current session. this is done to retain the variable value even after a page is refreshed.
var incrementvallocal = incrementval;
localStorage.setItem("incrementvalueper", incrementvallocal);

The incremented value stored in the variable incrementval is sent to the localstorage. Now just use the value of this variable on desired page(in this example it is formpage.html).

If you want to set the placeholder text on the form page which has an input field like this:

<input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">

by the incremented value, then use this jQuery code:

// get incremented value from the local storage of DOM.
var getincval = localStorage.getItem("incrementvalueper");

$(document).ready(function(){
  $('.serial-no').attr("placeholder", getincval);
});

This code uses the value of the variable getincval(which has the incremented click value) and sets it to the placeholder text of the input element which has the class .serial-no.

Let me know if this helps. :)


问:
How to display values from a linked list to a text area
I would like to display all values from the linked list to text area including the ones that the user will have to enter.
Also when the user adds more names, I would like the text area to display the next name almost like a queue.</p>

答:
try this.

```<code>String name = Username.getText(); //get text from text field
String name2 = mylist.getText();//get text from text area
mylist.setText(""); //remove all text in text area
Queue<String> myQ=new LinkedList<String>();

    myQ.add(name2);//add already writen data in text area
    myQ.add(name);//add text field data

    for(String str : myQ){ //iterate
        //System.out.print(str +" ");
        mylist.append(str +" ");//append into text area

    }
</code>```

Edit 1:

As you also want to remove element from queue so use this modify code.

Add Button:

```<code>    Queue<String> myQ=new LinkedList<>();
    int count=0;
    private void AddActionPerformed(java.awt.event.ActionEvent evt) {

    myQ.add(++count+":" + Username.getText());//add into queue
    mylist.setText("");//use to insert new data
    mylist.append(myQ +"\n");//insert queue object into text area
    myQ.peek();//get top value of queue

    }
</code>```

Remove Button:

```<code>    private void RegisterActionPerformed(java.awt.event.ActionEvent evt) {
    myQ.remove();//remove first element
    System.out.print(myQ);
    mylist.setText("");
    mylist.append(myQ +" ");

  }
</code>```

Hope this helps you.

Body:
try this.

String name = Username.getText(); //get text from text field
String name2 = mylist.getText();//get text from text area
mylist.setText(""); //remove all text in text area
Queue<String> myQ=new LinkedList<String>();

    myQ.add(name2);//add already writen data in text area
    myQ.add(name);//add text field data

    for(String str : myQ){ //iterate
        //System.out.print(str +" ");
        mylist.append(str +" ");//append into text area

    }

Edit 1:

As you also want to remove element from queue so use this modify code.

Add Button:

    Queue<String> myQ=new LinkedList<>();
    int count=0;
    private void AddActionPerformed(java.awt.event.ActionEvent evt) {

    myQ.add(++count+":" + Username.getText());//add into queue
    mylist.setText("");//use to insert new data
    mylist.append(myQ +"\n");//insert queue object into text area
    myQ.peek();//get top value of queue

    }

Remove Button:

    private void RegisterActionPerformed(java.awt.event.ActionEvent evt) {
    myQ.remove();//remove first element
    System.out.print(myQ);
    mylist.setText("");
    mylist.append(myQ +" ");

  }

Hope this helps you.


问:
Find number of CPUs in linux kernel
I want detect number of CPUs in linux kernel and write a sys_call that find it.

cpuinfo_x86 gives features of one CPU and cpu_detect fills it but how to find number of CPUs to detect?

答: You can use nr_cpu_ids variable which is set by all architectures during kernel boot up and initialization.</p>

Title: Find number of CPUs in linux kernel


问:
php mysqli query function not executing when the query contains php variable
I would really like some help. I am trying to return a record from a table where I am search that table by first name and last name, which is one string in a php variable $employee_coor.

This problem is when ever I use the variable within my query statement it returns nothing. No errors nothing. However, if I echo the variable to the screen the employee's full name is seen. Then I tried copying that full name into the statement and the record would be then returned.

I also tried mysqli_num_rows on the query to be sure if a record is being selected or not and it returned 0 when echoed to the screen.

I really don't know why I am getting this, I hope it's something I am over looking or something like that.  The code below shows the script.

UPDATE: I tested the exact query itself in the MySQL client and it works perfectly. The only difference would be the query in MySQL qould have a full name as opposed to a php variable representing that name.

```<code>    <?php
     include_once('dbconnect.php');

     if (!empty($_GET['employees'])) {

     $employee_coor = $_GET['employees'];

     $select = "SELECT * FROM employees
                WHERE employees.employee_fname = substring_index('$employee_coor',' ',1)
                AND employees.employee_lname = substring_index('$employee_coor',' ',-1)";

           $query = mysqli_query($con,$select);

           $cooridinator = mysqli_fetch_assoc($query);

           var_dump($cooridinator);

   } else{}
   ?>
</code>```

答:
It's hard to stare at PHP code that builds an SQL query, and try to diagnose what's wrong with the SQL query. Why make it that hard?

If you have doubts about the SQL statement, you should print out the SQL and look at the SQL, not the PHP that builds SQL. I mean the final SQL string, after you have copied PHP variables into it. It might be more clear once you look at the final query why it doesn't work.

```<code>$select = "SELECT * FROM employees
           WHERE employees.employee_fname = substring_index('$employee_coor',' ',1)
           AND employees.employee_lname = substring_index('$employee_coor',' ',-1)";

error_log($select);
</code>```

Try copying the final SQL and trying it in the MySQL client. Does it give zero rows? Why? Try editing the query and removing one term of the WHERE clause, then the other. Do those give zero rows?

You get the idea. Test, don't guess.

Anyway, your code has another problem: it's vulnerable to SQL injection. It will break even if you try to process a person named "O'Reilly."

I would recommend splitting the variable in PHP before you apply it to the SQL statement, and also use bound parameters.

```<code>$employee_coor = explode(' ', $_GET['employees']);

$select = "SELECT * FROM employees
            WHERE employees.employee_fname = ?
            AND employees.employee_lname = ?";

$stmt = mysqli_prepare($con,$select);
mysqli_stmt_bind_param($stmt, 'ss',
  array_shift($employee_coor),
  array_pop($employee_coor));
mysqli_stmt_execute($stmt);
</code>```

Body:
I would really like some help. I am trying to return a record from a table where I am search that table by first name and last name, which is one string in a php variable $employee_coor.

This problem is when ever I use the variable within my query statement it returns nothing. No errors nothing. However, if I echo the variable to the screen the employee's full name is seen. Then I tried copying that full name into the statement and the record would be then returned.

I also tried mysqli_num_rows on the query to be sure if a record is being selected or not and it returned 0 when echoed to the screen.

I really don't know why I am getting this, I hope it's something I am over looking or something like that.  The code below shows the script.

UPDATE: I tested the exact query itself in the MySQL client and it works perfectly. The only difference would be the query in MySQL qould have a full name as opposed to a php variable representing that name.

    <?php
     include_once('dbconnect.php');

     if (!empty($_GET['employees'])) {

     $employee_coor = $_GET['employees'];

     $select = "SELECT * FROM employees
                WHERE employees.employee_fname = substring_index('$employee_coor',' ',1)
                AND employees.employee_lname = substring_index('$employee_coor',' ',-1)";

           $query = mysqli_query($con,$select);

           $cooridinator = mysqli_fetch_assoc($query);

           var_dump($cooridinator);

   } else{}
   ?>

Body:
It's hard to stare at PHP code that builds an SQL query, and try to diagnose what's wrong with the SQL query. Why make it that hard?

If you have doubts about the SQL statement, you should print out the SQL and look at the SQL, not the PHP that builds SQL. I mean the final SQL string, after you have copied PHP variables into it. It might be more clear once you look at the final query why it doesn't work.

$select = "SELECT * FROM employees
           WHERE employees.employee_fname = substring_index('$employee_coor',' ',1)
           AND employees.employee_lname = substring_index('$employee_coor',' ',-1)";

error_log($select);

Try copying the final SQL and trying it in the MySQL client. Does it give zero rows? Why? Try editing the query and removing one term of the WHERE clause, then the other. Do those give zero rows?

You get the idea. Test, don't guess.

Anyway, your code has another problem: it's vulnerable to SQL injection. It will break even if you try to process a person named "O'Reilly."

I would recommend splitting the variable in PHP before you apply it to the SQL statement, and also use bound parameters.

$employee_coor = explode(' ', $_GET['employees']);

$select = "SELECT * FROM employees
            WHERE employees.employee_fname = ?
            AND employees.employee_lname = ?";

$stmt = mysqli_prepare($con,$select);
mysqli_stmt_bind_param($stmt, 'ss',
  array_shift($employee_coor),
  array_pop($employee_coor));
mysqli_stmt_execute($stmt);


问:
username not exists yet it says username already exists
I am using following codes to prevent entry of duplicate username in the database but it always says "username already exists" through the particular username not exists in the database. I can not understand where I am doing wrong. Thanks in advance. </p>

```<code>    $ImageName = $ImageDir.$image_tempname;
$query = mysqli_query($conn, "SELECT * FROM usernames WHERE username='".$username."'");
$rows = mysqli_num_rows($query);
if (move_uploaded_file($_FILES['image']['tmp_name'],
                      $ImageName)) {

  //get info about the image being uploaded
  list($width, $height, $type, $attr) = getimagesize($ImageName);

  //**insert these new lines
  if ($type > 3) {
    echo "Sorry, but the file you uploaded was not a GIF, JPG, or " .
         "PNG file.<br>";
    echo "Please hit your browser's 'back' button and try again.";

  }

elseif ($rows > 0){

    echo "email already exists";
}

else {

    //image is acceptable; ok to proceed

  //**end of inserted lines

  //insert info into image table

$insert = "INSERT INTO xyz (.......)
VALUES (........)";

$insertresults = mysqli_query($insert);  //order executes

 if($insertresults)
{

header ("Location:https://www.getalifepartner.com/free-matrimonial-site/upload_success.php");

 }
</code>```

答:
Here is one way

```<code>$query = mysqli_query($con, "SELECT * FROM usernames WHERE username='$username'");
$res = mysqli_fetch_array($query);

if ($res['username'] == $username)
{
    echo 'Username already in use, please choose another one.';
}
else
{
    // username not in use
}
</code>```

Here is another way

```<code>$query = mysqli_query($con, "SELECT * FROM usernames WHERE username='$username'");
$rows = mysqli_num_rows($query);

if ($rows > 0)
{
    echo 'Username already in use, please choose another one.';
}
else
{
    // username not in use
}
</code>```

UPDATE TO ORIGINAL QUESTION

```<code>$ImageName = $ImageDir.$image_tempname;

$query = mysqli_query($conn, "SELECT * FROM usernames WHERE username='$username'");
$rows = mysqli_num_rows($query);

if (move_uploaded_file($_FILES['image']['tmp_name'], $ImageName))
{
    //get info about the image being uploaded
    list($width, $height, $type, $attr) = getimagesize($ImageName);

    //**insert these new lines
    if ($type > 3)
    {
        echo "Sorry, but the file you uploaded was not a GIF, JPG, or PNG file.<br>";
        echo "Please hit your browser's 'back' button and try again.";
    }
}
elseif ($rows > 0)
{
    echo "Email already exists.";
}
else
{
    //image is acceptable; ok to proceed
    //**end of inserted lines
    //insert info into image table
}
</code>```

Body:
I am using following codes to prevent entry of duplicate username in the database but it always says "username already exists" through the particular username not exists in the database. I can not understand where I am doing wrong. Thanks in advance.

    $ImageName = $ImageDir.$image_tempname;
$query = mysqli_query($conn, "SELECT * FROM usernames WHERE username='".$username."'");
$rows = mysqli_num_rows($query);
if (move_uploaded_file($_FILES['image']['tmp_name'],
                      $ImageName)) {

  //get info about the image being uploaded
  list($width, $height, $type, $attr) = getimagesize($ImageName);

  //**insert these new lines
  if ($type > 3) {
    echo "Sorry, but the file you uploaded was not a GIF, JPG, or " .
         "PNG file.
";
    echo "Please hit your browser's 'back' button and try again.";

  }

elseif ($rows > 0){

    echo "email already exists";
}

else {

    //image is acceptable; ok to proceed

  //**end of inserted lines

  //insert info into image table

$insert = "INSERT INTO xyz (.......)
VALUES (........)";

$insertresults = mysqli_query($insert);  //order executes

 if($insertresults)
{

header ("Location:https://www.getalifepartner.com/free-matrimonial-site/upload_success.php");

 }

Body:
Here is one way

$query = mysqli_query($con, "SELECT * FROM usernames WHERE username='$username'");
$res = mysqli_fetch_array($query);

if ($res['username'] == $username)
{
    echo 'Username already in use, please choose another one.';
}
else
{
    // username not in use
}

Here is another way

$query = mysqli_query($con, "SELECT * FROM usernames WHERE username='$username'");
$rows = mysqli_num_rows($query);

if ($rows > 0)
{
    echo 'Username already in use, please choose another one.';
}
else
{
    // username not in use
}

UPDATE TO ORIGINAL QUESTION

$ImageName = $ImageDir.$image_tempname;

$query = mysqli_query($conn, "SELECT * FROM usernames WHERE username='$username'");
$rows = mysqli_num_rows($query);

if (move_uploaded_file($_FILES['image']['tmp_name'], $ImageName))
{
    //get info about the image being uploaded
    list($width, $height, $type, $attr) = getimagesize($ImageName);

    //**insert these new lines
    if ($type > 3)
    {
        echo "Sorry, but the file you uploaded was not a GIF, JPG, or PNG file.<br>";
        echo "Please hit your browser's 'back' button and try again.";
    }
}
elseif ($rows > 0)
{
    echo "Email already exists.";
}
else
{
    //image is acceptable; ok to proceed
    //**end of inserted lines
    //insert info into image table
}


问:
PHPMailer why i get connection timeout error?
In the company I work for we use microsoft exchange server and ofcourse ms outlook to send and recieve email.

on andriod we use exchange application as following to access our mail.

I am trying to use the following code to send emails IN php:

```<code> require 'PHPMailer/PHPMailerAutoload.php';

 $mail = new PHPMailer;

 $mail->SMTPDebug = 3;                               // Enable verbose debug output

 $mail->isSMTP();                                      // Set mailer to use SMTP
 $mail->Host = 'mail.dom-domain.com';  // Specify main and backup SMTP servers
 $mail->SMTPAuth = true;                               // Enable SMTP authentication
 $mail->Username = 'username';                 // SMTP username
 $mail->Password = 'password123';                           // SMTP password
 $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
 $mail->Port = 587;                                    // TCP port to connect to

 $mail->setFrom('username@dom-domain.com', 'Mailer');
 $mail->addAddress('recname@yahoo.com', 'Joe User');     // Add a recipient
 //$mail->addAddress('ellen@example.com');               // Name is optional
 $mail->addReplyTo('username@dom-domain.com', 'Information');
 //$mail->addCC('cc@example.com');
 //$mail->addBCC('bcc@example.com');

 //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
 //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
 $mail->isHTML(true);                                  // Set email format to HTML

 $mail->Subject = 'Here is the subject tls587';
 $mail->Body    = 'This is the HTML message body tls587 <b>in bold!</b>';
 $mail->AltBody = 'This is the body in plain text for non-HTML mail clients tls587';

 if(!$mail->send()) {
     echo 'Message could not be sent.';
     echo 'Mailer Error: ' . $mail->ErrorInfo;
 } else {
     echo 'Message has been sent';
 }
</code>```

but the page loads alot and I get this error:

2017-04-02 13:13:45 Connection: opening to mail.dom-domain.com:587, timeout=300, options=array ( ) 2017-04-02 13:14:48 Connection failed. Error #2: stream_socket_client(): unable to connect to mail.dom-domain.com:587 (Connection timed out) [/home/xxxxxxx/public_html/ml/PHPMailer/class.smtp.php line 294] 2017-04-02 13:14:48 SMTP ERROR: Failed to connect to server: Connection timed out (110) 2017-04-02 13:14:48 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

答:
Keep noted that on your Android device you are mostly using Microsoft Active Sync via port 443. You do NOT use a native SMTP connection here via port 587 (which would be used via IMAP/POP3). The same is true for a plain Outlook connection where MAPI or MAPI over HTTP/Outlook Anywhere is used. Both do not use a native SMTP connection here and might be the reason why it isn´t working. BUT on your GMail Account you are mostly using IMAP as this isn´t an Exchange Server which support Microsoft Active Sync.

It might therefore possible that your Exchange Administrator didn´t configured the SMTP Connector for external Authenticated connections for Outlook users as this isn´t needed in your case and therefore disabled for security reasons. As you didn´t specify if you are the Exchange Administrator and which version you are using its not easy to give you a how to here. So instead of that, you should follow these howtos here from Microsoft:

Controlling SMTP Relaying with Microsoft Exchange

Configure authenticated SMTP settings for POP3 and IMAP4 clients in Exchange 2016

If you aren´t an Microsoft Exchange Administrator you can try to send emails via the Microsoft Exchange Webservices (see here). However as said above, the Exchange Administrator might run a special configuration here to secure the environment.

Body:
In the company I work for we use microsoft exchange server and ofcourse ms outlook to send and recieve email.

on andriod we use exchange application as following to access our mail.

I am trying to use the following code to send emails IN php:

 require 'PHPMailer/PHPMailerAutoload.php';

 $mail = new PHPMailer;

 $mail->SMTPDebug = 3;                               // Enable verbose debug output

 $mail->isSMTP();                                      // Set mailer to use SMTP
 $mail->Host = 'mail.dom-domain.com';  // Specify main and backup SMTP servers
 $mail->SMTPAuth = true;                               // Enable SMTP authentication
 $mail->Username = 'username';                 // SMTP username
 $mail->Password = 'password123';                           // SMTP password
 $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
 $mail->Port = 587;                                    // TCP port to connect to

 $mail->setFrom('username@dom-domain.com', 'Mailer');
 $mail->addAddress('recname@yahoo.com', 'Joe User');     // Add a recipient
 //$mail->addAddress('ellen@example.com');               // Name is optional
 $mail->addReplyTo('username@dom-domain.com', 'Information');
 //$mail->addCC('cc@example.com');
 //$mail->addBCC('bcc@example.com');

 //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
 //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
 $mail->isHTML(true);                                  // Set email format to HTML

 $mail->Subject = 'Here is the subject tls587';
 $mail->Body    = 'This is the HTML message body tls587 in bold!';
 $mail->AltBody = 'This is the body in plain text for non-HTML mail clients tls587';

 if(!$mail->send()) {
     echo 'Message could not be sent.';
     echo 'Mailer Error: ' . $mail->ErrorInfo;
 } else {
     echo 'Message has been sent';
 }

but the page loads alot and I get this error:

2017-04-02 13:13:45 Connection: opening to mail.dom-domain.com:587, timeout=300, options=array ( ) 2017-04-02 13:14:48 Connection failed. Error #2: stream_socket_client(): unable to connect to mail.dom-domain.com:587 (Connection timed out) [/home/xxxxxxx/public_html/ml/PHPMailer/class.smtp.php line 294] 2017-04-02 13:14:48 SMTP ERROR: Failed to connect to server: Connection timed out (110) 2017-04-02 13:14:48 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting


问:
.NET Performance Issues - visual studio hosting process
I have a .NET 4.0 Client Profile, WPF + NHibernate 3 Line of Business style application, which I have almost completely developed. The backend database is a Microsoft Access file accessed via the NHibernate contrib JetDriver.

When running the application via the debugger in Visual Studio 2010, the application performance is very acceptable. If however I run either the Debug or Release .exe file or from a ClickOnce deployment, the performance of the whole application is extremely sluggish.

After searching on google, I found that disabling the 'visual studio hosting process' option would make my debugging experience similar to running the .exe file directly, which it did.

What I would like to know is, why is it I am experiencing such a slow down with respect to the normal debugging mode? And how can I improve matters at run time.

Compile Settings are as shown:

Regards,

答:
NHibernate performance problems can often be attributed to log4net configuration. If you are using log4net and the level is set to DEBUG NHibernate will do a lot of logging. This may also be the reason that performance is acceptable in the the VS debugger but not deployment. log4net may not have write access to a folder in the deployment environment so it's failing to open the log file. See this link: http://jagregory.com/writings/empty-nhibernate-logs-and-poor-performance/.

PS - I'm having a hard time reconciling line-of-business application with Access back end.


问:
Translating High Resolution Adobe Creative SDK from PHP to Ruby on Rails
I am trying to implement Adobe's Creative SDK into my Ruby on Rails app.

https://creativesdk.adobe.com/docs/web/#/articles/highresolution/index.html

I have the required access to the hi-res API.

The examples they have are for PHP and Node.js, and I am trying to write a Ruby on Rails version based on the PHP. I have it all setup, in that it's properly calling the "authenticationURL" but I'm getting an "Invalid authenticationURL response. Please check the formatting the response."

I'm new to programming at this level and basically tried to figure this out by referencing a few questions on PHP & Ruby here as well sites like http://www.phptoruby.com/.

Here is the PHP:

```<code><!-- /getAuth -->

<?php
$apiKey = "apikey";
$apiSecret = "apisecret";
$salt = rand(0,1000);
$time = time();
$sig = sha1($apiKey . $apiSecret . $time . $salt);

$authObj = array(
    "apiKey" => $apiKey,
    "salt" => $salt,
    "timestamp" => $time,
    "encryptionMethod" => 'sha1',
    "signature" => $sig
);

echo json_encode($authObj);

?>
</code>```

Here is what I have at the moment (with my apikey and apisecret entered correctly):

```<code>require 'time'
require 'json'
require 'digest/sha1'

def get_auth
 apiKey = 'apikey'
 apiSecret = 'apisecret'
 salt = "#{0 + rand(1000)}"
 time = "#{Time.now.to_i}"
 sig = Digest::SHA1.hexdigest('apiKey' + 'apiSecret' + 'time' + 'salt')

 authObj = { :apiKey => 'apiKey',
                 :salt => 'salt',
                 :timestamp => 'time',
                 :encryptionMethod => 'sha1',
                 :signature => 'sig' }

 print 'authObj'.to_json
 render :fxb
end
</code>```

I'm not sure if using print is correct here? Or if my problem is a syntax issue... Or something else entirely.

答:
Yes in php i set header and all work fine.

header('Content-Type: application/json');

Body:
I am trying to implement Adobe's Creative SDK into my Ruby on Rails app.

https://creativesdk.adobe.com/docs/web/#/articles/highresolution/index.html

I have the required access to the hi-res API.

The examples they have are for PHP and Node.js, and I am trying to write a Ruby on Rails version based on the PHP. I have it all setup, in that it's properly calling the "authenticationURL" but I'm getting an "Invalid authenticationURL response. Please check the formatting the response."

I'm new to programming at this level and basically tried to figure this out by referencing a few questions on PHP & Ruby here as well sites like http://www.phptoruby.com/.

Here is the PHP:

<?php
$apiKey = "apikey";
$apiSecret = "apisecret";
$salt = rand(0,1000);
$time = time();
$sig = sha1($apiKey . $apiSecret . $time . $salt);

$authObj = array(
    "apiKey" => $apiKey,
    "salt" => $salt,
    "timestamp" => $time,
    "encryptionMethod" => 'sha1',
    "signature" => $sig
);

echo json_encode($authObj);

?>

Here is what I have at the moment (with my apikey and apisecret entered correctly):

require 'time'
require 'json'
require 'digest/sha1'

def get_auth
 apiKey = 'apikey'
 apiSecret = 'apisecret'
 salt = "#{0 + rand(1000)}"
 time = "#{Time.now.to_i}"
 sig = Digest::SHA1.hexdigest('apiKey' + 'apiSecret' + 'time' + 'salt')

 authObj = { :apiKey => 'apiKey',
                 :salt => 'salt',
                 :timestamp => 'time',
                 :encryptionMethod => 'sha1',
                 :signature => 'sig' }

 print 'authObj'.to_json
 render :fxb
end

I'm not sure if using print is correct here? Or if my problem is a syntax issue... Or something else entirely.


问:
How to select a certain text from text file and enter into text box
Hi all
I have a sql script in text file which is as follows

```<code>create view [dbo].[budget_change-22]
as select projectname, projectnumber,location, client
FROM      OPENROWSET('SQLNCLI', 'SERVER=AABB1089\abcWORKSS_STO;UID=abcworkss;PWD=abcdef,
                      'SET NOCOUNT ON;SET FMTONLY OFF;EXEC abcworks_sto..SP_Budget_444 38') AS Workchanged_444
Go
</code>```

Now in the above script i have to select Server value (AABB1089\abcWORKSS_STO), UID value(abcwork), Pwd value(abcdef) so that i can replace in text box and edit them to create a new text file with different name.

答:
This depends on the framework your UI is using, however as you have tagged c# I am going to assume winforms.

Would it be feasible to do this instead?  Place your SQL in a file but do not populate the parameters, instead put in place holders that you can then use in code to add the values coming in from your textboxes, for example:

```<code>create view [dbo].[budget_change-22]
as select projectname, projectnumber,location, client
FROM OPENROWSET('SQLNCLI', 'SERVER={0};UID={1};PWD={2},
'SET NOCOUNT ON;SET FMTONLY OFF;EXEC abcworks_sto..SP_Budget_444 38') AS Workchanged_444
Go
</code>```

Notice the '{x}', in your code read in the file and use string.Format to replace {x} values as necessary.  Psuedo code:

```<code>// Read in the template file
string fileSql = System.File.IO.ReadAllText(pathToYourTemplateFile)

// Replace the place holders with your values (sample assumes
// they are coming from textboxes on the UI
string formattedSql = string.Format(fileSql,
    txtServerName.Text,
    txtUid.Text,
    txtPassword.Text);

// Write out the new file
System.IO.File.WriteAllText(formattedSql, pathToYourNewFile);
</code>```

If for whatever reason you can't go down the route of a template file, then you could use string.Replace() for example

```<code>// Read in the template file
string fileSql = System.File.IO.ReadAllText(pathToYourTemplateFile)

// Replace the values with the input from the UI
fileSql.Replace("AABB1089\abcWORKSS_STO", txtServer.Text)
// ... same for uid ...
// ... same for pwd ...

// Write out the new file
System.IO.File.WriteAllText(fileSql , pathToYourNewFile);
</code>```

Body:
Hi all
I have a sql script in text file which is as follows

create view [dbo].[budget_change-22]
as select projectname, projectnumber,location, client
FROM      OPENROWSET('SQLNCLI', 'SERVER=AABB1089\abcWORKSS_STO;UID=abcworkss;PWD=abcdef,
                      'SET NOCOUNT ON;SET FMTONLY OFF;EXEC abcworks_sto..SP_Budget_444 38') AS Workchanged_444
Go

Now in the above script i have to select Server value (AABB1089\abcWORKSS_STO), UID value(abcwork), Pwd value(abcdef) so that i can replace in text box and edit them to create a new text file with different name.

Body:
This depends on the framework your UI is using, however as you have tagged c# I am going to assume winforms.

Would it be feasible to do this instead?  Place your SQL in a file but do not populate the parameters, instead put in place holders that you can then use in code to add the values coming in from your textboxes, for example:

create view [dbo].[budget_change-22]
as select projectname, projectnumber,location, client
FROM OPENROWSET('SQLNCLI', 'SERVER={0};UID={1};PWD={2},
'SET NOCOUNT ON;SET FMTONLY OFF;EXEC abcworks_sto..SP_Budget_444 38') AS Workchanged_444
Go

Notice the '{x}', in your code read in the file and use string.Format to replace {x} values as necessary.  Psuedo code:

// Read in the template file
string fileSql = System.File.IO.ReadAllText(pathToYourTemplateFile)

// Replace the place holders with your values (sample assumes
// they are coming from textboxes on the UI
string formattedSql = string.Format(fileSql,
    txtServerName.Text,
    txtUid.Text,
    txtPassword.Text);

// Write out the new file
System.IO.File.WriteAllText(formattedSql, pathToYourNewFile);

If for whatever reason you can't go down the route of a template file, then you could use string.Replace() for example

// Read in the template file
string fileSql = System.File.IO.ReadAllText(pathToYourTemplateFile)

// Replace the values with the input from the UI
fileSql.Replace("AABB1089\abcWORKSS_STO", txtServer.Text)
// ... same for uid ...
// ... same for pwd ...

// Write out the new file
System.IO.File.WriteAllText(fileSql , pathToYourNewFile);


答:
One completely different approach: use Java8 streams.

Meaning: first rework your code to start with:

```<code>entries.stream(). ...
</code>```

because then, turning it into "parallel" might only need to replace it with

```<code>entries.parallelStream(). ...
</code>```

I am not too much into streams yet; but there are good example sites, like this here.

Title: Execute a for loop in parallel instead of sequential order when underlying method returns void

Body:
I have a class in which my add method is being called by multiple threads to populate clientidToTimestampHolder LinkedBlockingQueue. And then in the same below class, I start a background thread which runs every 30 milliseconds and calls a processData() method which drains clientidToTimestampHolder to List of Map and then I iterate that List to send data to different service by calling appropriate method.

I can get same userid many times with different timestamp so that is why I am using LinkedBlockingQueue with map.

public class Handler {
  private final ScheduledExecutorService executorService = Executors
      .newSingleThreadScheduledExecutor();
  private final LinkedBlockingQueue<Map.Entry<String, Long>> clientidToTimestampHolder =
      new LinkedBlockingQueue<>();

  private static class Holder {
    private static final Handler INSTANCE = new Handler();
  }

  public static Handler getInstance() {
    return Holder.INSTANCE;
  }

  private Handler() {
    executorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        processData();
      }
    }, 0, 30, TimeUnit.MILLISECONDS);
  }

  // called by multiple threads to populate clientidToTimestampHolder map
  public void add(final String clientid, final Long timestamp) {
    clientidToTimestampHolder.offer(Maps.immutableEntry(clientid, timestamp));
  }

  // called by single background thread every 30 milliseconds
  public void processData() {
    final List<Map.Entry<String, Long>> entries = new ArrayList<>();
    clientidToTimestampHolder.drainTo(entries);
    for (Map.Entry<String, Long> entry : entries) {
      String clientid = entry.getKey();
      long timestamp = entry.getValue();
      boolean isUpdated = isUpdatedClient(clientid, timestamp);
      if (!isUpdated) {
        updateClient(String.valueOf(clientid));
      }
    }
  }
}

Is my above code thread safe and there is no race condition? Since add method will be called from multiple threads and then I have a single background thread which runs every 30 milliseconds to calls processData() method which extracts data from clientidToTimestampHolder LinkedBlockingQueue.

Because right now it looks like under heavy load, my processData() method might be missing few entries which got added through add method. I added few logs in my add method which printed out the clientid but somehow that same clientid didn't got printed out in the logs I added in isUpdatedClient method so making it suspicious to me somehow.

I am working with Java 7.

Body:
One completely different approach: use Java8 streams.

Meaning: first rework your code to start with:

entries.stream(). ...

because then, turning it into "parallel" might only need to replace it with

entries.parallelStream(). ...

I am not too much into streams yet; but there are good example sites, like this here.


问:
PHP MySQL Transaction catch error
I have been looking for two days now and still haven't found the answer. Suppose I have underneath code in PHP:

```<code>$mysqli->begin_transaction();
mysqli_query($mysqli, "DELETE FROM Test WHERE ID=1");
mysqli_query($mysqli, "DELETE FROM TEST WHEREE ID=2"); <-- THIS ONE WILL FAIL BECAUSE OF TYPO
mysqli_query($mysqli, "DELETE FROM Test WHERE ID=3");
if ($mysqli->commit()) {
    //SUCCESS
    }
else {
    //Failed
    $mysqli->rollback();
    }
</code>```

I am not able to check whether the queries within the transaction all have succeeded, because when I execute these queries, the commit function always returns true.

How can I check whether all queries within the transaction have succeeded?

答:
Common way to do this:</p>
```<code>$mysqli->begin_transaction();
try {
    mysqli_query($mysqli, "DELETE FROM Test WHERE ID=1");
    mysqli_query($mysqli, "DELETE FROM TEST WHEREE ID=2"); <-- THIS ONE WILL FAIL BECAUSE OF TYPO
    mysqli_query($mysqli, "DELETE FROM Test WHERE ID=3");
    $mysqli->commit();
} catch (\Exception $e) {
    // this will show statement with error
    echo $e->getMessage();
    $mysqli->rollback();
    throw $e;
}
</code>```

Title: PHP MySQL Transaction catch error

Body:
I have been looking for two days now and still haven't found the answer. Suppose I have underneath code in PHP:

$mysqli->begin_transaction();
mysqli_query($mysqli, "DELETE FROM Test WHERE ID=1");
mysqli_query($mysqli, "DELETE FROM TEST WHEREE ID=2"); <-- THIS ONE WILL FAIL BECAUSE OF TYPO
mysqli_query($mysqli, "DELETE FROM Test WHERE ID=3");
if ($mysqli->commit()) {
    //SUCCESS
    }
else {
    //Failed
    $mysqli->rollback();
    }

I am not able to check whether the queries within the transaction all have succeeded, because when I execute these queries, the commit function always returns true.

How can I check whether all queries within the transaction have succeeded?

Body:
Common way to do this:

$mysqli->begin_transaction();
try {
    mysqli_query($mysqli, "DELETE FROM Test WHERE ID=1");
    mysqli_query($mysqli, "DELETE FROM TEST WHEREE ID=2"); <-- THIS ONE WILL FAIL BECAUSE OF TYPO
    mysqli_query($mysqli, "DELETE FROM Test WHERE ID=3");
    $mysqli->commit();
} catch (\Exception $e) {
    // this will show statement with error
    echo $e->getMessage();
    $mysqli->rollback();
    throw $e;
}


问:
Word2Vec: Is it possible to train with respect to weight in NLP?
I used Gensim's Word2Vec for training most similar words.

My dataset is all posts from my college community site.

Each dataset consists of like this:

```<code>(title) + (contents) + (all comments)  // String
</code>```

For example,

```<code>data[0] => "This is title. Contents is funny. What so funny?. Not funny for me"
</code>```

So, I have around 400,000 datas like above and make them as a vector and try to train these data via Word2Vec.

I wonder that whether it is possible to make Word2Vec consider WEIGHT, which means, if I give an weight to certain data vector, Word2Vec train this data in a way that each word in this data vector has more strong relationship(similarity).

For example, If I gave a weight 5 to dataset, I like Pizza, Chicken, the word Pizza and Chicken (or like and Pizza etc) has strong relations than other data vector's words.

Would that be possible?

Sorry for poor explanation but I'm not native english speaker. If need more detailed info, please post comment.

答:
There's no such configurable weighting in the definition of the word2vec algorithm, or the gensim implementation.

You could try repeating those text examples that you want to have more influence. (Ideally, such repetitions wouldn't be back-to-back, but shuffled among the entire dataset.)

As a result, those examples will affect the underlying model's training more often, for a greater proportion of the total training time – shifting the relative positioning of the involved words, compared to less-repeated examples. That might have the end result you're seeking.

Body:
I used Gensim's Word2Vec for training most similar words.

My dataset is all posts from my college community site.

Each dataset consists of like this:

(title) + (contents) + (all comments)  // String

For example,

data[0] => "This is title. Contents is funny. What so funny?. Not funny for me"

So, I have around 400,000 datas like above and make them as a vector and try to train these data via Word2Vec.

I wonder that whether it is possible to make Word2Vec consider WEIGHT, which means, if I give an weight to certain data vector, Word2Vec train this data in a way that each word in this data vector has more strong relationship(similarity).

For example, If I gave a weight 5 to dataset, I like Pizza, Chicken, the word Pizza and Chicken (or like and Pizza etc) has strong relations than other data vector's words.

Would that be possible?

Sorry for poor explanation but I'm not native english speaker. If need more detailed info, please post comment.


问:
how to set element center in the div
suppose i have text, images etc in div. so how can i make the element center horizontally and vertically in the div with the help javascript & css. please guide with sample code.

thanks

答:
you can do this all with css.

for horizontal center, use the text-align class.

For vertical center, I have used line-height --

this link goes over centering:

http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

Title: how to set element center in the div


问:
Fault Tolerance in Ignite Services
I have deployed ignite services()(some job to be performed on ignite nodes) on 4 ignite nodes. If one node fails and job is in midway of execution, I want other node to take over this job and continue executing it. How can we handle this type of failure in case of service grids? I have read about fail over SPI and check pointing SPI, which of these can be used in my case? are there any examples for same?

Thanks.

答:
Failover, checkpointing, etc. are parts of Compute Grid [1]. And from what I hear, it fits your use case much better than Service Grid.

[1] https://apacheignite.readme.io/docs/compute-grid

Title: Fault Tolerance in Ignite Services


问:
Form validation not working with FOR loop
I have 3 text fields and a hidden field. The text field accepts a date. If the date entered is later than today for any text field, it should display an error message. This only works properly if I enter a later date in the first text field. If I do it in the second or third, it continues to the redirect which obviously shouldn't happen.</p>

```<code>$count = count($_POST['complete_date']);
        for($i = 0; $i < $count; ++$i) {

        if($_POST['complete_date'][$i] > date('Y-m-d')) {
            echo error_message("Date can't be in the future");
            break;

            } else {

$stmt = $link->prepare("UPDATE `units` SET `complete_date` = ? WHERE `units` = ?");
        $stmt->bind_param("si", $_POST['complete_date'][$i], $_POST['units'][$i]);
        $stmt->execute();
        $stmt->close();
        header("location: dashboard.php");
        exit();

    }
}
</code>```

答:
That's normal, if you have an error in the second or third position, you still execute your query for the first item of the array. You should do something like that :</p>

```<code>$count = count($_POST['complete_date']);
$error = false;
    for($i = 0; $i < $count && ! $error; ++$i) {

    if($_POST['complete_date'][$i] > date('Y-m-d')) {
        echo error_message("Date can't be in the future");
        $error = true;

        }
   }

  //Only process if there are no errors in all the dates
  if(! $error){
  $stmt = $link->prepare("UPDATE `units` SET `complete_date` = ? WHERE `units` = ?");
    $stmt->bind_param("si", $_POST['complete_date'][$i],$_POST['units'][$i]);
    $stmt->execute();
    $stmt->close();
    header("location: dashboard.php");
    exit();

}
</code>```

Body:
I have 3 text fields and a hidden field. The text field accepts a date. If the date entered is later than today for any text field, it should display an error message. This only works properly if I enter a later date in the first text field. If I do it in the second or third, it continues to the redirect which obviously shouldn't happen.

$count = count($_POST['complete_date']);
        for($i = 0; $i < $count; ++$i) {

        if($_POST['complete_date'][$i] > date('Y-m-d')) {
            echo error_message("Date can't be in the future");
            break;

            } else {

$stmt = $link->prepare("UPDATE `units` SET `complete_date` = ? WHERE `units` = ?");
        $stmt->bind_param("si", $_POST['complete_date'][$i], $_POST['units'][$i]);
        $stmt->execute();
        $stmt->close();
        header("location: dashboard.php");
        exit();

    }
}

Body:
That's normal, if you have an error in the second or third position, you still execute your query for the first item of the array. You should do something like that :

$count = count($_POST['complete_date']);
$error = false;
    for($i = 0; $i < $count && ! $error; ++$i) {

    if($_POST['complete_date'][$i] > date('Y-m-d')) {
        echo error_message("Date can't be in the future");
        $error = true;

        }
   }

  //Only process if there are no errors in all the dates
  if(! $error){
  $stmt = $link->prepare("UPDATE `units` SET `complete_date` = ? WHERE `units` = ?");
    $stmt->bind_param("si", $_POST['complete_date'][$i],$_POST['units'][$i]);
    $stmt->execute();
    $stmt->close();
    header("location: dashboard.php");
    exit();

}