问:
WPF – Change Property Value in Setter of Another Property
In the following example of my custom control, why I can't change a TransparentColor property in a setter of a SelectedColor property? A solution with callback method works fine, what's the difference between them in the case of change another property?

```<code>public class MyColorPicker : Control
{
    static MyColorPicker()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyColorPicker), new FrameworkPropertyMetadata(typeof(MyColorPicker)));
    }

    public static readonly DependencyProperty SelectedColorProperty =
            DependencyProperty.Register("SelectedColor", typeof(Color), typeof(MyColorPicker), new PropertyMetadata(Color.FromRgb(0, 201, 201), OnSelectedColorChange));

    private static void OnSelectedColorChange(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var colorPicker = (MyColorPicker)sender;
        var selectedColor = colorPicker.SelectedColor;
        colorPicker.TransparentColor = Color.FromArgb(0, selectedColor.R, selectedColor.G, selectedColor.B);
    }

    public Color SelectedColor
    {
        get { return (Color)GetValue(SelectedColorProperty); }
        set
        {
            // Why this not working? BorderStopColor = Color.FromArgb(0, value.R, value.G, value.B);
            SetValue(SelectedColorProperty, value);
        }
    }

    private static readonly DependencyPropertyKey TransparentColorPropertyKey =
            DependencyProperty.RegisterReadOnly("TransparentColor", typeof(Color), typeof(MyColorPicker), new PropertyMetadata(Color.FromArgb(0, 0, 201, 201)));

    public static readonly DependencyProperty TransparentColorProperty = TransparentColorPropertyKey.DependencyProperty;

    public Color TransparentColor
    {
        get { return (Color)GetValue(TransparentColorProperty); }
        protected set { SetValue(TransparentColorPropertyKey, value); }
    }
}
</code>```

答:
The setter of a CLR wrapper for a dependency property should only call the SetValue method to set the actual value of the dependency property.

Any other logic should be implemented in the callback.

Also note that the CLR property wrappers are bypassed at runtime when setting dependency properties in XAML (but the callbacks are not):

Why are .NET property wrappers bypassed at runtime when setting dependency properties in XAML?

Body:
In the following example of my custom control, why I can't change a TransparentColor property in a setter of a SelectedColor property? A solution with callback method works fine, what's the difference between them in the case of change another property?

public class MyColorPicker : Control
{
    static MyColorPicker()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyColorPicker), new FrameworkPropertyMetadata(typeof(MyColorPicker)));
    }

    public static readonly DependencyProperty SelectedColorProperty =
            DependencyProperty.Register("SelectedColor", typeof(Color), typeof(MyColorPicker), new PropertyMetadata(Color.FromRgb(0, 201, 201), OnSelectedColorChange));

    private static void OnSelectedColorChange(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var colorPicker = (MyColorPicker)sender;
        var selectedColor = colorPicker.SelectedColor;
        colorPicker.TransparentColor = Color.FromArgb(0, selectedColor.R, selectedColor.G, selectedColor.B);
    }

    public Color SelectedColor
    {
        get { return (Color)GetValue(SelectedColorProperty); }
        set
        {
            // Why this not working? BorderStopColor = Color.FromArgb(0, value.R, value.G, value.B);
            SetValue(SelectedColorProperty, value);
        }
    }

    private static readonly DependencyPropertyKey TransparentColorPropertyKey =
            DependencyProperty.RegisterReadOnly("TransparentColor", typeof(Color), typeof(MyColorPicker), new PropertyMetadata(Color.FromArgb(0, 0, 201, 201)));

    public static readonly DependencyProperty TransparentColorProperty = TransparentColorPropertyKey.DependencyProperty;

    public Color TransparentColor
    {
        get { return (Color)GetValue(TransparentColorProperty); }
        protected set { SetValue(TransparentColorPropertyKey, value); }
    }
}


来源: stackexchange

问:
Submit Spark Jobs in EMR concurrently from Lambda
My application has requirement to real time processing data using EMR spark Jobs.

I am using addJobFlowSteps API of EMR from Lambda, but which is sequential in nature.

Is there any other way to submit Jobs to EMR from Lambda which is concurrent in nature ?

答:
You can use custom 'spark-submit' script.

I use this:

```<code>cat /usr/bin/spark-submit-forked
#!/bin/bash

(nohup spark-submit "$@" > /dev/null 2>&1 &)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use custom 'spark-submit' script.

I use this:

cat /usr/bin/spark-submit-forked
#!/bin/bash

(nohup spark-submit "$@" > /dev/null 2>&1 &)


问:
Choosing a simple web application framework
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages. </p>

<p>I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail. </p>

答:
If it's just a personal hobby thing, I would recommend either going with .Net MVC, Rails or Zend (there may be some good Java frameworks out there but I'm not familiar with them).

I'm guessing that since it's a hobby project, you're not going to want to spend a lot of time looking around the web for examples on how to do things with the framework or looking for tutorials on how to set it all up. You probably want to be able to play with a bunch of cool features right off the bat without things breaking or dealing with a bunch of bugs. That being said, I think .Net MVC and or Rails will allow you to have the most fun with the least amount of headache. With a lot of the other Open Source frameworks out there you're going to have to jump through a lot of hoops right from the start that you would rather not have to deal with, and a lot of the time documentation for getting through the initial setup problems is hard to find.

OwnerDisplayName: nagul

ContentLicense: CC BY-SA 2.5

Body:
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages.

I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail.

LastEditorDisplayName: Marko Dumic

OwnerDisplayName: Matt Schwartz


问:
How are people unit testing with Entity Framework 6, should you bother?
I am just starting out with Unit testings and TDD in general. I have dabbled before but now I am determined to add it to my workflow and write better software.

I asked a question yesterday that kind of included this, but it seems to be a question on its own.  I have sat down to start implementing a service class that I will use to abstract away the business logic from the controllers and map to specific models and data interactions using EF6.

The issue is I have roadblocked myself already because I didn't want to abstract EF away in a repository (it will still be available outside the services for specific queries, etc) and would like to test my services (EF Context will be used).

Here I guess is the question, is there a point to doing this? If so, how are people doing it in the wild in light of the leaky abstractions caused by IQueryable and the many great posts by Ladislav Mrnka on the subject of unit testing not being straightforward because of the differences in Linq providers when working with an in memory implementation as apposed to a specific database.

The code I want to test seems pretty simple. (this is just dummy code to try and understand what i am doing, I want to drive the creation using TDD)

Context

```<code>public interface IContext
{
    IDbSet<Product> Products { get; set; }
    IDbSet<Category> Categories { get; set; }
    int SaveChanges();
}

public class DataContext : DbContext, IContext
{
    public IDbSet<Product> Products { get; set; }
    public IDbSet<Category> Categories { get; set; }

    public DataContext(string connectionString)
                : base(connectionString)
    {

    }
}
</code>```

Service

```<code>public class ProductService : IProductService
{
    private IContext _context;

    public ProductService(IContext dbContext)
    {
        _context = dbContext;
    }

    public IEnumerable<Product> GetAll()
    {
        var query = from p in _context.Products
                    select p;

        return query;
    }
}
</code>```

Currently I am in the mindset of doing a few things:

Mocking EF Context with something like this approach- Mocking EF When Unit Testing or directly using a mocking framework on the interface like moq - taking the pain that the unit tests may pass but not necessarily work end to end and back them up with Integration tests?

Maybe using something like Effort to mock EF - I have never used it and not sure if anyone else is using it in the wild?

Not bother testing anything that simply calls back to EF - so essentially service methods that call EF directly (getAll etc) are not unit tested but just integration tested?

Anyone out there actually doing this out there without a Repo and having success?

答:
There is Effort which is an in memory entity framework database provider. I've not actually tried it... Haa just spotted this was mentioned in the question!

Alternatively you could switch to EntityFrameworkCore which has an in memory database provider built-in.

https://blog.goyello.com/2016/07/14/save-time-mocking-use-your-real-entity-framework-dbcontext-in-unit-tests/

https://github.com/tamasflamich/effort

I used a factory to get a context, so i can create the context close to its use. This seems to work locally in visual studio but not on my TeamCity build server, not sure why yet.

```<code>return new MyContext(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am just starting out with Unit testings and TDD in general. I have dabbled before but now I am determined to add it to my workflow and write better software.

I asked a question yesterday that kind of included this, but it seems to be a question on its own.  I have sat down to start implementing a service class that I will use to abstract away the business logic from the controllers and map to specific models and data interactions using EF6.

The issue is I have roadblocked myself already because I didn't want to abstract EF away in a repository (it will still be available outside the services for specific queries, etc) and would like to test my services (EF Context will be used).

Here I guess is the question, is there a point to doing this? If so, how are people doing it in the wild in light of the leaky abstractions caused by IQueryable and the many great posts by Ladislav Mrnka on the subject of unit testing not being straightforward because of the differences in Linq providers when working with an in memory implementation as apposed to a specific database.

The code I want to test seems pretty simple. (this is just dummy code to try and understand what i am doing, I want to drive the creation using TDD)

Context

public interface IContext
{
    IDbSet<Product> Products { get; set; }
    IDbSet<Category> Categories { get; set; }
    int SaveChanges();
}

public class DataContext : DbContext, IContext
{
    public IDbSet<Product> Products { get; set; }
    public IDbSet<Category> Categories { get; set; }

    public DataContext(string connectionString)
                : base(connectionString)
    {

    }
}

Service

public class ProductService : IProductService
{
    private IContext _context;

    public ProductService(IContext dbContext)
    {
        _context = dbContext;
    }

    public IEnumerable<Product> GetAll()
    {
        var query = from p in _context.Products
                    select p;

        return query;
    }
}

Currently I am in the mindset of doing a few things:

Mocking EF Context with something like this approach- Mocking EF When Unit Testing or directly using a mocking framework on the interface like moq - taking the pain that the unit tests may pass but not necessarily work end to end and back them up with Integration tests?

Maybe using something like Effort to mock EF - I have never used it and not sure if anyone else is using it in the wild?

Not bother testing anything that simply calls back to EF - so essentially service methods that call EF directly (getAll etc) are not unit tested but just integration tested?

Anyone out there actually doing this out there without a Repo and having success?

Body:
There is Effort which is an in memory entity framework database provider. I've not actually tried it... Haa just spotted this was mentioned in the question!

Alternatively you could switch to EntityFrameworkCore which has an in memory database provider built-in.

https://blog.goyello.com/2016/07/14/save-time-mocking-use-your-real-entity-framework-dbcontext-in-unit-tests/

https://github.com/tamasflamich/effort

I used a factory to get a context, so i can create the context close to its use. This seems to work locally in visual studio but not on my TeamCity build server, not sure why yet.

return new MyContext(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;");


问:
Smart way to remove PDO statement rows integer keys and relative values
I have a PHP page showing user a query content.

If a csv parameter is passed, I let the user download the results in csv like this:

```<code>$stmt = $pdo->prepare($query_select);
$stmt->execute($params);
if ($format == 'csv'){
  $fobj = fopen('php://output', 'w');
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename="' . $search_text . '.csv"');
  $i = 0;
  foreach ($stmt as $row) {
    if (!$i++) {
      fputcsv($fobj, array_keys($row));
    }
    fputcsv($fobj, array_values($row));
  }
  fclose($fobj);
  exit();
}
</code>```

Problem is $row contains data as this:

```<code>Array
(
    [name] => apple
    [0] => apple
    [colour] => red
    [1] => red
)
</code>```

so my csv file ends up with duplicate data:

```<code>name,0,colour,1
apple,apple,red,red
</code>```

Which could be a smart way to get instead what user expects?

```<code>name,colour
apple,red
</code>```

答:
Set the fetch mode like below:</p>

```<code>$stmt->setFetchMode(PDO::FETCH_ASSOC);
</code>```

Body:
I have a PHP page showing user a query content.

If a csv parameter is passed, I let the user download the results in csv like this:

$stmt = $pdo->prepare($query_select);
$stmt->execute($params);
if ($format == 'csv'){
  $fobj = fopen('php://output', 'w');
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename="' . $search_text . '.csv"');
  $i = 0;
  foreach ($stmt as $row) {
    if (!$i++) {
      fputcsv($fobj, array_keys($row));
    }
    fputcsv($fobj, array_values($row));
  }
  fclose($fobj);
  exit();
}

Problem is $row contains data as this:

Array
(
    [name] => apple
    [0] => apple
    [colour] => red
    [1] => red
)

so my csv file ends up with duplicate data:

name,0,colour,1
apple,apple,red,red

Which could be a smart way to get instead what user expects?

name,colour
apple,red

Body:
Set the fetch mode like below:

$stmt->setFetchMode(PDO::FETCH_ASSOC);


问:
How do I avoid checking for nulls in Java?
I use x != null to avoid NullPointerException. Is there an alternative?

if (x != null) {
    // ...
}
```

答:
If you are using java8 or later go for the isNull(yourObject) from java.util.Objects.

Example:-

```<code>String myObject = null;

Objects.isNull(myObject); //will return true
</code>```

Usage: The below code returns a non null value (if the name is not null then that value will be returned else the default value will be returned).

```<code>final String name = "Jobin";
String nonNullValue = Optional.ofNullable(name).orElse("DefaultName");
</code>```

OwnerDisplayName: Goran Martinic

LastEditorDisplayName: cletus

Body:
If you are using java8 or later go for the isNull(yourObject) from java.util.Objects.

Example:-

String myObject = null;

Objects.isNull(myObject); //will return true

Usage: The below code returns a non null value (if the name is not null then that value will be returned else the default value will be returned).

final String name = "Jobin";
String nonNullValue = Optional.ofNullable(name).orElse("DefaultName");


问:
Where to call ASP.Net HTTP2 PushPromise
We're migrating our ASP.Net (4.6) Web Forms website to a shiny new 2016 Server and as part of that we're keen to make the most out of the new HTTP2 possibilities. Part of that is using Server Push to get css and js files to the client as quickly as possible. However, having found basically zero documentation around this online (please correct me if I'm wrong) I'm struggling to check the best place to call the HttpResponse.PushPromise() method.

On a standard page I'm assuming this would just sit in Page_Load()? However, most pages in this project actually derive from a BasePage class rather than from System.Web.UI.Page (basically just to provide common methods and custom properties) so what's the best-practice case here. Should we override Page_Load?
 Or call PushPromise() from somewhere else in the application?

Any assistance gratefully received. I know HTTP2 is fairly new, but I've found the lack of documentation/support/examples from Microsoft on this to be really poor.

Many thanks!

答:
Technically you can do it wherever you send a response.

The server creates the PUSH_PROMISE frame to the response part of a
  normal, browser-initiated stream

Since you are calling on the response object ,you have to have Response object avaialble(in the context of a request which has an HTTP connection.

```<code>public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.PushPromise("/Images/1.png");
        }
    }
</code>```

I have done a channel 9 presentation on the basics of HTTP and all the benefits it gives here .It also contains a demo of HTTP push promise with how it works in the network trace level.I also have a complete demo code here in this github repo

Title: Where to call ASP.Net HTTP2 PushPromise

Body:
Technically you can do it wherever you send a response.

The server creates the PUSH_PROMISE frame to the response part of a
  normal, browser-initiated stream

Since you are calling on the response object ,you have to have Response object avaialble(in the context of a request which has an HTTP connection.

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.PushPromise("/Images/1.png");
        }
    }

I have done a channel 9 presentation on the basics of HTTP and all the benefits it gives here .It also contains a demo of HTTP push promise with how it works in the network trace level.I also have a complete demo code here in this github repo


问:
Minus positive with negative value in a table using subquery
I have the data below:

```<code>| Amount | Type | Employee |
| -----  | ---- | -------- |
| 500   |  A   |  001     |
| 200   |  B   |  001     |
| 300   |  A   |  002     |
| 200   |  A   |  002     |
| 100   |  B   |  002     |
</code>```

In the scenario above, all Type A columns are positive values, and Type B are negative values.

I need to calculate the amount of each employee with positive minus negative as the end result, which means Type A minus Type B.

So Employee 001 should have the result 500 - 200 = 300, and Employee 002 is 300 + 200 - 100 = 400.

I have following incomplete query:

```<code>SELECT
 (SELECT SUM(Amount) FROM A WHERE Type = 'A') -
 (SELECT SUM(Amount) FROM A WHERE Type = 'B') As Payable, Employee
FROM Payroll A
WHERE Company = @Company AND Month = @Month AND Year = @Year
GROUP BY Employee
</code>```

In the query above, the statement SELECT SUM(Amount) FROM A WHERE Type = 'A' is trying to get the positive Amount of the Payroll table which is already filtered by Company, Month and Year column. It didn't work because A is not recognize as a valid object.

So what should I do to get the data from the filtered Payroll table rather than I have to put in the WHERE condition again into both subquery?

EDIT:

Thanks Kannan and Thomas for the suggestion, but I still have problem achieving the desire result. Right now, this is my modified query with CASE

```<code>SELECT
 SUM(CASE WHEN Type = 'B' THEN -Amount ELSE Amount END) As Payable, Employee
FROM Payroll A
WHERE Company = @Company AND Month = @Month AND Year = @Year
GROUP BY Employee
</code>```

And this is the result of the query:

```<code>| Payable | Employee |
| -----   | -------- |
| 500     |  001     |
| -200    |  001     |
| 500     |  002     |
| -100    |  002     |
</code>```

Instead of sum up the value, both positive and negative is displayed as different rows.

Any help please?

答:
You have to use the table name and you have to repeat the conditions and filter for the employee:

```<code>(SELECT SUM(Amount) FROM Payroll WHERE Type = 'A' AND Company = @Company AND Month = @Month AND Year = @Year AND Employee = A.Employee)
</code>```

But you can also use a different approach which doesn't need a subselect at all:

```<code>SELECT
 SUM(Amount * CASE WHEN = 'A' THEN 1 ELSE -1 END) As Payable, Employee
FROM Payroll A
WHERE Company = @Company AND Month = @Month AND Year = @Year
GROUP BY Employee
</code>```

Body:
I have the data below:

| Amount | Type | Employee |
| -----  | ---- | -------- |
| 500   |  A   |  001     |
| 200   |  B   |  001     |
| 300   |  A   |  002     |
| 200   |  A   |  002     |
| 100   |  B   |  002     |

In the scenario above, all Type A columns are positive values, and Type B are negative values.

I need to calculate the amount of each employee with positive minus negative as the end result, which means Type A minus Type B.

So Employee 001 should have the result 500 - 200 = 300, and Employee 002 is 300 + 200 - 100 = 400.

I have following incomplete query:

SELECT
 (SELECT SUM(Amount) FROM A WHERE Type = 'A') -
 (SELECT SUM(Amount) FROM A WHERE Type = 'B') As Payable, Employee
FROM Payroll A
WHERE Company = @Company AND Month = @Month AND Year = @Year
GROUP BY Employee

In the query above, the statement SELECT SUM(Amount) FROM A WHERE Type = 'A' is trying to get the positive Amount of the Payroll table which is already filtered by Company, Month and Year column. It didn't work because A is not recognize as a valid object.

So what should I do to get the data from the filtered Payroll table rather than I have to put in the WHERE condition again into both subquery?

EDIT:

Thanks Kannan and Thomas for the suggestion, but I still have problem achieving the desire result. Right now, this is my modified query with CASE

SELECT
 SUM(CASE WHEN Type = 'B' THEN -Amount ELSE Amount END) As Payable, Employee
FROM Payroll A
WHERE Company = @Company AND Month = @Month AND Year = @Year
GROUP BY Employee

And this is the result of the query:

| Payable | Employee |
| -----   | -------- |
| 500     |  001     |
| -200    |  001     |
| 500     |  002     |
| -100    |  002     |

Instead of sum up the value, both positive and negative is displayed as different rows.

Any help please?

Body:
You have to use the table name and you have to repeat the conditions and filter for the employee:

(SELECT SUM(Amount) FROM Payroll WHERE Type = 'A' AND Company = @Company AND Month = @Month AND Year = @Year AND Employee = A.Employee)

But you can also use a different approach which doesn't need a subselect at all:

SELECT
 SUM(Amount * CASE WHEN = 'A' THEN 1 ELSE -1 END) As Payable, Employee
FROM Payroll A
WHERE Company = @Company AND Month = @Month AND Year = @Year
GROUP BY Employee


问:
Easy way of handling different user / pass for DB on dev. machine vs production server
I usually have a config-file with some global variables for database connectivity settings (such as db host, db name, user, pass).

I also really like to be able to just drag and drop all files from my dev machine to the production server. However, development db host etc may be different from the one on the production server.

Is there an easy way of, in PHP, saying something like "if I'm on the dev-machine, use these values"? (I'd prefer to avoid hacks based on host IP / name.) I'm thinking of something like perhaps setting something in php.ini or httpd.conf so that for instance $DEV_MACHINE, is set to true on the dev machine.

答:
I usually use a file called config-local.php which is not under the source control.

If the file is absent, the app shows a warning page saying "finish the setup", or just runs a master to set up database credentials etc.


问:
Replacing a string at a particular positiion
I have a text file with Name at position 0-10, phone at 11-20.

How can I replace a string at location 11 to contain all 9's?

I've been playing around with Get-Content and -replace to get familiar.

```<code>$path = "g:\test.txt"
(Get-Content $path) -replace "Name", "Forename" | Out-File $path
</code>```

Example :

```<code>STARTDELIV|BA|BATCH PRINT               |
INFORMAT01|email@address.com            |
INFORMAT02|01021990|CRZWS|AA|2          |
INFORMAT03|Mr. John Doe|+00000          |
</code>```

So say I would like to replace the name Mr. John Doe with X's , how would I prevent it replacing the same 10 bytes on every line

答:
You could use the SubString method to get the 10 characters of the string starting from position 11:

```<code>$Path = "g:\test.txt"
$String = (Get-Content $Path)
$StringToReplace = $String.Substring(11,10)
</code>```

And then use -Replace to replace that part of the string with all 9s (beware this assumes that string doesn't occur in that way anywhere else in the string):

```<code>$String -Replace $StringToReplace,('9'*$StringToReplace.Length)
</code>```

Here's a shorter single line way to achieve the same result:

```<code>$String.Replace($String.Substring(11,10),'9'*10)
</code>```

Body:
I have a text file with Name at position 0-10, phone at 11-20.

How can I replace a string at location 11 to contain all 9's?

I've been playing around with Get-Content and -replace to get familiar.

$path = "g:\test.txt"
(Get-Content $path) -replace "Name", "Forename" | Out-File $path

Example :

STARTDELIV|BA|BATCH PRINT               |
INFORMAT01|email@address.com            |
INFORMAT02|01021990|CRZWS|AA|2          |
INFORMAT03|Mr. John Doe|+00000          |

So say I would like to replace the name Mr. John Doe with X's , how would I prevent it replacing the same 10 bytes on every line

Body:
You could use the SubString method to get the 10 characters of the string starting from position 11:

$Path = "g:\test.txt"
$String = (Get-Content $Path)
$StringToReplace = $String.Substring(11,10)

And then use -Replace to replace that part of the string with all 9s (beware this assumes that string doesn't occur in that way anywhere else in the string):

$String -Replace $StringToReplace,('9'*$StringToReplace.Length)

Here's a shorter single line way to achieve the same result:

$String.Replace($String.Substring(11,10),'9'*10)


问:
Export SQL server data into a CSV file
I've just taken care of a project that requires converting data from the old website (built in C# web form) to the new one (using PHP).

In the old database, there is a product table contains 1600 products that I need to export into a CSV file then import to the new database but I have no idea to do that.

I can access the current server but I don't see any .cs file (code-behind file). I also have no idea how to export that table to a CSV file using myLittleTools (The SQL server management tool that Plesk provide).

Can any have me please?

Thank you very much.

答: According to the MyLittleAdmin site you can opent the table to view the data and export it form there.</p>

Title: Export SQL server data into a CSV file


问:
How to create a reusable component in VueJs?
I would like to create Side Panel as a reusable component in Framework7 with VueJS. Here is my code..

Card.vue

```<code><f7-card>
  <f7-card-header>Card header content</f7-card-header>
  <f7-card-content><img src="https://wiki.videolan.org/images/Ubuntu-logo.png"></img></f7-card-content>
  <f7-card-footer>Card footer content</f7-card-footer>
</f7-card>
</code>```

Now i registered as a component like below,

```<code>import Vue from 'vue'
export default [
    {
        path: '/card/',
        component: require('./Card')
    },
]
</code>```

In later vues i imported as,

```<code>import Card from './Card.vue'
</code>```

and i try to access in another vues like,

Now i'm getting an error like

[Vue warn]: Unknown custom element:  - did you register the
  component correctly? For recursive components, make sure to provide
  the "name" option.

Can anyone help me where have i mistaken?

Thanks,

Body:
I would like to create Side Panel as a reusable component in Framework7 with VueJS. Here is my code..

Card.vue

<f7-card>
  <f7-card-header>Card header content</f7-card-header>
  <f7-card-content></f7-card-content>
  <f7-card-footer>Card footer content</f7-card-footer>
</f7-card>

Now i registered as a component like below,

import Vue from 'vue'
export default [
    {
        path: '/card/',
        component: require('./Card')
    },
]

In later vues i imported as,

import Card from './Card.vue'

and i try to access in another vues like,

Now i'm getting an error like

[Vue warn]: Unknown custom element:  - did you register the
  component correctly? For recursive components, make sure to provide
  the "name" option.

Can anyone help me where have i mistaken?

Thanks,

Body: Are you showing us all of Card.vue? For a valid  single-file vue component, I would expect to see <template>, <script> and <style> elements. The render function will be generated from whatever you put in the <template> element.


问:
How to make a button not show up but still be used by javascript?
I am using a button that has to be invible and should be used by a javascript function.

```<code><asp:Button ID ="btnDummy1" runat="server" Visible ="true" OnClick="btnSubmit1_Click" width="0px" height="0px"/
</code>```

I cannot keep visible = false as it the javascript will not use invible content in the poage. I havetried to give width=0 and height=0, still it showws up in Chrome. What do you guys think i should do?

Thanks in advance :)

答:
I think the first question you should ask yourself is : why would I put in my HTML doc a button that should not be visible ?

An HTML document should be used ONLY TO DESCRIBE A CONTENT'S SEMANTICS. So an HTML doc should ONLY contain the content you want to publish and extra data to explain the content's SEMANTIC !! NOTHING about the way it is displayed, NOTHING about the way it behaves !!

All displaying and behaviors questions should be managed with CSS and Javascript, NEVER within HTML itself.

Any element needed for Javascript only purpose should be added in the doc by Javascript itself !

You should never find, in an HTML doc, such things as prev/next buttons for a javascript picture gallery for example. The HTML doc should only contain the pictures list, than your JS script will change the way this list is shown, making it a eye candy gallery and add buttons for navigation.

So in your example, your saying you want to add in your HTML doc an invisible button with some Javascript actions on it.... that's probably an example of some content that should never be in the HTML doc.

Body:
I am using a button that has to be invible and should be used by a javascript function.

<asp:Button ID ="btnDummy1" runat="server" Visible ="true" OnClick="btnSubmit1_Click" width="0px" height="0px"/

I cannot keep visible = false as it the javascript will not use invible content in the poage. I havetried to give width=0 and height=0, still it showws up in Chrome. What do you guys think i should do?

Thanks in advance :)


问:
Adding Methods to Constructors
Refactor the carlike function in a way that allows us to use the method calling syntax with "dot access".

var carlike = function(obj, loc) {
  obj.loc = loc;
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);

/*
Here we want to call move with "dot access"

amy.move();
ben.move();
*/```
</div>
</div>
</p>

<p><strong>THIS IS WHAT I'VE DONE...</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;//CHANGE#1
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3</code>```

BUT IT WON'T WORK IT'S HAVING ERROR REGARDING LOCATION VARIABLE WHICH WAS WORKING GOOD UNTIL!

Thank You in Advance ☺

答:
```<code>obj.move = move.bind(window,obj);
</code>```

You may want to bind obj to the car parameter, so when you call move it gets automatically set. However, i would restructure the whole code like this (using class syntax):

```<code>class Car {
 constructor(val=0){
    this.loc=val;
 }
 move(distance=1){
  this.loc+=distance;
 }
 set(pos){
  this.loc=pos;
 }
}

var ben=new Car(10);
console.log(ben.loc);
ben.move();
</code>```

Title: Adding Methods to Constructors

Body:
Refactor the carlike function in a way that allows us to use the method calling syntax with "dot access".

var carlike = function(obj, loc) {
  obj.loc = loc;
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);

/*
Here we want to call move with "dot access"

amy.move();
ben.move();
*/

THIS IS WHAT I'VE DONE...

var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;//CHANGE#1
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3

BUT IT WON'T WORK IT'S HAVING ERROR REGARDING LOCATION VARIABLE WHICH WAS WORKING GOOD UNTIL!

Thank You in Advance ☺

Body:
obj.move = move.bind(window,obj);

You may want to bind obj to the car parameter, so when you call move it gets automatically set. However, i would restructure the whole code like this (using class syntax):

class Car {
 constructor(val=0){
    this.loc=val;
 }
 move(distance=1){
  this.loc+=distance;
 }
 set(pos){
  this.loc=pos;
 }
}

var ben=new Car(10);
console.log(ben.loc);
ben.move();


问:
Can we extract view data into insert scripts in SQL Server?
I am using SQL server and I need to extract the data in view to insert queries. I have used Generate Scripts -> Data Only option in Tasks to do it.

I was able to extract only the create statement of the view in that file not the insert queries. When I tried the same thing on a table instead of view, I am able to extract the insert queries.

Then, I wrote the data of the view into a table and extracted the insert queries. Am I missing anything here? Or is it a known behavior?

答:
You can use

```<code>SELECT * INTO ATable FROM AView
</code>```

and then script out the table it created...

The reason you cannot script data from the view is because the view does not contain any data its self, it is just a saved query... so you can script its definition, but it does not make sense to say the view's data, as the data the view presents is actually in some tables, not the view. Saving the RESULTS of the view into a table, makes it into data.

Body:
You can use

SELECT * INTO ATable FROM AView

and then script out the table it created...

The reason you cannot script data from the view is because the view does not contain any data its self, it is just a saved query... so you can script its definition, but it does not make sense to say the view's data, as the data the view presents is actually in some tables, not the view. Saving the RESULTS of the view into a table, makes it into data.


问:
awk on a field captured by awk
I can't find a proper way to parse a field that was already retrieved by awk.

Using awk I collect the nth element that looks like that:

```<code>bbr:(bw:492.2Mbps,mrtt:0.412,pacing_gain:1.25,cwnd_gain:2)
</code>```

I would like to parse once again this nth field in order to collect the data:

```<code>$1 = 492.2;
$2 = 0.41;
$3 = 1.25;
$4 = 2;
</code>```

If you have any suggestion, you would be pleased to hear it

G.

答:
In this case the string is stored to a file, read to $0, cleaned, splited to hash a and outputed in a for loop:

```<code>$ awk '{gsub(/^.*\(|\)$/,"");n=split($0,a,/[:,]/);for(i=2;i<=n;i+=2)print a[i]}' file
492.2Mbps
0.412
1.25
2
</code>```

Explained:

```<code>gsub(/^.*\(|\)$/,"")     # clean outside of parentheses, including them
n=split($0,a,/[:,]/)     # split to a
for(i=2;i<=n;i+=2)       # further process every other element in a
    print a[i]           # you could remove the Mbps and what not here
</code>```

Title: awk on a field captured by awk

Body:
I can't find a proper way to parse a field that was already retrieved by awk.

Using awk I collect the nth element that looks like that:

bbr:(bw:492.2Mbps,mrtt:0.412,pacing_gain:1.25,cwnd_gain:2)

I would like to parse once again this nth field in order to collect the data:

$1 = 492.2;
$2 = 0.41;
$3 = 1.25;
$4 = 2;

If you have any suggestion, you would be pleased to hear it

G.

Body:
In this case the string is stored to a file, read to $0, cleaned, splited to hash a and outputed in a for loop:

$ awk '{gsub(/^.*\(|\)$/,"");n=split($0,a,/[:,]/);for(i=2;i<=n;i+=2)print a[i]}' file
492.2Mbps
0.412
1.25
2

Explained:

gsub(/^.*\(|\)$/,"")     # clean outside of parentheses, including them
n=split($0,a,/[:,]/)     # split to a
for(i=2;i<=n;i+=2)       # further process every other element in a
    print a[i]           # you could remove the Mbps and what not here


问:
How to Kill or Abort Task.Run or Task.Factory.StartNew() in C#
I have situation where i have to Use Task.Run In my ForEach loop

Requirement:
I'm going to be forced to manually kill thread
I have button where i can start and stop this Thread or Task.Run in For loop.

Problem
My problem is when i start the Task.Run method Its running but when i try to stop with using CancellationTokenSource or runningTaskThread.Abort(); it will not kill. its just stop when i start new Task.Run at that time it run with old thread so it become multiple thread every start process.

Code:

Below is my code for start Thread

```<code> var messages = rootObject.MultiQData.Messages.Where(m => m.TimeStamp > DateTime.Now).OrderBy(x => x.TimeStamp).ToList();
                                //Simulate MultiQ file in BackGroud
                                if (messages.Count > 0)
                                {
                                    cancellationTokenSource = new CancellationTokenSource();
                                    cancellationToken = cancellationTokenSource.Token;
                                    Task.Factory.StartNew(
                                        () =>
                                        {
                                            runningTaskThread = Thread.CurrentThread;
                                            messages.ForEach(
                                                m => SetUpTimer(m, rootObject.MultiQData.Connection.FleetNo));
                                        }, cancellationToken);
                                }
</code>```

For stop Task.Run

```<code> if (cancellationTokenSource != null)
            {
                if (cancellationToken.IsCancellationRequested)
                    return;
                else
                    cancellationTokenSource.Cancel();
            }
</code>```

I have also use Thread with Thread.Abort but it is not working

Please Help to solve this issue

答:
I got solution using timer.Stop(),timer.Dispose(). On creation of Thread i am calling  SetUpTimer and this SetupTimer i have created multiple timer.

So on call of stop thread i have dispose timer and its work for me

For reference see below code

```<code>private void SetUpTimer(Message message, string fleetNo)
        {
            var ts = new MessageTimer();

            var interval = (message.TimeStamp - DateTime.Now).TotalMilliseconds;
            interval = interval <= 0 ? 100 : interval;

            ts.MessageWrapper = new MessageWrapper(message, fleetNo);
            ts.Interval = interval;
            ts.Elapsed += ts_Elapsed;
            ts.Start();

            //Add timer in to the lost for disposing timer at time of stop Simulation
            lsTimers.Add(ts);
        }
</code>```

```<code>    private void StopTask()
    {
        try
        {
            // Attempt to cancel the task politely
            if (cancellationTokenSource != null)
            {
                if (cancellationToken.IsCancellationRequested)
                    return;
                else
                    cancellationTokenSource.Cancel();
            }

            //Stop All Timer
            foreach (var timer in lsTimers)
            {
                timer.Stop();
                timer.Dispose();
            }
        }
        catch (Exception ex)
        {
            errorLogger.Error("Error while Stop simulation :", ex);
        }

    }
</code>```

Body:
I have situation where i have to Use Task.Run In my ForEach loop

Requirement:
I'm going to be forced to manually kill thread
I have button where i can start and stop this Thread or Task.Run in For loop.

Problem
My problem is when i start the Task.Run method Its running but when i try to stop with using CancellationTokenSource or runningTaskThread.Abort(); it will not kill. its just stop when i start new Task.Run at that time it run with old thread so it become multiple thread every start process.

Code:

Below is my code for start Thread

 var messages = rootObject.MultiQData.Messages.Where(m => m.TimeStamp > DateTime.Now).OrderBy(x => x.TimeStamp).ToList();
                                //Simulate MultiQ file in BackGroud
                                if (messages.Count > 0)
                                {
                                    cancellationTokenSource = new CancellationTokenSource();
                                    cancellationToken = cancellationTokenSource.Token;
                                    Task.Factory.StartNew(
                                        () =>
                                        {
                                            runningTaskThread = Thread.CurrentThread;
                                            messages.ForEach(
                                                m => SetUpTimer(m, rootObject.MultiQData.Connection.FleetNo));
                                        }, cancellationToken);
                                }

For stop Task.Run

 if (cancellationTokenSource != null)
            {
                if (cancellationToken.IsCancellationRequested)
                    return;
                else
                    cancellationTokenSource.Cancel();
            }

I have also use Thread with Thread.Abort but it is not working

Please Help to solve this issue

Body:
I got solution using timer.Stop(),timer.Dispose(). On creation of Thread i am calling  SetUpTimer and this SetupTimer i have created multiple timer.

So on call of stop thread i have dispose timer and its work for me

For reference see below code

private void SetUpTimer(Message message, string fleetNo)
        {
            var ts = new MessageTimer();

            var interval = (message.TimeStamp - DateTime.Now).TotalMilliseconds;
            interval = interval <= 0 ? 100 : interval;

            ts.MessageWrapper = new MessageWrapper(message, fleetNo);
            ts.Interval = interval;
            ts.Elapsed += ts_Elapsed;
            ts.Start();

            //Add timer in to the lost for disposing timer at time of stop Simulation
            lsTimers.Add(ts);
        }

    private void StopTask()
    {
        try
        {
            // Attempt to cancel the task politely
            if (cancellationTokenSource != null)
            {
                if (cancellationToken.IsCancellationRequested)
                    return;
                else
                    cancellationTokenSource.Cancel();
            }

            //Stop All Timer
            foreach (var timer in lsTimers)
            {
                timer.Stop();
                timer.Dispose();
            }
        }
        catch (Exception ex)
        {
            errorLogger.Error("Error while Stop simulation :", ex);
        }

    }


问:
How to fire click event for choosing each plot in google map drawing manager function?
I'm using google map javascript api to create labs for runner. I need to set marker icon for clicking each plot points. In this case i'm able to draw a line but can't able to set icon in each plots. How to achieve this? I'm struggling past one week to get this done.</p>

```<code>const me = this;
    const drawingManager = new google.maps.drawing.DrawingManager({
      drawingMode: google.maps.drawing.OverlayType.POLYLINE,
      drawingControl: false,
      circleOptions: {
        fillColor: '#a8aaa9',
        fillOpacity: 0.3,
        strokeWeight: 0,
        clickable: false,
        editable: true,
        zIndex: 1,
      },
    });

    drawingManager.setMap(this.map);

    google.maps.event.addListener(drawingManager, 'overlaycomplete', OverlayCompleteEvent => {
      const bounds = OverlayCompleteEvent.overlay.getPath().getArray();
      me.setState({
        collectedCordinates: bounds,
      });
    });

    google.maps.event.addListener(drawingManager, 'click', function(){
      // not firing here
    });
</code>```

答:
From Google Maps API documentation:

Note that google.maps.Map events, such as click and mousemove are disabled while drawing on the map.

Drawing Layer(Library)

If i got your goal correctly, you can try it by adding icon (in this example-Marker for each plot):

```<code>  google.maps.event.addListener(drawingManager, 'overlaycomplete', OverlayCompleteEvent => {
    const bounds = OverlayCompleteEvent.overlay.getPath().getArray();
    me.setState({
      collectedCordinates: bounds,
    });

    bounds.map((coord, i)=>{
      const marker = new google.maps.Marker({
        position: {lat: coord.lat(), lng: coord.lng()},
        map: map,
        title: 'marker ' + i
      })
    });
  });
</code>```

Body:
I'm using google map javascript api to create labs for runner. I need to set marker icon for clicking each plot points. In this case i'm able to draw a line but can't able to set icon in each plots. How to achieve this? I'm struggling past one week to get this done.

const me = this;
    const drawingManager = new google.maps.drawing.DrawingManager({
      drawingMode: google.maps.drawing.OverlayType.POLYLINE,
      drawingControl: false,
      circleOptions: {
        fillColor: '#a8aaa9',
        fillOpacity: 0.3,
        strokeWeight: 0,
        clickable: false,
        editable: true,
        zIndex: 1,
      },
    });

    drawingManager.setMap(this.map);

    google.maps.event.addListener(drawingManager, 'overlaycomplete', OverlayCompleteEvent => {
      const bounds = OverlayCompleteEvent.overlay.getPath().getArray();
      me.setState({
        collectedCordinates: bounds,
      });
    });

    google.maps.event.addListener(drawingManager, 'click', function(){
      // not firing here
    });

Body:
From Google Maps API documentation:

Note that google.maps.Map events, such as click and mousemove are disabled while drawing on the map.

Drawing Layer(Library)

If i got your goal correctly, you can try it by adding icon (in this example-Marker for each plot):

  google.maps.event.addListener(drawingManager, 'overlaycomplete', OverlayCompleteEvent => {
    const bounds = OverlayCompleteEvent.overlay.getPath().getArray();
    me.setState({
      collectedCordinates: bounds,
    });

    bounds.map((coord, i)=>{
      const marker = new google.maps.Marker({
        position: {lat: coord.lat(), lng: coord.lng()},
        map: map,
        title: 'marker ' + i
      })
    });
  });


问:
My boolean value is false even though all the code is correct
About my Program:

My algorithm(this class) is meant to check whether a delivery has been finished and afterwards makes the truck/trailer/driver available for another delivery, at the same time this algorithm sends another truck/trailer/driver on a delivery. To sum it up this class does the following:

Check whether a booking is in Allocation mode (Allocation mode basically means that the "booking" is in progress of being delivered

Check whether there is tonnage left of the booking (Ex. I want to sent 500 ton to a place, but a delivery can only be 30 ton at a time so it checks if there is still ton that needs to be delivered)

To make the Driver(s)/Truck(s)/Trailer(s) available that finished their delivery.

To automatically allocate tonnage to a Driver/Trailer/Truck.

Deleting entries that are finished (any bookings that are finished - Logs still stay in the database).

My Problem:

I have no idea what is wrong with my class, I have been hours at it and can't seem to figure out what is causing my boolean variable (forLoopBreak) to trigger a "false" value when it is calling the method checkAvailTrailers(). The problem seems to be in there but I can't figure out what causes the problem.

Class:

```<code>[https://pastebin.com/4up8eppd][1]
</code>```

( I couldn't paste it here as I met the limit of characters)

Notes:

I know my programming looks but, but I am still new to this.

I decided to attach the whole class as the problem may be at a different place.

Edit:

My code is too large to investigate so here is the relevant parts:

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

                  checkAvailTrailers();
                        if (forloopBreak == false)
                        {
                            setErrorMessage("Avail Trailers not enough!");
                        }
}
</code>```

private void checkAvailTrailers()

    {

```<code>    string trailerRouteAllocation = null;
    string trailerVragAllocation = null;
    string tempHolderTrailer = null;
    string myNewTempT = null;
    string trailermyTemp = null;

    int trailerCount = 0;
    int tempTra = -1;

    //Gets trailer route classification
    using (SqlCommand selectTrailer = new SqlCommand("SELECT [TR_Routes] FROM dbo.TrailerDetail  WHERE [TR_Allocation] = " + 0, con))
    {
        using (SqlDataReader reader = selectTrailer.ExecuteReader())
        {
            while (reader.Read())
            {
                trailerRouteAllocation = reader.GetString(0);
                tempHolderTrailer = trailerRouteAllocation;
                myNewTempT = trailerRouteAllocation;

                for (int l = 0; l < tempHolderTrailer.Length; l++)
                {
                    tempTra = myNewTempT.IndexOf(",");
                    if (tempTra >= 0)
                    {
                        trailermyTemp = myNewTempT.Substring(0,tempTra);
                    }
                    else
                    {
                        trailermyTemp = myNewTempT;
                        if (trailermyTemp == myCurrentBookingRoute.ToString())
                        {
                            mycurrentTrailerAvailableRoute[trailerCount] = tempHolderTrailer;
                        }
                        break;

                    }
                    myNewTempT = myNewTempT.Substring(tempTra + 1);
                    if (trailermyTemp == myCurrentBookingRoute.ToString())
                    {
                        mycurrentTrailerAvailableRoute[trailerCount] = trailerRouteAllocation;
                    }
                }
                trailerCount++;
            }
            reader.Close();
        }
    }
    //gets trailer vrag classification.
    int countTrailerVrag = 0;
    for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
    {
        if (mycurrentTrailerAvailableRoute[l] != null)
        {
            using (SqlCommand select = new SqlCommand("Select [TR_Classification] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "' AND [TR_Allocation] = " + 0, con))
            {
                using (SqlDataReader readerS = select.ExecuteReader())
                {
                        while (readerS.Read())
                        {
                            trailerVragAllocation = readerS.GetString(0);
                            myAvailableTrailerVragClassification[countTrailerVrag] = trailerVragAllocation;
                            countTrailerVrag++;
                        }
                        readerS.Close();
                }
            }
        }
    }

    int countTrailers = 0;
    string trailerRegNum = null;
    for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
    {
        if (mycurrentTrailerAvailableRoute[l] != null)
        {
            using (SqlCommand selectT = new SqlCommand("Select [TR_RegNumber] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "'" + " AND [TR_Classification] = '" + myAvailableTrailerVragClassification[l] + "' AND [TR_Allocation] = " + 0, con))
            {
                 SqlDataReader readerT = selectT.ExecuteReader();
                    if (readerT.HasRows)
                    {
                        while (readerT.Read())
                        {
                            trailerRegNum = readerT.GetString(0);
                            myAvailableCurrentTraillerRegNumber[countTrailers] = trailerRegNum;
                            countTrailers++;
                        }
                    }
                    else
                    {
                        forloopBreak = false;
                    }
                readerT.Close();
            }
        }
    }//END OF TRAILER CHECKING

    //gets trailer's max tonnage
    int myTrailerTonMax = 0;
    int myTrailerTon = 0;

    for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
    {
        if (mycurrentTrailerAvailableRoute[l] != null)
        {
            using (SqlCommand selectT = new SqlCommand("Select [TR_MaxTonnage] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "'" + " AND [TR_Classification] = '" + myAvailableTrailerVragClassification[l] + "'", con))
            {
                using (SqlDataReader readerS = selectT.ExecuteReader())
                {
                    while (readerS.Read())
                    {
                        myTrailerTon = readerS.GetInt32(0);
                        myTrailerAvailableTonMax[myTrailerTonMax] = myTrailerTon;
                        myTrailerTonMax++;
                    }
                    readerS.Close();
                }
            }
        }
    }
}
</code>```

Extra:
- The data in my database matches the criteria, the while loop even executes but in the end my boolean value returns a false.

答:
The readerT.HasRows clause will always be true if there is any data initially in the reader. Here is the property's description from the MSDN page

Gets a value that indicates whether the SqlDataReader contains one or more rows.

What you want to do instead (I assume) is set forloopBreak = false; when the while loop is finished. So inside the using block you put this:

```<code>SqlDataReader readerT = selectT.ExecuteReader();
while (readerT.Read())
{
     trailerRegNum = readerT.GetString(0);
     myAvailableCurrentTraillerRegNumber[countTrailers] = trailerRegNum;
     countTrailers++;
}
forloopBreak = false;
readerT.Close();
</code>```

Let me know if this works!

Body:
About my Program:

My algorithm(this class) is meant to check whether a delivery has been finished and afterwards makes the truck/trailer/driver available for another delivery, at the same time this algorithm sends another truck/trailer/driver on a delivery. To sum it up this class does the following:

Check whether a booking is in Allocation mode (Allocation mode basically means that the "booking" is in progress of being delivered

Check whether there is tonnage left of the booking (Ex. I want to sent 500 ton to a place, but a delivery can only be 30 ton at a time so it checks if there is still ton that needs to be delivered)

To make the Driver(s)/Truck(s)/Trailer(s) available that finished their delivery.

To automatically allocate tonnage to a Driver/Trailer/Truck.

Deleting entries that are finished (any bookings that are finished - Logs still stay in the database).

My Problem:

I have no idea what is wrong with my class, I have been hours at it and can't seem to figure out what is causing my boolean variable (forLoopBreak) to trigger a "false" value when it is calling the method checkAvailTrailers(). The problem seems to be in there but I can't figure out what causes the problem.

Class:

[https://pastebin.com/4up8eppd][1]

( I couldn't paste it here as I met the limit of characters)

Notes:

I know my programming looks but, but I am still new to this.

I decided to attach the whole class as the problem may be at a different place.

Edit:

My code is too large to investigate so here is the relevant parts:

private void startAlgo()
{

                  checkAvailTrailers();
                        if (forloopBreak == false)
                        {
                            setErrorMessage("Avail Trailers not enough!");
                        }
}

private void checkAvailTrailers()

    {

    string trailerRouteAllocation = null;
    string trailerVragAllocation = null;
    string tempHolderTrailer = null;
    string myNewTempT = null;
    string trailermyTemp = null;

    int trailerCount = 0;
    int tempTra = -1;

    //Gets trailer route classification
    using (SqlCommand selectTrailer = new SqlCommand("SELECT [TR_Routes] FROM dbo.TrailerDetail  WHERE [TR_Allocation] = " + 0, con))
    {
        using (SqlDataReader reader = selectTrailer.ExecuteReader())
        {
            while (reader.Read())
            {
                trailerRouteAllocation = reader.GetString(0);
                tempHolderTrailer = trailerRouteAllocation;
                myNewTempT = trailerRouteAllocation;

                for (int l = 0; l < tempHolderTrailer.Length; l++)
                {
                    tempTra = myNewTempT.IndexOf(",");
                    if (tempTra >= 0)
                    {
                        trailermyTemp = myNewTempT.Substring(0,tempTra);
                    }
                    else
                    {
                        trailermyTemp = myNewTempT;
                        if (trailermyTemp == myCurrentBookingRoute.ToString())
                        {
                            mycurrentTrailerAvailableRoute[trailerCount] = tempHolderTrailer;
                        }
                        break;

                    }
                    myNewTempT = myNewTempT.Substring(tempTra + 1);
                    if (trailermyTemp == myCurrentBookingRoute.ToString())
                    {
                        mycurrentTrailerAvailableRoute[trailerCount] = trailerRouteAllocation;
                    }
                }
                trailerCount++;
            }
            reader.Close();
        }
    }
    //gets trailer vrag classification.
    int countTrailerVrag = 0;
    for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
    {
        if (mycurrentTrailerAvailableRoute[l] != null)
        {
            using (SqlCommand select = new SqlCommand("Select [TR_Classification] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "' AND [TR_Allocation] = " + 0, con))
            {
                using (SqlDataReader readerS = select.ExecuteReader())
                {
                        while (readerS.Read())
                        {
                            trailerVragAllocation = readerS.GetString(0);
                            myAvailableTrailerVragClassification[countTrailerVrag] = trailerVragAllocation;
                            countTrailerVrag++;
                        }
                        readerS.Close();
                }
            }
        }
    }

    int countTrailers = 0;
    string trailerRegNum = null;
    for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
    {
        if (mycurrentTrailerAvailableRoute[l] != null)
        {
            using (SqlCommand selectT = new SqlCommand("Select [TR_RegNumber] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "'" + " AND [TR_Classification] = '" + myAvailableTrailerVragClassification[l] + "' AND [TR_Allocation] = " + 0, con))
            {
                 SqlDataReader readerT = selectT.ExecuteReader();
                    if (readerT.HasRows)
                    {
                        while (readerT.Read())
                        {
                            trailerRegNum = readerT.GetString(0);
                            myAvailableCurrentTraillerRegNumber[countTrailers] = trailerRegNum;
                            countTrailers++;
                        }
                    }
                    else
                    {
                        forloopBreak = false;
                    }
                readerT.Close();
            }
        }
    }//END OF TRAILER CHECKING

    //gets trailer's max tonnage
    int myTrailerTonMax = 0;
    int myTrailerTon = 0;

    for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
    {
        if (mycurrentTrailerAvailableRoute[l] != null)
        {
            using (SqlCommand selectT = new SqlCommand("Select [TR_MaxTonnage] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "'" + " AND [TR_Classification] = '" + myAvailableTrailerVragClassification[l] + "'", con))
            {
                using (SqlDataReader readerS = selectT.ExecuteReader())
                {
                    while (readerS.Read())
                    {
                        myTrailerTon = readerS.GetInt32(0);
                        myTrailerAvailableTonMax[myTrailerTonMax] = myTrailerTon;
                        myTrailerTonMax++;
                    }
                    readerS.Close();
                }
            }
        }
    }
}

Extra:
- The data in my database matches the criteria, the while loop even executes but in the end my boolean value returns a false.

Body:
The readerT.HasRows clause will always be true if there is any data initially in the reader. Here is the property's description from the MSDN page

Gets a value that indicates whether the SqlDataReader contains one or more rows.

What you want to do instead (I assume) is set forloopBreak = false; when the while loop is finished. So inside the using block you put this:

SqlDataReader readerT = selectT.ExecuteReader();
while (readerT.Read())
{
     trailerRegNum = readerT.GetString(0);
     myAvailableCurrentTraillerRegNumber[countTrailers] = trailerRegNum;
     countTrailers++;
}
forloopBreak = false;
readerT.Close();

Let me know if this works!


问:
Open Lock screen for android app in setting screen with DevicePolicyManager
```<code>I'm able to change the password,pin or Pattern from the below code, on Click function of Switch.

switchPreferenceAppLock.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                    @Override
                    public boolean onPreferenceChange(Preference preference, Object newValue) {
                        if (!((Boolean) newValue)) {

                        } else {
                            Log.d("Test", "Change to Phone Default Lock");

                            Intent intent = new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD);
                        startActivity(intent);
                        return true;
                    }
                });
            }
</code>```

My purpose is to use the user's phone security factor (like pattern, pin, password) in my app. Like if in my app user wants to do any critical function then security screen will be appeared and will ask to authenticate and after the authentication, i will allow the user to do the functionality.

But It is only used to change the password,I want to set this to lock the phone instead of changing.The Intent DevicePolicyManager.ACTION_SET_NEW_PASSWORD will only be used to change the password.How Can I set the app lock int he same setting screen of my App.

答:
On API 21+ you can use KeyguardManager.createConfirmDeviceCredentialIntent(...) to create a new Intent that will take the user to the lock screen to confirm the identity, which you can start with startActivityForResult(...). Here's a quick sample for starting the lock screen intent:

```<code>KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE)
boolean isSecure = keyguardManager.isKeyguardSecure();

if (isSecure) {
    Intent intent = keyguardManager.createConfirmDeviceCredentialIntent(null, null);
    startActivityForResult(intent, YOUR_REQUEST_CODE);
} else {
    // no lock screen set, show the new lock needed screen
}
</code>```

Then you check the results:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case YOUR_REQUEST_CODE:
            if (resultCode == RESULT_OK) {
                // user authenticated
            } else {
                // user did not authenticate
            }
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
    }
}
</code>```

Body:
I'm able to change the password,pin or Pattern from the below code, on Click function of Switch.

switchPreferenceAppLock.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                    @Override
                    public boolean onPreferenceChange(Preference preference, Object newValue) {
                        if (!((Boolean) newValue)) {

                        } else {
                            Log.d("Test", "Change to Phone Default Lock");

                            Intent intent = new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD);
                        startActivity(intent);
                        return true;
                    }
                });
            }

My purpose is to use the user's phone security factor (like pattern, pin, password) in my app. Like if in my app user wants to do any critical function then security screen will be appeared and will ask to authenticate and after the authentication, i will allow the user to do the functionality.

But It is only used to change the password,I want to set this to lock the phone instead of changing.The Intent DevicePolicyManager.ACTION_SET_NEW_PASSWORD will only be used to change the password.How Can I set the app lock int he same setting screen of my App.

Body:
On API 21+ you can use KeyguardManager.createConfirmDeviceCredentialIntent(...) to create a new Intent that will take the user to the lock screen to confirm the identity, which you can start with startActivityForResult(...). Here's a quick sample for starting the lock screen intent:

KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE)
boolean isSecure = keyguardManager.isKeyguardSecure();

if (isSecure) {
    Intent intent = keyguardManager.createConfirmDeviceCredentialIntent(null, null);
    startActivityForResult(intent, YOUR_REQUEST_CODE);
} else {
    // no lock screen set, show the new lock needed screen
}

Then you check the results:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case YOUR_REQUEST_CODE:
            if (resultCode == RESULT_OK) {
                // user authenticated
            } else {
                // user did not authenticate
            }
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
    }
}


问:
What does it mean that "Flows in RxJava are sequential in nature..."
I'm reading the docs for RxJava and came across this which I don't really understand. https://github.com/ReactiveX/RxJava

Flows in RxJava are sequential in nature split into processing stages
  that may run concurrently with each other:

```<code>Flowable.range(1, 10)
  .observeOn(Schedulers.computation())
  .map(v -> v * v)
  .blockingSubscribe(System.out::println);
</code>```

Nothing about that block of code seems like it would run concurrently to me.

答: Squares the numbers from 1 to 10 on the computation (Worker) thread, and and consumes the results on the "main" thread. The lambda v -> v * v doesn't run in parallel, while v+1 * v+1 (range 1-10) is  executing on the computation thread System.out::println run for earlier v*v on main thread.

Body:
I'm reading the docs for RxJava and came across this which I don't really understand. https://github.com/ReactiveX/RxJava

Flows in RxJava are sequential in nature split into processing stages
  that may run concurrently with each other:

Flowable.range(1, 10)
  .observeOn(Schedulers.computation())
  .map(v -> v * v)
  .blockingSubscribe(System.out::println);

Nothing about that block of code seems like it would run concurrently to me.


问:
how to translate website right to left for arabic in WordPress?
1) I install the gtranslate plugin in my WordPress website and translate it in Arabic language but language only translate right to left not whole website I check another pluginin but they need to purchase for translate website like plygon, so it is possible using gtranslate. (I need only two language English and Arabic can I set also rtl tester on click on arbic using single click event call)

2) Can I set default language arabic using gtranslate wordpress plugin?

答:
First, you should use qTranslate-X plugin as the original qTranslate has been discontinued.

According to qTranslate-X documentation, the plugin supports RTL text, where it says:

RTL should get enabled by WordPress based on locale of active language

Maybe you need to set dir="rtl" when the current language is arabic, for example something like this in the  tag:

```<code><body<?php if(qtranxf_getLanguage() == 'ar') echo ' dir="rtl"' ?>>
</code>```

Body:
First, you should use qTranslate-X plugin as the original qTranslate has been discontinued.

According to qTranslate-X documentation, the plugin supports RTL text, where it says:

RTL should get enabled by WordPress based on locale of active language

Maybe you need to set dir="rtl" when the current language is arabic, for example something like this in the <body> tag:

<body<?php if(qtranxf_getLanguage() == 'ar') echo ' dir="rtl"' ?>>


问:
copy data using formula in excel
Please help, I have this situation. I am not sure how to solve with vlookup, if anyone can guide me that would be great help.

```<code>County  Status  Status Count
dublin  In      2
dublin  out     1
dublin  closed  10
donegal closed  2
donegal in      5
</code>```

Sheet 2 with

```<code>County  Economy     EconomyCount
dublin  good growth  23
dublin  average      15
donegal not good     14
</code>```

I want result as

```<code>County  Status  Status Count    Economy     EconomyCount
dublin  In      2               good growth  23
dublin  out     1               average      15
dublin  closed  10              N/A
donegal closed  2               not good     14
donegal in      5               N/A
</code>```

答:
Considering your Sheet1 is as

and Sheet2 is

Assuming you are matching for the first occurrence, then in Cell D2 of Sheet1 enter the formula

```<code>=IF(COUNTIF($A$2:$A2,$A2)=1,INDEX(Sheet2!$B$2:$B$3,MATCH($A2,Sheet2!$A$2:$A$3,0)),"N/A")
</code>```

and in Cell E2 of Sheet1 enter the following formula

```<code>=IF(COUNTIF($A$2:$A2,$A2)=1,INDEX(Sheet2!$C$2:$C$3,MATCH($A2,Sheet2!$A$2:$A$3,0)),"")
</code>```

Drag/Copy down as required. See image for reference.

Title: copy data using formula in excel

Body:
Please help, I have this situation. I am not sure how to solve with vlookup, if anyone can guide me that would be great help.

County  Status  Status Count
dublin  In      2
dublin  out     1
dublin  closed  10
donegal closed  2
donegal in      5

Sheet 2 with

County  Economy     EconomyCount
dublin  good growth  23
dublin  average      15
donegal not good     14

I want result as

County  Status  Status Count    Economy     EconomyCount
dublin  In      2               good growth  23
dublin  out     1               average      15
dublin  closed  10              N/A
donegal closed  2               not good     14
donegal in      5               N/A

Body:
Considering your Sheet1 is as

and Sheet2 is

Assuming you are matching for the first occurrence, then in Cell D2 of Sheet1 enter the formula

=IF(COUNTIF($A$2:$A2,$A2)=1,INDEX(Sheet2!$B$2:$B$3,MATCH($A2,Sheet2!$A$2:$A$3,0)),"N/A")

and in Cell E2 of Sheet1 enter the following formula

=IF(COUNTIF($A$2:$A2,$A2)=1,INDEX(Sheet2!$C$2:$C$3,MATCH($A2,Sheet2!$A$2:$A$3,0)),"")

Drag/Copy down as required. See image for reference.


问:
"Runtime error 13 - Type mismatch" when parsing date from a text cell
I'm importing a .csv file from another program into Excel. The date format is text, formatted as follows :
mm/dd/yy or
07/03/17
The imported file is very unstructured, with more than just dates in the first field.

I want to write 2017-07-03 into the cell (2,13)

Here is the code I'm using

```<code>ActiveSheet.Cells(2, 13).Select
ActiveCell.FormulaR1C1 = "=IF(LEN(RC[-12]))=8, _  'How I identify date
20&MID((RC[-12]),7,2)&" - "&                      'To get 2017 4 digit Year
MID((RC[-12]),1,2)&" - "&                         'To extract 2 digit month
MID((RC[-12]),4,2)),"""")"                        'To extract 2 digit day
</code>```

This gives me Runtime error 13 - Type mismatch.
I think that my code is causing the error by mixing values and text, but I cannot see where.

答:
The reasons for your error message is due to the formula not being properly created.

It should look like:

```<code>Cells(2, 13).FormulaR1C1 = "=IF(LEN(RC[-12])=8, 20 & MID(RC[-12],7,2) & ""-"" & MID(RC[-12],1,2) & ""-"" & MID(RC[-12],4,2),"""")"
</code>```

Instead of writing formulas to the worksheet, I suggest doing the conversion within VBA and then writing the results to the worksheet.  This can make your code easier to understand, debug, and maintain in the future.

The code below could be shortened, but purposely is not so as to provide more clarity.  It is written as a macro that will process everything in column A, and write the dates to column M, in the format you specify.

I note that in your question, you specify a format of 2017-07-03, but in your code, you generate a format of 2017 - 07 - 03.  I generated the former in the code, but it should be obvious how to change to the latter if that is what you really want.

Also note that in the code I used the default conversion for Excel for 2-digit years, where two digit years are assumed to be in the range 1930 - 2029.  That can be changed if necessary.

The code uses a more involved method of assuring the value being converted is truly a date.  But it does not check for "illegal" dates and will convert, for example 2/31/17  to 2017-03-03.  Your formula method would return the string 2017-02-31  It would be trivial, in the VBA macro, to add code to flag this kind of problem, if it might be an issue.

There are other ways to check for valid dates, including seeing if CDate or VBA's DateValue functions return a date or an error.  But these may not work properly across workbooks in different locale's, with different default short date formats in the windows Regional Settings.

Instead of writing the results as text, the results could be written as a real date formatted as you wish with the .numberformat property of the cell (which could be used in future calculations), and that option is in the comments in the macro.

If you require that the result be dynamic, with a formula, the macro could be easily converted into a User Defined Function, but you would have to assure that the cell format is "text" else Excel will try to convert the resultant date into a "real date" (depending on which of the two formats you really want).

Post back with any questions about the code.

```<code>Option Explicit
Sub ConvertOnlyDates()
    Dim V As Variant
    Dim YR As Long, MN As Long, DY As Long
    Dim DT As Date

    Dim WS As Worksheet
    Dim rSrc As Range, C As Range

'Define the range to check:  Columns A
'Always best to explicitly define worksheets and cells
'  and not rely on ActiveSheet, Activate, Select, etc
Set WS = Worksheets("sheet2")
With WS
    Set rSrc = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With

For Each C In rSrc

    'check if a date
    V = Split(C.Text, "/")
        If UBound(V) = 2 Then
            If V(0) > 0 And V(0) <= 12 _
                And V(1) > 0 And V(1) <= 31 _
                And V(2) >= 0 And V(2) <= 99 Then

                    MN = V(0)
                    DY = V(1)

                    'note that this is Excel's default (at least for now)
                    YR = V(2) + IIf(V(2) < 30, 2000, 1900)

                    DT = DateSerial(YR, MN, DY)

                    'Can be written as text
                    '  or as a real date with proper formatting

                    '  REAL DATE
                    'With C.Offset(0, 12) 'write in column M
                    '    .NumberFormat = "yyyy-mm-dd"
                    '    .Value = DT
                    'End With

                    With C.Offset(0, 12)
                        .NumberFormat = "@"
                        .Value = Format(DT, "yyyy-mm-dd")
                    End With
                End If
            End If
Next C

End Sub
</code>```

Body:
I'm importing a .csv file from another program into Excel. The date format is text, formatted as follows :
mm/dd/yy or
07/03/17
The imported file is very unstructured, with more than just dates in the first field.

I want to write 2017-07-03 into the cell (2,13)

Here is the code I'm using

ActiveSheet.Cells(2, 13).Select
ActiveCell.FormulaR1C1 = "=IF(LEN(RC[-12]))=8, _  'How I identify date
20&MID((RC[-12]),7,2)&" - "&                      'To get 2017 4 digit Year
MID((RC[-12]),1,2)&" - "&                         'To extract 2 digit month
MID((RC[-12]),4,2)),"""")"                        'To extract 2 digit day

This gives me Runtime error 13 - Type mismatch.
I think that my code is causing the error by mixing values and text, but I cannot see where.

Body:
The reasons for your error message is due to the formula not being properly created.

It should look like:

Cells(2, 13).FormulaR1C1 = "=IF(LEN(RC[-12])=8, 20 & MID(RC[-12],7,2) & ""-"" & MID(RC[-12],1,2) & ""-"" & MID(RC[-12],4,2),"""")"

Instead of writing formulas to the worksheet, I suggest doing the conversion within VBA and then writing the results to the worksheet.  This can make your code easier to understand, debug, and maintain in the future.

The code below could be shortened, but purposely is not so as to provide more clarity.  It is written as a macro that will process everything in column A, and write the dates to column M, in the format you specify.

I note that in your question, you specify a format of 2017-07-03, but in your code, you generate a format of 2017 - 07 - 03.  I generated the former in the code, but it should be obvious how to change to the latter if that is what you really want.

Also note that in the code I used the default conversion for Excel for 2-digit years, where two digit years are assumed to be in the range 1930 - 2029.  That can be changed if necessary.

The code uses a more involved method of assuring the value being converted is truly a date.  But it does not check for "illegal" dates and will convert, for example 2/31/17  to 2017-03-03.  Your formula method would return the string 2017-02-31  It would be trivial, in the VBA macro, to add code to flag this kind of problem, if it might be an issue.

There are other ways to check for valid dates, including seeing if CDate or VBA's DateValue functions return a date or an error.  But these may not work properly across workbooks in different locale's, with different default short date formats in the windows Regional Settings.

Instead of writing the results as text, the results could be written as a real date formatted as you wish with the .numberformat property of the cell (which could be used in future calculations), and that option is in the comments in the macro.

If you require that the result be dynamic, with a formula, the macro could be easily converted into a User Defined Function, but you would have to assure that the cell format is "text" else Excel will try to convert the resultant date into a "real date" (depending on which of the two formats you really want).

Post back with any questions about the code.

Option Explicit
Sub ConvertOnlyDates()
    Dim V As Variant
    Dim YR As Long, MN As Long, DY As Long
    Dim DT As Date

    Dim WS As Worksheet
    Dim rSrc As Range, C As Range

'Define the range to check:  Columns A
'Always best to explicitly define worksheets and cells
'  and not rely on ActiveSheet, Activate, Select, etc
Set WS = Worksheets("sheet2")
With WS
    Set rSrc = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With

For Each C In rSrc

    'check if a date
    V = Split(C.Text, "/")
        If UBound(V) = 2 Then
            If V(0) > 0 And V(0) <= 12 _
                And V(1) > 0 And V(1) <= 31 _
                And V(2) >= 0 And V(2) <= 99 Then

                    MN = V(0)
                    DY = V(1)

                    'note that this is Excel's default (at least for now)
                    YR = V(2) + IIf(V(2) < 30, 2000, 1900)

                    DT = DateSerial(YR, MN, DY)

                    'Can be written as text
                    '  or as a real date with proper formatting

                    '  REAL DATE
                    'With C.Offset(0, 12) 'write in column M
                    '    .NumberFormat = "yyyy-mm-dd"
                    '    .Value = DT
                    'End With

                    With C.Offset(0, 12)
                        .NumberFormat = "@"
                        .Value = Format(DT, "yyyy-mm-dd")
                    End With
                End If
            End If
Next C

End Sub


问:
FileNotFoundError: [Errno 2] No such file or directory with ABSOLUTE file path
I have read through several other questions about this topic, but none seem to work.

Here's my code:

```<code>fileIN_csv = "C:/OpenWeatherMap_Stockholm_bulk_5years.csv"
with open(fileIN_csv) as csvfile:
    readCSV = csv.reader(csvfile, delimeter=',')
</code>```

And here is proof of the file's path:
File Path

And here is the specific error:

```<code>FileNotFoundError: [Errno 2] No such file or directory:
'C:/OpenWeatherMap_Stockholm_bulk_5years.csv'
</code>```

答: Just a guess, but try removing the .csv bit at the end. when I request files I leave the extension off and it works. </p>

Body:
I have read through several other questions about this topic, but none seem to work.

Here's my code:

fileIN_csv = "C:/OpenWeatherMap_Stockholm_bulk_5years.csv"
with open(fileIN_csv) as csvfile:
    readCSV = csv.reader(csvfile, delimeter=',')

And here is proof of the file's path:
File Path

And here is the specific error:

FileNotFoundError: [Errno 2] No such file or directory:
'C:/OpenWeatherMap_Stockholm_bulk_5years.csv'


答:
var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;//CHANGE#1
  return obj;
};

var move = function() {
  this.loc++;
  console.log(this.loc);
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3```

Title: Adding Methods to Constructors

Body:
Refactor the carlike function in a way that allows us to use the method calling syntax with "dot access".

var carlike = function(obj, loc) {
  obj.loc = loc;
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);

/*
Here we want to call move with "dot access"

amy.move();
ben.move();
*/

THIS IS WHAT I'VE DONE...

var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;//CHANGE#1
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3

BUT IT WON'T WORK IT'S HAVING ERROR REGARDING LOCATION VARIABLE WHICH WAS WORKING GOOD UNTIL!

Thank You in Advance ☺


问:
CL_INVALID_COMMAND_QUEUE issue
I'm newbie in open CL, therefore would be appreciate if somebody can help.
I have a small kernel that always finished with CL_INVALID_COMMAND_QUEUE error. I've tried on different hardware gtx 765m or gtx 980, the result is the same.
Here is the code host + kernel:</p>

```<code>//get all platforms (drivers)
std::vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(all_platforms.size()==0){
    std::cout<<" No platforms found. Check OpenCL installation!\n";
    exit(1);
}
cl::Platform default_platform=all_platforms[1];
std::cout << "Using platform: "<<default_platform.getInfo<CL_PLATFORM_NAME>()<<"\n";

//get default device of the default platform
std::vector<cl::Device> all_devices;
default_platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices);
if(all_devices.size()==0){
    std::cout<<" No devices found. Check OpenCL installation!\n";
    exit(1);
}
cl::Device default_device=all_devices[0];
std::cout<< "Using device: "<<default_device.getInfo<CL_DEVICE_NAME>()<<"\n";

cl::Context context({default_device});

cl::Program::Sources sources;

std::string kernel_code=
        "__kernel void test(__global float* A,__global float* R) {"
            "int i = get_global_id(0);"
            "if(i<3000) {"
                "R[i]=0;"
                "return;"
            "} "
            "float vm=0;"
            "for(int j=i-3000;j<=i;++j)"
                "vm+=A[j];"
            "R[i]=vm;"
        "}";

sources.push_back({kernel_code.c_str(),kernel_code.length()});

cl::Program program(context,sources);
if(program.build({default_device})!=CL_SUCCESS){
    std::cout<<" Error building: "<<program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(default_device)<<"\n";
    exit(1);
}

size_t n=1075021;
// create buffers on the device
cl::Buffer buffer_A(context,CL_MEM_READ_WRITE,sizeof(float)*n);
cl::Buffer buffer_R(context,CL_MEM_READ_WRITE,sizeof(float)*n);

float *A = new float[n];
float *R = new float[n];

srand (time(NULL));

for(size_t i=0;i<n;++i)
    A[i]=rand()%10;

//create queue to which we will push commands for the device.
cl::CommandQueue queue(context,default_device);

//write arrays A to the device
queue.enqueueWriteBuffer(buffer_A,CL_TRUE,0,sizeof(float)*n,A);
queue.finish();

//run the kernel
cl_int ret;
cl::Kernel kernel_test=cl::Kernel(program,"test");
kernel_test.setArg(0,buffer_A);
kernel_test.setArg(1,buffer_R);
queue.enqueueNDRangeKernel(kernel_test,cl::NullRange,cl::NDRange(n),cl::NullRange);
ret=queue.finish();

//read result R from the device to array R
ret=queue.enqueueReadBuffer(buffer_R,CL_TRUE,0,sizeof(float)*n,R);
</code>```

答:
Summarizing what we've got in comments so far:

The number of global work items was set to 1075021 which is a prime number. Initially it was let the implementation to decide how the work is to be divided, which very likely was divided into 1075021 work groups with 1 work item each which besides being very inefficient was very likely hitting nvidia hardware limit.

Upon rounding global size to the nearest 1024 multiple and explicitly specifying  local size to be 1024 this fixed the problem for offset of 3000 but still the problem remains if offset is set to 65000. Note that rounding requires adding additional check in the kernel for not attempting to process over 1075021th element.

For offset of 65000 the kernel for the first 65000 work items just sets R[0]=0. That's another large inefficiency. This can be done on the host and the kernel can be scheduled to proces starting from 65000. Here is how this can be done:

First the kernel:

```<code>std::string kernel_code=
        "__kernel void test(__global float* A,__global float* R) {"
            "int i = get_global_id(0);"
            "if(i >= 1075021)" // don't process if over
            "    return;"
            "float vm=0;"
            "for(int j=i-65000;j<=i;++j)"
                "vm+=A[j];"
            "R[i]=vm;"
    "}";
</code>```

Now use the offset:

```<code>size_t n=1075021;
size_t offset=65000; // define our offset
// create buffers on the device
cl::Buffer buffer_A(context,CL_MEM_READ_WRITE,sizeof(float)*n);
cl::Buffer buffer_R(context,CL_MEM_READ_WRITE,sizeof(float)*n);

float *A = new float[n];
float *R = new float[n];
memset(R,0,sizeof(float)*offset); // set to zero first 'offset' elements
</code>```

And schedule the kernel taking into account the offset:

```<code>int local_size=1024;
int global_size = ((n-offset)/local_size+1)*local_size; // calculate required global size taking into account the offset
queue.enqueueNDRangeKernel(kernel_test,cl::NDRange(offset),cl::NDRange(global_size),cl::NDRange(local_size)); // schedule kernel using our offset
ret=queue.finish();

//read result R from the device to array R
ret=queue.enqueueReadBuffer(buffer_R,CL_TRUE,0,sizeof(float)*(n-offset),&R[offset]); // read modified data only
</code>```

Also note that hardware watchdog timer may be killing your kernel if the execution time is taking too long - I think that is usually more than 5 seconds. If that's the case you may consider increasing the timeout to say 60 seconds or disable it.

Title: CL_INVALID_COMMAND_QUEUE issue

Body:
I'm newbie in open CL, therefore would be appreciate if somebody can help.
I have a small kernel that always finished with CL_INVALID_COMMAND_QUEUE error. I've tried on different hardware gtx 765m or gtx 980, the result is the same.
Here is the code host + kernel:

//get all platforms (drivers)
std::vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(all_platforms.size()==0){
    std::cout<<" No platforms found. Check OpenCL installation!\n";
    exit(1);
}
cl::Platform default_platform=all_platforms[1];
std::cout << "Using platform: "<<default_platform.getInfo<CL_PLATFORM_NAME>()<<"\n";

//get default device of the default platform
std::vector<cl::Device> all_devices;
default_platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices);
if(all_devices.size()==0){
    std::cout<<" No devices found. Check OpenCL installation!\n";
    exit(1);
}
cl::Device default_device=all_devices[0];
std::cout<< "Using device: "<<default_device.getInfo<CL_DEVICE_NAME>()<<"\n";

cl::Context context({default_device});

cl::Program::Sources sources;

std::string kernel_code=
        "__kernel void test(__global float* A,__global float* R) {"
            "int i = get_global_id(0);"
            "if(i<3000) {"
                "R[i]=0;"
                "return;"
            "} "
            "float vm=0;"
            "for(int j=i-3000;j<=i;++j)"
                "vm+=A[j];"
            "R[i]=vm;"
        "}";

sources.push_back({kernel_code.c_str(),kernel_code.length()});

cl::Program program(context,sources);
if(program.build({default_device})!=CL_SUCCESS){
    std::cout<<" Error building: "<<program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(default_device)<<"\n";
    exit(1);
}

size_t n=1075021;
// create buffers on the device
cl::Buffer buffer_A(context,CL_MEM_READ_WRITE,sizeof(float)*n);
cl::Buffer buffer_R(context,CL_MEM_READ_WRITE,sizeof(float)*n);

float *A = new float[n];
float *R = new float[n];

srand (time(NULL));

for(size_t i=0;i<n;++i)
    A[i]=rand()%10;

//create queue to which we will push commands for the device.
cl::CommandQueue queue(context,default_device);

//write arrays A to the device
queue.enqueueWriteBuffer(buffer_A,CL_TRUE,0,sizeof(float)*n,A);
queue.finish();

//run the kernel
cl_int ret;
cl::Kernel kernel_test=cl::Kernel(program,"test");
kernel_test.setArg(0,buffer_A);
kernel_test.setArg(1,buffer_R);
queue.enqueueNDRangeKernel(kernel_test,cl::NullRange,cl::NDRange(n),cl::NullRange);
ret=queue.finish();

//read result R from the device to array R
ret=queue.enqueueReadBuffer(buffer_R,CL_TRUE,0,sizeof(float)*n,R);

Body:
Summarizing what we've got in comments so far:

The number of global work items was set to 1075021 which is a prime number. Initially it was let the implementation to decide how the work is to be divided, which very likely was divided into 1075021 work groups with 1 work item each which besides being very inefficient was very likely hitting nvidia hardware limit.

Upon rounding global size to the nearest 1024 multiple and explicitly specifying  local size to be 1024 this fixed the problem for offset of 3000 but still the problem remains if offset is set to 65000. Note that rounding requires adding additional check in the kernel for not attempting to process over 1075021th element.

For offset of 65000 the kernel for the first 65000 work items just sets R[0]=0. That's another large inefficiency. This can be done on the host and the kernel can be scheduled to proces starting from 65000. Here is how this can be done:

First the kernel:

std::string kernel_code=
        "__kernel void test(__global float* A,__global float* R) {"
            "int i = get_global_id(0);"
            "if(i >= 1075021)" // don't process if over
            "    return;"
            "float vm=0;"
            "for(int j=i-65000;j<=i;++j)"
                "vm+=A[j];"
            "R[i]=vm;"
    "}";

Now use the offset:

size_t n=1075021;
size_t offset=65000; // define our offset
// create buffers on the device
cl::Buffer buffer_A(context,CL_MEM_READ_WRITE,sizeof(float)*n);
cl::Buffer buffer_R(context,CL_MEM_READ_WRITE,sizeof(float)*n);

float *A = new float[n];
float *R = new float[n];
memset(R,0,sizeof(float)*offset); // set to zero first 'offset' elements

And schedule the kernel taking into account the offset:

int local_size=1024;
int global_size = ((n-offset)/local_size+1)*local_size; // calculate required global size taking into account the offset
queue.enqueueNDRangeKernel(kernel_test,cl::NDRange(offset),cl::NDRange(global_size),cl::NDRange(local_size)); // schedule kernel using our offset
ret=queue.finish();

//read result R from the device to array R
ret=queue.enqueueReadBuffer(buffer_R,CL_TRUE,0,sizeof(float)*(n-offset),&R[offset]); // read modified data only

Also note that hardware watchdog timer may be killing your kernel if the execution time is taking too long - I think that is usually more than 5 seconds. If that's the case you may consider increasing the timeout to say 60 seconds or disable it.


问:
Not Acceptable! An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security
I'm new to moodle environment and I'm having this error:

Not Acceptable!

An appropriate representation of the requested resource could not be
  found on this server. This error was generated by Mod_Security.

I haven't done anything, I'm just viewing the registered users in my website:

http://www.joyfementira.com/dnsc/it14lms
 I've noticed that my profile picture is not properly loaded so I clicked on it (picture's position), and after that the error came out.

What probably caused this error and how would I fix it?

答:
In my case, I received this error when sending to viewer file wrong path to the file it needed to view.</p>

```<code>err: example.com/subDir/myViewer.php?file=%27../../myImages/myFile.gif%27
fix: example.com/subDir/myViewer.php?file=%27../myImages/myFile.gif%27
</code>```

Body:
In my case, I received this error when sending to viewer file wrong path to the file it needed to view.

err: example.com/subDir/myViewer.php?file=%27../../myImages/myFile.gif%27
fix: example.com/subDir/myViewer.php?file=%27../myImages/myFile.gif%27


问:
Spring MVC GET request with Java 8 Instant request parameter
I'm trying to write a Spring MVC GET controller that takes a Java 8 Instant as request parameter:

```<code>    @GetMapping
    @JsonView(OrderListing.class)
    @Validated
    public WebSeekPaginatedResultsDto<OrderListingDto> findAll(@Valid OrderSearchCommand orderSearchCommand) {
       // Some code
    }
</code>```

with:

```<code>    public class OrderSearchCommand {
        private Instant dateCreatedStart;
        private Instant dateCreatedEnd;
        // Some other fields
    }
</code>```

I'm triggering a GET request from some React/Javascript code with something like that:

```<code>    http://localhost:8080/mms/front/orders?dateCreatedStart=2017-05-31T22%3A00%3A00.000Z
</code>```

Spring does not seem to like it and throws an error. Here is the error message:

```<code>    Failed to convert property value of type 'java.lang.String' to required type 'java.time.Instant' for property 'dateCreatedStart';
    nested exception is java.lang.IllegalStateException:
    Cannot convert value of type 'java.lang.String' to required type 'java.time.Instant' for property 'dateCreatedStart': no matching editors or conversion strategy found
</code>```

Any idea why I'm getting this?

Thank you

答: Maybe this can help you? serialize/deserialize java 8 java.time with Jackson JSON mapper I see that this Jackson include Instant class.</p>

Body:
I'm trying to write a Spring MVC GET controller that takes a Java 8 Instant as request parameter:

    @GetMapping
    @JsonView(OrderListing.class)
    @Validated
    public WebSeekPaginatedResultsDto<OrderListingDto> findAll(@Valid OrderSearchCommand orderSearchCommand) {
       // Some code
    }

with:

    public class OrderSearchCommand {
        private Instant dateCreatedStart;
        private Instant dateCreatedEnd;
        // Some other fields
    }

I'm triggering a GET request from some React/Javascript code with something like that:

    http://localhost:8080/mms/front/orders?dateCreatedStart=2017-05-31T22%3A00%3A00.000Z

Spring does not seem to like it and throws an error. Here is the error message:

    Failed to convert property value of type 'java.lang.String' to required type 'java.time.Instant' for property 'dateCreatedStart';
    nested exception is java.lang.IllegalStateException:
    Cannot convert value of type 'java.lang.String' to required type 'java.time.Instant' for property 'dateCreatedStart': no matching editors or conversion strategy found

Any idea why I'm getting this?

Thank you