问:
How to modify the duplicate form in the database manager?
I want to add some other field to this form that can be accessed from the Database Manager in Odoo

The data is sent to this controller:

```<code>@http.route('/web/database/duplicate', type='http', auth="none", methods=['POST'], csrf=False)
def duplicate(self, master_pwd, name, new_name):
    try:
        if not re.match(DBNAME_PATTERN, new_name):
            raise Exception(_('Invalid database name. Only alphanumerical characters, underscore, hyphen and dot are allowed.'))
        dispatch_rpc('db', 'duplicate_database', [master_pwd, name, new_name])
        return http.local_redirect('/web/database/manager')
    except Exception as e:
        error = "Database duplication error: %s" % (str(e) or repr(e))
        return self._render_template(error=error)
</code>```

But the form is plain html, so I cannot inherit and modify any template:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Duplicate Database

        <form id="form-duplicate-db" role="form" action="/web/database/duplicate" method="post">

            {{ master_input() }}

                Database Name
                <input id="name" type="text" name="name" class="form-control" required="required" readonly="readonly"/>

                New Name
                <input id="new_name" type="text" name="new_name" class="form-control" required="required" pattern="{{ pattern }}" title="Only alphanumerical characters, underscore, hyphen and dot are allowed"/>

            <input type="submit" value="Continue" class="btn btn-primary pull-right"/>

        </form>

```

<p>I found a python code where this html is rendered</p>

```class Database(http.Controller):

    def _render_template(self, **d):
        d.setdefault('manage',True)
        d['insecure'] = odoo.tools.config.verify_admin_password('admin')
        d['list_db'] = odoo.tools.config['list_db']
        d['langs'] = odoo.service.db.exp_list_lang()
        d['countries'] = odoo.service.db.exp_list_countries()
        d['pattern'] = DBNAME_PATTERN
        # databases list
        d['databases'] = []
        try:
            d['databases'] = http.db_list()
            d['incompatible_databases'] = odoo.service.db.list_db_incompatible(d['databases'])
        except odoo.exceptions.AccessDenied:
            monodb = db_monodb()
            if monodb:
                d['databases'] = [monodb]
        return env.get_template("database_manager.html").render(d)
```

Should I modify this code in order to use another template? Or is there another more appropriate solution?

Is modifying the original code directly in the web module the only way to achieve this? Is there a way to change all this behaviour by inheriting the web module?

答:
Sure, you can done it by a custom module.First You have to define your own html template as per your need , and then have to rewrite the controller which render the html file.

You can refer the following code to rewrite the controller.

```<code>from odoo.addons.web.controllers.main import Database  # importing base controller class

class MyDatabase(Database):
    def _render_template(self, **d):
       d.setdefault('manage',True)
       d['insecure'] = odoo.tools.config.verify_admin_password('admin')
       d['list_db'] = odoo.tools.config['list_db']
       d['langs'] = odoo.service.db.exp_list_lang()
       d['countries'] = odoo.service.db.exp_list_countries()
       d['pattern'] = DBNAME_PATTERN
       #additional parameters if any
       d['databases'] = []
       try:
           d['databases'] = http.db_list()
           d['incompatible_databases'] = odoo.service.db.list_db_incompatible(d['databases'])
       except odoo.exceptions.AccessDenied:
           monodb = db_monodb()
           if monodb:
               d['databases'] = [monodb]

       return env.get_template("your_modified_template.html").render(d)  #render your modified html template.
</code>```

If you have any doubts have a look in to the code of This module.

Body:
I want to add some other field to this form that can be accessed from the Database Manager in Odoo

The data is sent to this controller:

@http.route('/web/database/duplicate', type='http', auth="none", methods=['POST'], csrf=False)
def duplicate(self, master_pwd, name, new_name):
    try:
        if not re.match(DBNAME_PATTERN, new_name):
            raise Exception(_('Invalid database name. Only alphanumerical characters, underscore, hyphen and dot are allowed.'))
        dispatch_rpc('db', 'duplicate_database', [master_pwd, name, new_name])
        return http.local_redirect('/web/database/manager')
    except Exception as e:
        error = "Database duplication error: %s" % (str(e) or repr(e))
        return self._render_template(error=error)

But the form is plain html, so I cannot inherit and modify any template:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Duplicate Database

        <form id="form-duplicate-db" role="form" action="/web/database/duplicate" method="post">

            {{ master_input() }}

                Database Name
                <input id="name" type="text" name="name" class="form-control" required="required" readonly="readonly"/>

                New Name
                <input id="new_name" type="text" name="new_name" class="form-control" required="required" pattern="{{ pattern }}" title="Only alphanumerical characters, underscore, hyphen and dot are allowed"/>

            <input type="submit" value="Continue" class="btn btn-primary pull-right"/>

        </form>

I found a python code where this html is rendered

class Database(http.Controller):

    def _render_template(self, **d):
        d.setdefault('manage',True)
        d['insecure'] = odoo.tools.config.verify_admin_password('admin')
        d['list_db'] = odoo.tools.config['list_db']
        d['langs'] = odoo.service.db.exp_list_lang()
        d['countries'] = odoo.service.db.exp_list_countries()
        d['pattern'] = DBNAME_PATTERN
        # databases list
        d['databases'] = []
        try:
            d['databases'] = http.db_list()
            d['incompatible_databases'] = odoo.service.db.list_db_incompatible(d['databases'])
        except odoo.exceptions.AccessDenied:
            monodb = db_monodb()
            if monodb:
                d['databases'] = [monodb]
        return env.get_template("database_manager.html").render(d)

Should I modify this code in order to use another template? Or is there another more appropriate solution?

Is modifying the original code directly in the web module the only way to achieve this? Is there a way to change all this behaviour by inheriting the web module?

Body:
Sure, you can done it by a custom module.First You have to define your own html template as per your need , and then have to rewrite the controller which render the html file.

You can refer the following code to rewrite the controller.

from odoo.addons.web.controllers.main import Database  # importing base controller class

class MyDatabase(Database):
    def _render_template(self, **d):
       d.setdefault('manage',True)
       d['insecure'] = odoo.tools.config.verify_admin_password('admin')
       d['list_db'] = odoo.tools.config['list_db']
       d['langs'] = odoo.service.db.exp_list_lang()
       d['countries'] = odoo.service.db.exp_list_countries()
       d['pattern'] = DBNAME_PATTERN
       #additional parameters if any
       d['databases'] = []
       try:
           d['databases'] = http.db_list()
           d['incompatible_databases'] = odoo.service.db.list_db_incompatible(d['databases'])
       except odoo.exceptions.AccessDenied:
           monodb = db_monodb()
           if monodb:
               d['databases'] = [monodb]

       return env.get_template("your_modified_template.html").render(d)  #render your modified html template.

If you have any doubts have a look in to the code of This module.


来源: stackexchange

问:
How to find the number of days between two dates
I have a basic query:

```<code>SELECT dtCreated
    , bActive
    , dtLastPaymentAttempt
    , dtLastUpdated
    , dtLastVisit
FROM Customers
WHERE (bActive = 'true')
    AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-0100:00:00', 102))
</code>```

I want to add another column to the output... lets call it "Difference" to find out the number of days between 'dtcreated' and 'dtlastupdated'  So for example if record 1 has a dtcreated of 1/1/11 and dtlastupdated is 1/1/12 the "Difference" column would be "365".

Can this be accomplished in a query?

答:
```<code>DECLARE @Firstdate DATE='2016-04-01',
 @LastDate DATE=GETDATE(),/*get today date*/
 @resultDay int=null

SET @resultDay=(SELECT DATEDIFF(d, @Firstdate, @LastDate))
PRINT @resultDay
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a basic query:

SELECT dtCreated
    , bActive
    , dtLastPaymentAttempt
    , dtLastUpdated
    , dtLastVisit
FROM Customers
WHERE (bActive = 'true')
    AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-0100:00:00', 102))

I want to add another column to the output... lets call it "Difference" to find out the number of days between 'dtcreated' and 'dtlastupdated'  So for example if record 1 has a dtcreated of 1/1/11 and dtlastupdated is 1/1/12 the "Difference" column would be "365".

Can this be accomplished in a query?

ContentLicense: CC BY-SA 4.0


问:
How can I perform on update cascade in EF
EF Database First:

I have model

```<code>public class Book {
  public Guid BookId { get;set; }
  public string BookName { get;set; }
  public string CategoryCode { get;set; }
  public Category Category { get;set; }
}

public class Category {
  public Guid CategoryId { get;set; }
  public string CategoryName { get;set; }
  public string CategoryCode { get;set; }
}
</code>```

Then, in my Context i have

```<code>        modelBuilder.Entity<Book>()
            .HasKey(c => c.BookId);

        modelBuilder.Entity<Book>()
            .Property(c => c.CategoryCode )
            .HasColumnName("Category");

        modelBuilder.Entity<Book>()
            .HasOne(c => c.Category)
            .WithMany()
            .HasForeignKey(c => c.CategoryCode )
            .HasPrincipalKey(bu => bu.CategoryCode );
</code>```

When I try to update CategoryName the error :

The property 'CategoryName ' on entity type 'Category' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key first delete the dependent and invoke 'SaveChanges' then associate the dependent with the new principal.

So I try to so On update cascade but I see only On delete cascade. So how can I update it?.

Actually I just try to refer 'CategoryCode' in Book to 'CategoryCode' in Category and able to update that so how it should be?

答:
As @PanagiotisKanavos already explained greatly in the comment, I am just posting the solution:

CategoryCode is not the PrimaryKey of Category model class. So you can not make CategoryCode as ForeignKey in Book model class. Instead you have to use CategoryId as ForeignKey in Book model class as follows:

```<code>public class Book
{
  public Guid BookId { get;set; }
  public string BookName { get;set; }

  [ForeignKey("Category")]
  public Guid CategoryId { get;set; } // <-- Here CategoryId instead of CategoryCode
  public Category Category { get;set; }
}
</code>```

Body:
EF Database First:

I have model

public class Book {
  public Guid BookId { get;set; }
  public string BookName { get;set; }
  public string CategoryCode { get;set; }
  public Category Category { get;set; }
}

public class Category {
  public Guid CategoryId { get;set; }
  public string CategoryName { get;set; }
  public string CategoryCode { get;set; }
}

Then, in my Context i have

        modelBuilder.Entity<Book>()
            .HasKey(c => c.BookId);

        modelBuilder.Entity<Book>()
            .Property(c => c.CategoryCode )
            .HasColumnName("Category");

        modelBuilder.Entity<Book>()
            .HasOne(c => c.Category)
            .WithMany()
            .HasForeignKey(c => c.CategoryCode )
            .HasPrincipalKey(bu => bu.CategoryCode );

When I try to update CategoryName the error :

The property 'CategoryName ' on entity type 'Category' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key first delete the dependent and invoke 'SaveChanges' then associate the dependent with the new principal.

So I try to so On update cascade but I see only On delete cascade. So how can I update it?.

Actually I just try to refer 'CategoryCode' in Book to 'CategoryCode' in Category and able to update that so how it should be?

Body:
As @PanagiotisKanavos already explained greatly in the comment, I am just posting the solution:

CategoryCode is not the PrimaryKey of Category model class. So you can not make CategoryCode as ForeignKey in Book model class. Instead you have to use CategoryId as ForeignKey in Book model class as follows:

public class Book
{
  public Guid BookId { get;set; }
  public string BookName { get;set; }

  [ForeignKey("Category")]
  public Guid CategoryId { get;set; } // <-- Here CategoryId instead of CategoryCode
  public Category Category { get;set; }
}


问:
Python - Average of three values in a while true loop
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)
```

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

答:
You can apply some math and recalculate average each new iteration.</p>

```<code>passed = 0
avg_distance = 0
while True:
    passed += 1
    distance = misura()
    print("Distanza : %.2f" % distanza)

    avg_distance = ((passed - 1) * avg_distance + distance) / passed

    if (avg_distance > 30):
        print("NOT PRESENT")
    else:
        print("PRESENT")

    time.sleep(1.5)
</code>```

Body:
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

Body:
You can apply some math and recalculate average each new iteration.

passed = 0
avg_distance = 0
while True:
    passed += 1
    distance = misura()
    print("Distanza : %.2f" % distanza)

    avg_distance = ((passed - 1) * avg_distance + distance) / passed

    if (avg_distance > 30):
        print("NOT PRESENT")
    else:
        print("PRESENT")

    time.sleep(1.5)


问:
Passing ecrypted id in url parameter using javascript
Can any one tell me how to pass encrypted id in url using JS like as localhost/data?action=23 convert 23 to encrypt

I have already tried

btoa()

atob()

but these convert only string I want to convert id in encrypted form in url parameter

```<code>var action= id;

localhost/data.php?action=encrypt(id)
</code>```

答:
Why you need encrypt in javascript? If you want to protect data submit (user cannot change) you can use oAuth by token.

Example: url: http://aaa.com/user/delete/23

Url protect: http://aaa.com/user/delete/23/token/aaaaaaaaaaaa...

Step1: when login, create a session variable "secuKeyInSession" with
  random anything and md5 it. Ex: secuKeyInSession = "bbbbbbbb"

Step2: when create link, make token parameter like: token =
  md5(secuKeyInSession . "23" . "user/delete")

Step3: when user submit or call link, double check and compare.

Body:
Can any one tell me how to pass encrypted id in url using JS like as localhost/data?action=23 convert 23 to encrypt

I have already tried

btoa()

atob()

but these convert only string I want to convert id in encrypted form in url parameter

var action= id;

localhost/data.php?action=encrypt(id)


问:
Is there any tool to optimize MySQL Queries?
I am  undergoing the performance test on MySQL and i need your guidance.If there is any tool available to optimize the MySQL Queries.Please let me know.The tool i am  seeking for is one which would be useful to identify the query which causing the memory leak.

Thanks,

答: You can use: EXPLAIN and EXPLAIN EXTENDED


问:
customizing bootstrap form-control on select option
I'm using bootstrap's form-control class to keep a consistent style between my form input and those that requires a select option. However using bootstrap's form-control on select elements gives it the ugly drop-down button in firefox.

What I'd like to achieve is this

However looking through the css part I have no way of identifying which part it is that I should override as there does not seem to be a css specifying the drop-down arrow's decoration.

This is how the current code looks like

```<code><div class="form-group row">
    <label for="industry" class="">Industry :</label>
    <select name="industry" class="form-control">
        <option value="" disabled selected>Select Industry</option>
        <option value="financial-service">Financial Services</option>
        <option value="healthcare-lifescience">Healthcare & Life Science</option>
        <option value="communications">Communications</option>
    </select>
</div>
</code>```

答:
Check out -moz-appearance here and set it to none.

By default, browsers such as Chrome, Firefox, ... apply a style to inputs, selects, dropdowns, etc. Using appearance allows you to remove this default style and apply your own using pseudo elements (already done in Bootstrap in your specific case).

Body:
I'm using bootstrap's form-control class to keep a consistent style between my form input and those that requires a select option. However using bootstrap's form-control on select elements gives it the ugly drop-down button in firefox.

What I'd like to achieve is this

However looking through the css part I have no way of identifying which part it is that I should override as there does not seem to be a css specifying the drop-down arrow's decoration.

This is how the current code looks like

    Industry :
    <select name="industry" class="form-control">
        <option value="" disabled selected>Select Industry</option>
        <option value="financial-service">Financial Services</option>
        <option value="healthcare-lifescience">Healthcare & Life Science</option>
        <option value="communications">Communications</option>
    </select>


问:
Combinations in the right order
I am dealing with combinations of variables. In my model the combination (A,B) would be similar to (B,A). I would like to reshape my data in order to get similar combinations in the same order.

I try to used the duplicated function and to work with the paste function but I do not sort out the issue.

This is my first table :

```<code>df <- data.frame(V1=c("A","A","A","B","B","B"),
                 V2=c("B","C","D","A","D","A"))
</code>```

This what I would like to obtain :

```<code>df2 <- data.frame(V1=c("A","A","A","B","B","B"),
                  V2=c("B","C","D","A","D","A"),
                  Test=c("OK","OK","OK","FALSE","OK","FALSE"),
                  V1b=c("A","A","A","A","B","A"),
                  V2b=c("B","C","D","B","D","B"))
</code>```

答:
Assuming the "right order" is the alphabetical order, you can use

```<code>alphabetical <- function(x,y){x < y}
</code>```

which return true when x,y is sorted alphabetically and false otherwise.

EDIT : here is a working solution :

```<code>
df_sorted <- df %>% rowwise() %>% mutate(Test = alphabetical(as.character(V1),as.character(V2))) %>%
                 mutate(V1b = if (Test) {
                  as.character(V1)
                } else {
                  as.character(V2)
                }) %>%
                mutate(V2b = if (Test) {
                  as.character(V2)
                } else {
                  as.character(V1)
                })
</code>```

Title: Combinations in the right order

Body:
I am dealing with combinations of variables. In my model the combination (A,B) would be similar to (B,A). I would like to reshape my data in order to get similar combinations in the same order.

I try to used the duplicated function and to work with the paste function but I do not sort out the issue.

This is my first table :

df <- data.frame(V1=c("A","A","A","B","B","B"),
                 V2=c("B","C","D","A","D","A"))

This what I would like to obtain :

df2 <- data.frame(V1=c("A","A","A","B","B","B"),
                  V2=c("B","C","D","A","D","A"),
                  Test=c("OK","OK","OK","FALSE","OK","FALSE"),
                  V1b=c("A","A","A","A","B","A"),
                  V2b=c("B","C","D","B","D","B"))

Body:
Assuming the "right order" is the alphabetical order, you can use

alphabetical <- function(x,y){x < y}

which return true when x,y is sorted alphabetically and false otherwise.

EDIT : here is a working solution :

df_sorted <- df %>% rowwise() %>% mutate(Test = alphabetical(as.character(V1),as.character(V2))) %>%
                 mutate(V1b = if (Test) {
                  as.character(V1)
                } else {
                  as.character(V2)
                }) %>%
                mutate(V2b = if (Test) {
                  as.character(V2)
                } else {
                  as.character(V1)
                })


问:
Exception detected while using GetPositionAsync Geolocator
I'm getting an exception error: System.Threading.Tasks.TaskCanceledException, while trying to get some geolocation informations using Plugin.Geolocator.

here 's the exception that I get : System.Threading.Tasks.TaskCanceledException: A task was canceled.
  at Plugin.Geolocator.GeolocatorImplementation.GetPositionAsync (System.Nullable1[T] timeout, System.Nullable1[T] cancelToken, System.Boolean includeHeading) [0x004d3] in :0
  at interface_test.MainPage.CreateMainPageAsync () [0x0018b] in /Users/khalidharkati/Projects/interface_test/interface_test/MainPage.xaml.cs:140
  at interface_test.App.OnStart () [0x0001a] in /Users/khalidharkati/Projects/interface_test/interface_test/App.xaml.cs:23
  at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_0 (System.Object state) [0x00000] in <58604b4522f748968296166e317b04b4>:0
  at Android.App.SyncContext+<>c__DisplayClass2_0.b__0 () [0x00000] in <788a34f7a7b84486905dfde786529d42>:0
  at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <788a34f7a7b84486905dfde786529d42>:0
  at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <788a34f7a7b84486905dfde786529d42>:0
  at at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.40(intptr,intptr)

To be able to use an async constructor, I made one with the position as an argument:

public MainPage(Plugin.Geolocator.Abstractions.Position position)
{
    ...
}
```

<p>Then I added this method to get my position:</p>

<pre class="lang-cs prettyprint-override"><code>public static async Task<MainPage> CreateMainPageAsync()
{
    var locator = CrossGeolocator.Current;
    locator.DesiredAccuracy = 50;
    var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
    MainPage page = new MainPage(position);
    return page;
}
</code>```

In the app.xaml.cs file, I added this code to the OnStart() method:

protected override async void OnStart()
{
    interface_test.MainPage main = await interface_test.MainPage.CreateMainPageAsync();
    MainPage = main;
}
```

PS: Before I update some components, Xamarin and some packages, I start getting this error.

答: I solved it , actually , this might sound stupid , but I just forgot to turn my GPS on , on my phone . that's it .</p>

Body:
I'm getting an exception error: System.Threading.Tasks.TaskCanceledException, while trying to get some geolocation informations using Plugin.Geolocator.

here 's the exception that I get : System.Threading.Tasks.TaskCanceledException: A task was canceled.
  at Plugin.Geolocator.GeolocatorImplementation.GetPositionAsync (System.Nullable1[T] timeout, System.Nullable1[T] cancelToken, System.Boolean includeHeading) [0x004d3] in :0
  at interface_test.MainPage.CreateMainPageAsync () [0x0018b] in /Users/khalidharkati/Projects/interface_test/interface_test/MainPage.xaml.cs:140
  at interface_test.App.OnStart () [0x0001a] in /Users/khalidharkati/Projects/interface_test/interface_test/App.xaml.cs:23
  at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_0 (System.Object state) [0x00000] in <58604b4522f748968296166e317b04b4>:0
  at Android.App.SyncContext+<>c__DisplayClass2_0.b__0 () [0x00000] in <788a34f7a7b84486905dfde786529d42>:0
  at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <788a34f7a7b84486905dfde786529d42>:0
  at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <788a34f7a7b84486905dfde786529d42>:0
  at at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.40(intptr,intptr)

To be able to use an async constructor, I made one with the position as an argument:

public MainPage(Plugin.Geolocator.Abstractions.Position position)
{
    ...
}

Then I added this method to get my position:

public static async Task<MainPage> CreateMainPageAsync()
{
    var locator = CrossGeolocator.Current;
    locator.DesiredAccuracy = 50;
    var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
    MainPage page = new MainPage(position);
    return page;
}

In the app.xaml.cs file, I added this code to the OnStart() method:

protected override async void OnStart()
{
    interface_test.MainPage main = await interface_test.MainPage.CreateMainPageAsync();
    MainPage = main;
}

PS: Before I update some components, Xamarin and some packages, I start getting this error.


问:
React Drag & Drop Event propagation problem
I have a simple Drag & Drop setup. What's special is that there can be dropzones inside dropzones. My problem is, that whenever I drop something in my child component, the parent event gets fired as well but only under certain circumstances.

For example (this works, no event propagation):

```<code>export default class Folder extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dragActive: false
        };
    }

    onDragOver = (e) => {
        e.preventDefault();
        this.setState({ dragActive: true });
    }

    onDragLeave = () => {
        this.setState({ dragActive: false });
    }

    onDrop = (e) => {
        e.stopPropagation();
        alert("test");
    }

    render() {
        return (
            <div className="col-6 col-sm-4 col-md-3 col-lg-2 col-xl-8ths" onDragOver={this.onDragOver} onDragLeave={this.onDragLeave} onDrop={this.onDrop}>

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

The important part is this line here:

```<code>onDrop={this.onDrop}
</code>```

If my drop event is inside the same component everything works as expected.

As soon as I change the line to this:

```<code>onDrop={() => this.props.onDropFunction(event, this.props.folder.id)}
</code>```

The event propagation stops working. This is the onDrop function I am calling inside the parent:

```<code>onDrop = (e, folderId) => {
    e.stopPropagation();
    e.preventDefault();
    var files = this.fileListToArray(e.dataTransfer.files);
    this.setState({
        dragActive: false,
        uploadFiles: files
    }, () => {
        this.uploadFiles(folderId);
    });
}
</code>```

答:
Found the answer in this SO-Post (just didn't scroll down enough).

So apparently the solution is to basically use the first approach and replace the alert("test") part with this.props.onDropFunction(event, this.props.folder.id);

Body:
I have a simple Drag & Drop setup. What's special is that there can be dropzones inside dropzones. My problem is, that whenever I drop something in my child component, the parent event gets fired as well but only under certain circumstances.

For example (this works, no event propagation):

export default class Folder extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dragActive: false
        };
    }

    onDragOver = (e) => {
        e.preventDefault();
        this.setState({ dragActive: true });
    }

    onDragLeave = () => {
        this.setState({ dragActive: false });
    }

    onDrop = (e) => {
        e.stopPropagation();
        alert("test");
    }

    render() {
        return (

        );
    }
}

The important part is this line here:

onDrop={this.onDrop}

If my drop event is inside the same component everything works as expected.

As soon as I change the line to this:

onDrop={() => this.props.onDropFunction(event, this.props.folder.id)}

The event propagation stops working. This is the onDrop function I am calling inside the parent:

onDrop = (e, folderId) => {
    e.stopPropagation();
    e.preventDefault();
    var files = this.fileListToArray(e.dataTransfer.files);
    this.setState({
        dragActive: false,
        uploadFiles: files
    }, () => {
        this.uploadFiles(folderId);
    });
}


问:
how to return the date as dd-FullMonth-yyyy
I have a date field in SharePoint list as mm/dd/yyyy

I want to list it as dd MonthName yyyy

When I use the below function, it return the date with one month added,
for example, if the field date is 1/1/2019 it will be displayed as 1 February 2019 (instead of January, it displays February)

I tried to subtract 1 from monthindex but it didn't work.

```<code>function formatDate(thedate) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];
  var diffrentformat = thedate.split(" ")[0];
  var divideddate = diffrentformat.split("-");
  var d = new Date(divideddate[0], divideddate[1], divideddate[2]);
  //var d = new Date(thedate.split[]);
  var day = d.getDate();
  var monthIndex = d.getMonth();
  var year = d.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}
</code>```

I expect the output to be dd MonthName yyyy, but I'm getting dd nextMonthName yyyy

答:
In javascript the month start from 0-11.

So you should have to set the index as per that.

Body:
I have a date field in SharePoint list as mm/dd/yyyy

I want to list it as dd MonthName yyyy

When I use the below function, it return the date with one month added,
for example, if the field date is 1/1/2019 it will be displayed as 1 February 2019 (instead of January, it displays February)

I tried to subtract 1 from monthindex but it didn't work.

function formatDate(thedate) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];
  var diffrentformat = thedate.split(" ")[0];
  var divideddate = diffrentformat.split("-");
  var d = new Date(divideddate[0], divideddate[1], divideddate[2]);
  //var d = new Date(thedate.split[]);
  var day = d.getDate();
  var monthIndex = d.getMonth();
  var year = d.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

I expect the output to be dd MonthName yyyy, but I'm getting dd nextMonthName yyyy


问:
What causes this weird display ? I suspect it might be CSS or a bug in Chrome OS X?
This is what the weird view looks like, in Chrome on OS X on first load:

That blue bar running right across the screen is actually the navigation bar that should be at the top of the screen. See below.

This is what the original view looks like, and this is what it reverts to - once I scroll down (so that portion of the screen disappears) and scroll back up:

Edit1: I don't even know what code to post, if any because it is kinda random. If you ask some questions though, maybe something might jump out and I will know what code to either post or look at.

Thanks.

Edit2: Here is the code for the div#navigation:

```<code><div id="navigation">
        <div id="quota-info">
            Plan: Chameleon<br />
            # of Projects: 2 / 20<br />
            # of Clients: 2 / 15<br />
            Storage: 10.8 MB / 10.0GB <br />
        </div>

        <div id="user-info">
            <span class="username">Hi Test</span><br />
            Name: Test User<br />
            Email: test@abc.com<br />
            Last Logged In: about 2 hours ago<br />

        </div>

        <ul>
            <li><a href="/home/index"><img src="logo.png" /></a></li>
            <li id="dashboard"><a href="/home/index">Dashboard</a></li>
            <li id="settings"><a href="/settings">Settings</a></li>
            <li id="logout"><a href="/logout">Logout</a></li>
        </ul>
    </div>
</code>```

Here is the CSS:

```<code>#navigation {
    font-family: Verdana, Arial,  sans-serif;
    font-size: 13px;
    background: #2d343f;
    background-image: url('../images/nav-textured-bg.png');
    background-repeat: repeat;
    padding: 5px 5px;
    margin: 0px auto;
    position: relative;
    height: 75px;
}

#navigation a {
    text-decoration: none;
    padding: 10px 15px;
    display: inline;
    height: 35px;
    line-height: 35px;
    color: #c6c8cb;
}

#navigation ul {
    width: 100%;
    margin: 0 auto;
    text-align: center;
}

#navigation li {
    width: 100%;
    display: inline;
    list-style-type: none;
}

#navigation li img {
    position: relative;
    top: 15px;
}
</code>```

Edit 3:

Here is another screenshot of how it looks when I scroll up. The top navigational bar is still there. This blue thing is not even the menu, it's like a screenshot of it. When I hover over the menu links, they don't work.

答:
You have to create a reduction. Start with a copy of the actual page and then remove stuff not related to the problem, one by one, until it disappears. Then you'll see what's causing it, whether it's a browser bug and what you can do to fix it.

PS: If it's a browser bug, don't neglect to report it. It's a web developer's responsibility.

Body:
This is what the weird view looks like, in Chrome on OS X on first load:

That blue bar running right across the screen is actually the navigation bar that should be at the top of the screen. See below.

This is what the original view looks like, and this is what it reverts to - once I scroll down (so that portion of the screen disappears) and scroll back up:

Edit1: I don't even know what code to post, if any because it is kinda random. If you ask some questions though, maybe something might jump out and I will know what code to either post or look at.

Thanks.

Edit2: Here is the code for the div#navigation:

            Plan: Chameleon

            # of Projects: 2 / 20

            # of Clients: 2 / 15

            Storage: 10.8 MB / 10.0GB

            Hi Test

            Name: Test User

            Email: test@abc.com

            Last Logged In: about 2 hours ago

Dashboard

Settings

Logout

Here is the CSS:

#navigation {
    font-family: Verdana, Arial,  sans-serif;
    font-size: 13px;
    background: #2d343f;
    background-image: url('../images/nav-textured-bg.png');
    background-repeat: repeat;
    padding: 5px 5px;
    margin: 0px auto;
    position: relative;
    height: 75px;
}

#navigation a {
    text-decoration: none;
    padding: 10px 15px;
    display: inline;
    height: 35px;
    line-height: 35px;
    color: #c6c8cb;
}

#navigation ul {
    width: 100%;
    margin: 0 auto;
    text-align: center;
}

#navigation li {
    width: 100%;
    display: inline;
    list-style-type: none;
}

#navigation li img {
    position: relative;
    top: 15px;
}

Edit 3:

Here is another screenshot of how it looks when I scroll up. The top navigational bar is still there. This blue thing is not even the menu, it's like a screenshot of it. When I hover over the menu links, they don't work.


问:
How to mount jar file to tomcat container
I have a folder in my project, which contains 1 properties file and 1 jar file(db-driver) file.

I need to copy both of these files to /usr/local/tomcat/lib directory on my pod. I am not sure how to achieve this in kubernetes yaml file. Below is my yaml file where I am trying to achieve this using configMap, but pod creation fails with error "configmap references non-existent config key: app.properties"

Target /usr/local/tomcat/lib already has other jar files so I am trying to use configMap to not override entire directory and just add 2 files which are specific to my application.

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: tomcatdeployment
  labels:
    app:  tomcat
spec:
  replicas: 1
  selector:
    matchLabels:
      app:  tomcat
  template:
    metadata:
      labels:
        app:  tomcat
    spec:
      containers:
        - name: tomcat
          image: tomcat:latest
          imagePullPolicy: IfNotPresent
          volumeMounts:
          - name: appvolume
            mountPath: /usr/local/data
          - name: config
            mountPath: /usr/local/tomcat/lib
            subPath: ./configuration
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
      volumes:
        - name: appvolume
        - name: config
          configMap:
            name: config-map
            items:
              - key: app.properties
                path: app.properties
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: config-map
data:
  key:  app.properties

</code>```

Current Directory structure...

```<code>.
├── configuration
│   ├── app.properties
│   └── mysql-connector-java-5.1.21.jar
├── deployment.yaml
└── service.yaml

</code>```

Please share your valuable feedback on how to achieve this.

Regards.

答:
it's normal to have this error because in this volume declaration you mentioned that key: app.properties otherwise in the configmap key: app.properties so here the key is key and the value is app.properties so you must in the volume declaration change :

```<code>volumes:
        - name: appvolume
        - name: config
          configMap:
            name: config-map
            items:
              - key: app.properties
                path: app.properties
</code>```

to :

```<code>   volumes:
            - name: appvolume
            - name: config
              configMap:
                name: config-map
                items:
                  - key: key
                    path: app.properties
</code>```

for more you can refer here : add-configmap-data-to-a-volume

Body:
I have a folder in my project, which contains 1 properties file and 1 jar file(db-driver) file.

I need to copy both of these files to /usr/local/tomcat/lib directory on my pod. I am not sure how to achieve this in kubernetes yaml file. Below is my yaml file where I am trying to achieve this using configMap, but pod creation fails with error "configmap references non-existent config key: app.properties"

Target /usr/local/tomcat/lib already has other jar files so I am trying to use configMap to not override entire directory and just add 2 files which are specific to my application.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: tomcatdeployment
  labels:
    app:  tomcat
spec:
  replicas: 1
  selector:
    matchLabels:
      app:  tomcat
  template:
    metadata:
      labels:
        app:  tomcat
    spec:
      containers:
        - name: tomcat
          image: tomcat:latest
          imagePullPolicy: IfNotPresent
          volumeMounts:
          - name: appvolume
            mountPath: /usr/local/data
          - name: config
            mountPath: /usr/local/tomcat/lib
            subPath: ./configuration
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
      volumes:
        - name: appvolume
        - name: config
          configMap:
            name: config-map
            items:
              - key: app.properties
                path: app.properties
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: config-map
data:
  key:  app.properties

Current Directory structure...

.
├── configuration
│   ├── app.properties
│   └── mysql-connector-java-5.1.21.jar
├── deployment.yaml
└── service.yaml

Please share your valuable feedback on how to achieve this.

Regards.

Body:
it's normal to have this error because in this volume declaration you mentioned that key: app.properties otherwise in the configmap key: app.properties so here the key is key and the value is app.properties so you must in the volume declaration change :

volumes:
        - name: appvolume
        - name: config
          configMap:
            name: config-map
            items:
              - key: app.properties
                path: app.properties

to :

   volumes:
            - name: appvolume
            - name: config
              configMap:
                name: config-map
                items:
                  - key: key
                    path: app.properties

for more you can refer here : add-configmap-data-to-a-volume


问:
PutImageData() not drawing ImageData
I want to make a fractal generator that uses this method: https://www.johndcook.com/blog/2017/07/08/the-chaos-game-and-the-sierpinski-triangle/
It's really interesting and I wanted to try it on squares and pentagons etc.
The result of the Code below should look like a Sierpinski triangle but unfortunately the canvas stays blank :/

Thx for your help :)

```<code><!DOCTYPE html>
<html>
    <head>
        <title>sierpinksi polygons</title>
    </head>
    <body>
        <canvas width="500" height="500" id="canvas"></canvas>
        <script>
            let canavas = document.getElementById("canvas");
            let ctx = canvas.getContext("2d");
            let imgdata = ctx.createImageData(500, 500);
            let data = imgdata.data;
            let vertices = [{x: 0, y: 0}, {x: 500, y: 0}, {x: 250, y: 433}];

            function pixel(x, y) {
                data[4*y*canvas.width+4*x + 3] = 1; //sets alpha to 1 which makes the pixel black
            }

            function random() {
                return vertices[Math.floor(Math.random()*vertices.length)];
            }

            let point = {x: 0, y: 0};

            for (let i = 0; i < 10000; i++) {
                let temp = random();

                //algorithm to draw sierpinksi triangle pixel by pixel
                point.x = point.x + (temp.x - point.x)/2;
                point.y = point.y + (temp.y - point.y)/2;
                pixel(Math.round(point.x), Math.round(point.y));
            }
            console.log(imgdata)
            ctx.putImageData(imgdata, 0, 0);
        </script>
    </body>
</html>
</code>```

答:
data[4*y*canvas.width+4*x + 3] = 1; //sets alpha to 1 which makes the pixel black

No, it doesn’t - the A component of the RGBA value has to be in the range of 0 to 255 as well, 255 matching what opacity: 1 in CSS would mean.

With 1 you have given your pixels an opacity of 1/255 here, which is really only just 0.00392156862

You want to use 255 here to get full black pixels.

Title: PutImageData() not drawing ImageData

Body:
I want to make a fractal generator that uses this method: https://www.johndcook.com/blog/2017/07/08/the-chaos-game-and-the-sierpinski-triangle/
It's really interesting and I wanted to try it on squares and pentagons etc.
The result of the Code below should look like a Sierpinski triangle but unfortunately the canvas stays blank :/

Thx for your help :)

<!DOCTYPE html>

        <title>sierpinksi polygons</title>

        <canvas width="500" height="500" id="canvas"></canvas>


问:
how to implement search query for multiple record seperated by comma from single field single column?
```<code>if(count($_POST["search"]) > 0) {

     $arrayString =  implode("','",$_POST["search"]) ;
}
//echo $arrayString;exit;

 $sql="SELECT * FROM domain_inventory_Global_History WHERE company_domain in ('$arrayString') ";
 echo $sql;
</code>```

答:
you may use LIKE operator to handle this .Forexample</p>

```<code> $sql="SELECT * FROM domain_inventory_Global_History WHERE company_domain LIKE %$arrayString%"
</code>```

Body:
you may use LIKE operator to handle this .Forexample

 $sql="SELECT * FROM domain_inventory_Global_History WHERE company_domain LIKE %$arrayString%"


问:
Can't uninstall mysql-server because : Script SACSrv is broken
I want to install maven on my computer but when I start the installation, an error occurs concerning mysql-server. Since I don't need mysql-server on my computer, I decide to uninstall it but I face the same problem, the same error. I guess the problem comes from the SACSrv script but I have no idea of the usefulness of this script, or even its location.

Thank you very much for your help

This is for an Ubuntu device.
I've tried to purge, autoremove, and reinstall but that's the same result.

```<code>$ sudo apt remove mysql-server
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Le paquet « mysql-server » n'est pas installé, et ne peut donc être supprimé
0 mis à jour, 0 nouvellement installés, 0 à enlever et 13 non mis à jour.
1 partiellement installés ou enlevés.
Après cette opération, 0 o d'espace disque supplémentaires seront utilisés.
Paramétrage de mysql-server-5.7 (5.7.26-0ubuntu0.16.04.1) ...
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script Srv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
mysql_upgrade: Got error: 1045: Access denied for user 'root'@'localhost' (using password: NO) while connecting to the MySQL server
Upgrade process encountered error and will not continue.
mysql_upgrade failed with exit status 11
dpkg: erreur de traitement du paquet mysql-server-5.7 (--configure) :
 le sous-processus script post-installation installé a retourné une erreur de sortie d'état 1
Des erreurs ont été rencontrées pendant l'exécution :
 mysql-server-5.7
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

答:
The SACSrv script was on /etc/init.d, I've always no idea about it usefulness.
Indeed, 'Required-Stop' entry was missing (I don't know how and why).
I've copy-paste the 'Require-start' line and rename to 'Require-stop' and my purge works fine.</p>

Body:
I want to install maven on my computer but when I start the installation, an error occurs concerning mysql-server. Since I don't need mysql-server on my computer, I decide to uninstall it but I face the same problem, the same error. I guess the problem comes from the SACSrv script but I have no idea of the usefulness of this script, or even its location.

Thank you very much for your help

This is for an Ubuntu device.
I've tried to purge, autoremove, and reinstall but that's the same result.

$ sudo apt remove mysql-server
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Le paquet « mysql-server » n'est pas installé, et ne peut donc être supprimé
0 mis à jour, 0 nouvellement installés, 0 à enlever et 13 non mis à jour.
1 partiellement installés ou enlevés.
Après cette opération, 0 o d'espace disque supplémentaires seront utilisés.
Paramétrage de mysql-server-5.7 (5.7.26-0ubuntu0.16.04.1) ...
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script SACSrv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
insserv: Script Srv is broken: incomplete LSB comment.
insserv: missing `Required-Stop:'  entry: please add even if empty.
mysql_upgrade: Got error: 1045: Access denied for user 'root'@'localhost' (using password: NO) while connecting to the MySQL server
Upgrade process encountered error and will not continue.
mysql_upgrade failed with exit status 11
dpkg: erreur de traitement du paquet mysql-server-5.7 (--configure) :
 le sous-processus script post-installation installé a retourné une erreur de sortie d'état 1
Des erreurs ont été rencontrées pendant l'exécution :
 mysql-server-5.7
E: Sub-process /usr/bin/dpkg returned an error code (1)


问:
pd.read_hdf throws 'cannot set WRITABLE flag to True of this array' and 'No module named 'numpy.core._multiarray_umath'
When I run

```<code>pd.read_hdf('xxx')
</code>```

I got

cannot set WRITABLE flag to True of this array

. I found solution here which suggest to downgrade numpy from 1.16.0 to 1.15.x

However, after downgrading numpy to 1.15.4, a new error comes

No module named 'numpy.core._multiarray_umath'

. For this error, someone suggests to upgrade numpy to 1.16.0 .

Anyone encounter the same problem?

答: If you use jupyter notebook or Google Colaboratory use !pip install numpy==1.15.0 before import numpy module and restart kernal or runtime. I had the same problem and solved it in this way.

Body:
When I run

pd.read_hdf('xxx')

I got

cannot set WRITABLE flag to True of this array

. I found solution here which suggest to downgrade numpy from 1.16.0 to 1.15.x

However, after downgrading numpy to 1.15.4, a new error comes

No module named 'numpy.core._multiarray_umath'

. For this error, someone suggests to upgrade numpy to 1.16.0 .

Anyone encounter the same problem?


问:
Google Cloud Functions is not returning response
I am using this api on Google cloud functions https://ocr.space/ocrapi
This is the function I have deployed

```<code>def ocr_space_url(request):
    request_json = request.get_json()
    request_args = request.args

    if request_json and 'url' in request_json:
        url = request_json['url']

    elif request_args and 'url' in request_args:
        url = request_args['url']
    else:
        url = 'http://www.africau.edu/images/default/sample.pdf'

    headers = {
        'apikey': 'helloworld',
    }
     payload = {'url': url,
               }
    r = requests.post('https://api.ocr.space/parse/image',
                      headers=headers, data=payload,
                      )

    return r.content.decode()
</code>```

Deployed like this:
 gcloud functions deploy ocr_space_url --runtime python37 --trigger-http

Calling it by:
curl -X POST "https://us-central1-prefab-environs-241910.cloudfunctions.net/ocr_space_url" -H "Content-Type:application/json" -d "{"url": "http://dl.a9t9.com/ocrbenchmark/pdfscan.pdf"}"

 when I call it with content type it gives me below error

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
</code>```

 if I call it without content type, it goes into the else, because i get request_json = None and for the url in else it give me proper result

I am using cloud functions for the first time in my life please help

答:
Use request as the param, parse your POST data as json(or whatever you want)

```<code>#def ocr_space_url(url, overlay=False, api_key='helloworld', language='eng'):
def ocr_space_url(request):
    """ OCR.space API request with remote file.
        Python3.5 - not tested on 2.7
    :param url: Image url.
    :param overlay: Is OCR.space overlay required in your response.
                    Defaults to False.
    :param api_key: OCR.space API key.
                    Defaults to 'helloworld'.
    :param language: Language code to be used in OCR.
                    List of available language codes can be found on https://ocr.space/OCRAPI
                    Defaults to 'en'.
    :return: Result in JSON format.
    """

    request_json = request.get_json()
    if request_json and 'url' in request_json:
        url = request_json['url']
    else:
        url = 'http://www.africau.edu/images/defaultsample.pdf'

    payload = {'url': url,
               'isOverlayRequired': False,
               'apikey': 'helloworld',
               'language': 'eng',

               }
    r = requests.post('https://api.ocr.space/parse/image',
                      data=payload,
                      )
    return r.content.decode()
</code>```

Make the request with --data '{"url": "http://www.africau.edu/images/defaultsample.pdf"}' -H "Content-Type: application/json"

Body:
I am using this api on Google cloud functions https://ocr.space/ocrapi
This is the function I have deployed

def ocr_space_url(request):
    request_json = request.get_json()
    request_args = request.args

    if request_json and 'url' in request_json:
        url = request_json['url']

    elif request_args and 'url' in request_args:
        url = request_args['url']
    else:
        url = 'http://www.africau.edu/images/default/sample.pdf'

    headers = {
        'apikey': 'helloworld',
    }
     payload = {'url': url,
               }
    r = requests.post('https://api.ocr.space/parse/image',
                      headers=headers, data=payload,
                      )

    return r.content.decode()

Deployed like this:
 gcloud functions deploy ocr_space_url --runtime python37 --trigger-http

Calling it by:
curl -X POST "https://us-central1-prefab-environs-241910.cloudfunctions.net/ocr_space_url" -H "Content-Type:application/json" -d "{"url": "http://dl.a9t9.com/ocrbenchmark/pdfscan.pdf"}"

 when I call it with content type it gives me below error

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>

Bad Request

The browser (or proxy) sent a request that this server could not understand.

 if I call it without content type, it goes into the else, because i get request_json = None and for the url in else it give me proper result

I am using cloud functions for the first time in my life please help

Body:
Use request as the param, parse your POST data as json(or whatever you want)

#def ocr_space_url(url, overlay=False, api_key='helloworld', language='eng'):
def ocr_space_url(request):
    """ OCR.space API request with remote file.
        Python3.5 - not tested on 2.7
    :param url: Image url.
    :param overlay: Is OCR.space overlay required in your response.
                    Defaults to False.
    :param api_key: OCR.space API key.
                    Defaults to 'helloworld'.
    :param language: Language code to be used in OCR.
                    List of available language codes can be found on https://ocr.space/OCRAPI
                    Defaults to 'en'.
    :return: Result in JSON format.
    """

    request_json = request.get_json()
    if request_json and 'url' in request_json:
        url = request_json['url']
    else:
        url = 'http://www.africau.edu/images/defaultsample.pdf'

    payload = {'url': url,
               'isOverlayRequired': False,
               'apikey': 'helloworld',
               'language': 'eng',

               }
    r = requests.post('https://api.ocr.space/parse/image',
                      data=payload,
                      )
    return r.content.decode()

Make the request with --data '{"url": "http://www.africau.edu/images/defaultsample.pdf"}' -H "Content-Type: application/json"


问:
How to retrieve company name from the selected contact
Using ContactsContract I am able to retrieve and display selected mobile number and the relevant contact name.

But instead of returning the company name it's returning the mobile number again.

The intent I use to select a specific phone number when there are multiple numbers

```<code>Intent calContctPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    calContctPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                    startActivityForResult(calContctPickerIntent, 1);
</code>```

here is the main code

```<code> @Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
        case (1):
            if (resultCode == Activity.RESULT_OK) {
                Uri contctDataVar = data.getData();

                Cursor contctCursorVar = getContentResolver().query(contctDataVar, null, null, null, null);
                if (contctCursorVar.getCount() > 0) {
                    while (contctCursorVar.moveToNext()) {
                        String ContctUidVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts._ID));

                        String ContctNamVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        String Companyname = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));

                        Log.i("Names", ContctNamVar);

                        if (Integer.parseInt(contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                            // Query phone here. Covered next
                            String ContctMobVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            String Companyname2 = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));

                            mobile.setText(ContctMobVar);
                            custname.setText(ContctNamVar);
                            companyname.setText(Companyname2);

                            Log.i("Number", ContctMobVar);

                        }

                    }
                }
            }
            break;
    }
}
</code>```

I need to find a way to retrieve the company name saved under the selected contact.

答:
You may try something like this : </p>

```<code>ContentResolver mContentResolver = this.getContentResolver();
 Cursor contacts = cr.query(ContactsContract.Contacts.CONTENT_URI,
                        null, null, null, null);

String mContactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
String mRawContactId = getRawContactID(mContactId);
String mCompanyName = getCompanyName(mRawContactId);

private String getRawContactID(String contactId) {
        String[] projection = new String[]{ContactsContract.RawContacts._ID};
        String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
        String[] selectionArgs = new String[]{contactId};
        Cursor c = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
        if (c == null) return null;
        int rawContactId = -1;
        if (c.moveToFirst()) {
            rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
        }
        c.close();
        return String.valueOf(rawContactId);

    }

private String getCompanyName(String rawContactId) {
        try {
            String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
            String[] orgWhereParams = new String[]{rawContactId,
                    ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
            Cursor cursor = mContentResolver.query(ContactsContract.Data.CONTENT_URI,
                    null, orgWhere, orgWhereParams, null);

            if (cursor == null) return null;
            String name = null;
            if (cursor.moveToFirst()) {
                name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
            }
            cursor.close();
            return name;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
</code>```

Body:
Using ContactsContract I am able to retrieve and display selected mobile number and the relevant contact name.

But instead of returning the company name it's returning the mobile number again.

The intent I use to select a specific phone number when there are multiple numbers

Intent calContctPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    calContctPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                    startActivityForResult(calContctPickerIntent, 1);

here is the main code

 @Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
        case (1):
            if (resultCode == Activity.RESULT_OK) {
                Uri contctDataVar = data.getData();

                Cursor contctCursorVar = getContentResolver().query(contctDataVar, null, null, null, null);
                if (contctCursorVar.getCount() > 0) {
                    while (contctCursorVar.moveToNext()) {
                        String ContctUidVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts._ID));

                        String ContctNamVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        String Companyname = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));

                        Log.i("Names", ContctNamVar);

                        if (Integer.parseInt(contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                            // Query phone here. Covered next
                            String ContctMobVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            String Companyname2 = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));

                            mobile.setText(ContctMobVar);
                            custname.setText(ContctNamVar);
                            companyname.setText(Companyname2);

                            Log.i("Number", ContctMobVar);

                        }

                    }
                }
            }
            break;
    }
}

I need to find a way to retrieve the company name saved under the selected contact.

Body:
You may try something like this :

ContentResolver mContentResolver = this.getContentResolver();
 Cursor contacts = cr.query(ContactsContract.Contacts.CONTENT_URI,
                        null, null, null, null);

String mContactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
String mRawContactId = getRawContactID(mContactId);
String mCompanyName = getCompanyName(mRawContactId);

private String getRawContactID(String contactId) {
        String[] projection = new String[]{ContactsContract.RawContacts._ID};
        String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
        String[] selectionArgs = new String[]{contactId};
        Cursor c = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
        if (c == null) return null;
        int rawContactId = -1;
        if (c.moveToFirst()) {
            rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
        }
        c.close();
        return String.valueOf(rawContactId);

    }

private String getCompanyName(String rawContactId) {
        try {
            String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
            String[] orgWhereParams = new String[]{rawContactId,
                    ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
            Cursor cursor = mContentResolver.query(ContactsContract.Data.CONTENT_URI,
                    null, orgWhere, orgWhereParams, null);

            if (cursor == null) return null;
            String name = null;
            if (cursor.moveToFirst()) {
                name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
            }
            cursor.close();
            return name;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


答:
The next option is to use the Single-Quoted Style. See the example below</p>

```<code>- hosts: localhost
  vars:
    my_dir1: "/scratch/tmp/G1\\$"
    my_dir2: '/scratch/tmp/G2\$'
  tasks:
    - file:
        state: directory
        path: "{{ item }}"
      loop:
        - "{{ my_dir1 }}"
        - "{{ my_dir2 }}"

# ls -1 /scratch/tmp/
'G1\$'
'G2\$'
</code>```

Title: Ansible PLaybook: Escape '$' in Linux path

Body:
I have a path which looks like this -

base_dir/123/path/to/G\$/subdirectory/html/

When I try to set this path in Ansible playbook, it throws error. If add \$ to escape '\', it throws unexpected failure error.

Playbkook -

- hosts: localhost
  vars:
    account_id: 123
  tasks:
  - name: Add \ to path
    debug:
      var: "base_dir/{{ account_id }}/path/to/G\\$/subdirectory/html/"

Result -

TASK [Gathering Facts] *************************************************************************************************************************************************
task path: /playbooks/example_path.yml:2
ok: [localhost]
META: ran handlers

TASK [Add \ to path] ***************************************************************************************************************************************************
task path: /playbooks/exmaple_path.yml:6
fatal: [localhost]: FAILED! => {
    "msg": "Unexpected failure during module execution."
}

PLAY RECAP *************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1

Body:
The next option is to use the Single-Quoted Style. See the example below

- hosts: localhost
  vars:
    my_dir1: "/scratch/tmp/G1\\$"
    my_dir2: '/scratch/tmp/G2\$'
  tasks:
    - file:
        state: directory
        path: "{{ item }}"
      loop:
        - "{{ my_dir1 }}"
        - "{{ my_dir2 }}"

# ls -1 /scratch/tmp/
'G1\$'
'G2\$'


问:
Service that does advanced queries on a data set, and automatically returns relevant updated results every time new data is added to the set?
I'm looking for a cloud service that can do advanced statistics calculations on a large amount of votes submitted by users, in "real time".

In our app, users can submit different kind of votes like picking a favorite, rating 1-5, say yes/no etc. on various topics.

We also want to show "live" statistics to the user, showing the popularity of a person etc. This will be generated by a rather complex SQL where we are calculating the average number of times a person was picked as favorite, divided by total number of votes and the number of games in which the person has been participating etc. And the score for the latest X games should count higher than the overall score for all games. This is just an example, there are several other SQL queries with similar complexity.

All our presentable data (including calculated statistics) is served from Firestore documents, and the votes will be saved as Firestore documents.

Ideally, the Firebase-backend (functions, firestore etc) should not need to know about the query logic.

What I wish for is a pay as you go cloud service that does the following:

I define some schemas and set up the queries we need for the statistics we have (15-20 different SQLs). Like setting up views in MySQL

On every vote, we push the vote data to this service, which will store it in a row.

The service should then, based on its knowledge about the defined queries, and the content of the pushed vote data, determine which statistics that are affected by the newly added row, and recalculate these. A specific vote type can affect one or more statistics.

Every time a statistic is recalculated, the result should be automatically pushed back to our Firebase backend (for instance by calling an HTTPS endpoint that hits a cloud function) - so we can update the relevant Firestore documents.

The service should be able to throttle the calculations, like only regenerating new statistics every 1 minute despite having several votes per second on the same topic.

Is there any product like this in the market? Or can it be built by combining available cloud services? And what is the official term for such a product, if I should search for it myself?

I know that I can probably build a solution like this myself, and run it on a cloud hosted database server, which can scale as our need grows - but I believe that I'm not the first developer with a need of this, so I hope that someone has solved it before me :)

答:
You can leverage the existing cloud services available on the Google Cloud Platform.
Google BigQuery, Google Cloud Firestore, Google App Engine (CRON Jobs), Google Cloud Tasks

The services can be used to solve the problems mentioned above:

1) Google BigQuery : Here you can define schema for the data on which you're going to run the SQL queries. BigQuery supports Standard and legacy SQL queries.

2) Every vote can be pushed to the defined BigQuery tables using its streaming insert service.

3) Every vote pushed can trigger the recalculation service which calculates the statistics by executing the defined SQL queries and the query results can be stored as documents in collections in Google Cloud Firestore.

4) Google Cloud Firestore: Here you can store the live statistics of the user. This is a real time database, so you'll be able to configure listeners for the modifications to the statistics and show the modifications as soon as the statistics are recalculated.

5) In the same service which inserts every vote, create a new record with a "syncId" in an another table. The idea is to group a number of votes cast in a particular interval to a its corresponding syncId. The syncId can be suffixed with a timestamp. According to your requirement a particular time interval can be set so that the recalculation can be triggered using CRON jobs service which invokes the recalculation service within the interval. Once the recalculation related to a particular syncId is completed the record corresponding to the syncId should be marked as completed.

We are leveraging the above technologies to build a web application on Google Cloud Platform, where the inputs are recorded on Google Firestore and then stream-inserted to Google BigQuery. The data stored in BigQuery is queried after 30 sec of each update using SQL queries and the query results are stored in Google Cloud Firestore to serve dashboards which are automatically updated using listeners configured for the collection in which the dashboard information is stored.


问:
Remove title from ScatterChart
I would like to know how to be able to assign a name just to a serie of data (using a scatterchart), without getting the same serie's name as title of the chart. I would like to get just the series name as legend and NOT chart title at all.

I realized that autoTitleDeleted needs to have a value of 1.

So, consulting documentation I found that ´chartContainer´ is the class to implement the aforementioned option. Therefore, I import the class and apply it as next:

```<code>from openpyxl import Workbook
from openpyxl.chart import (
        ScatterChart,
        Reference,
        Series,
)
from openpyxl.chart.chartspace import ChartContainer

wb = Workbook()
ws = wb.active

rows = [
        ["Size", "Batch 1", "Batch 2"],
        [2, 40, 30],
        [3, 40, 25],
        [4, 50, 30],
        [5, 30, 25],
        [6, 25, 35],
        [7, 20, 40],
]

for row in rows:
    ws.append(row)

chart2 = ScatterChart()

chart2.x_axis.title = "Size"
chart2.y_axis.title = "Percentage"

xvalues = Reference(ws, min_col = 1, min_row = 2, max_row = 7)
values = Reference(ws, min_col = 3, min_row = 1, max_row = 7)
series1 = Series(values, xvalues)
chart2.series.append(series1)

chart2 = ChartContainer(autoTitleDeleted = 1)

ws.add_chart(chart2, "J10")

wb.save("Ex1.xlsx")
</code>```

However, next error comes up:

`runfile('C:/Users/Administrador/Desktop/Pre-Try/Ex1/Ex1.py', wdir='C:/Users/Administrador/Desktop/Pre-Try/Ex1')
Traceback (most recent call last):

File "", line 1, in
    runfile('C:/Users/Administrador/Desktop/Pre-Try/Ex1/Ex1.py', wdir='C:/Users/Administrador/Desktop/Pre-Try/Ex1')

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/Administrador/Desktop/Pre-Try/Ex1/Ex1.py", line 46, in
    wb.save("Ex1.xlsx")

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\workbook\workbook.py", line 397, in save
    save_workbook(self, filename)

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\writer\excel.py", line 294, in save_workbook
    writer.save()

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\writer\excel.py", line 276, in save
    self.write_data()

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\writer\excel.py", line 76, in write_data
    self._write_worksheets()

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\writer\excel.py", line 219, in _write_worksheets
    self._write_drawing(ws._drawing)

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\writer\excel.py", line 142, in _write_drawing
    self._archive.writestr(drawing.path[1:], tostring(drawing._write()))

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\drawing\spreadsheet_drawing.py", line 296, in _write
    self._rels.append(rel)

UnboundLocalError: local variable 'rel' referenced before assignment`

I do not really understand this error. If you could help would be grateful!

答:
chart2 = ChartContainer(autoTitleDeleted = 1)
This the problem: you must use openpyxl chart objects so that the library can manage the plumbing between objects: charts are very complicated objects and we try and hide some of the complexity Your idea is correct - to set the value to True – but that won't work like this because a ChartContainer doesn't know how to add itself to the XLSX package.

As a workaround it's probably easiest create a title with an empty string. Otherwise you could submit a PR that allows the mapping of the autoTitleDeleted attribute from chartContainers to charts and vice versa.

Title: Remove title from ScatterChart

Body:
I would like to know how to be able to assign a name just to a serie of data (using a scatterchart), without getting the same serie's name as title of the chart. I would like to get just the series name as legend and NOT chart title at all.

I realized that autoTitleDeleted needs to have a value of 1.

So, consulting documentation I found that ´chartContainer´ is the class to implement the aforementioned option. Therefore, I import the class and apply it as next:

from openpyxl import Workbook
from openpyxl.chart import (
        ScatterChart,
        Reference,
        Series,
)
from openpyxl.chart.chartspace import ChartContainer

wb = Workbook()
ws = wb.active

rows = [
        ["Size", "Batch 1", "Batch 2"],
        [2, 40, 30],
        [3, 40, 25],
        [4, 50, 30],
        [5, 30, 25],
        [6, 25, 35],
        [7, 20, 40],
]

for row in rows:
    ws.append(row)

chart2 = ScatterChart()

chart2.x_axis.title = "Size"
chart2.y_axis.title = "Percentage"

xvalues = Reference(ws, min_col = 1, min_row = 2, max_row = 7)
values = Reference(ws, min_col = 3, min_row = 1, max_row = 7)
series1 = Series(values, xvalues)
chart2.series.append(series1)

chart2 = ChartContainer(autoTitleDeleted = 1)

ws.add_chart(chart2, "J10")

wb.save("Ex1.xlsx")

However, next error comes up:

`runfile('C:/Users/Administrador/Desktop/Pre-Try/Ex1/Ex1.py', wdir='C:/Users/Administrador/Desktop/Pre-Try/Ex1')
Traceback (most recent call last):

File "", line 1, in
    runfile('C:/Users/Administrador/Desktop/Pre-Try/Ex1/Ex1.py', wdir='C:/Users/Administrador/Desktop/Pre-Try/Ex1')

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/Administrador/Desktop/Pre-Try/Ex1/Ex1.py", line 46, in
    wb.save("Ex1.xlsx")

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\workbook\workbook.py", line 397, in save
    save_workbook(self, filename)

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\writer\excel.py", line 294, in save_workbook
    writer.save()

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\writer\excel.py", line 276, in save
    self.write_data()

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\writer\excel.py", line 76, in write_data
    self._write_worksheets()

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\writer\excel.py", line 219, in _write_worksheets
    self._write_drawing(ws._drawing)

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\writer\excel.py", line 142, in _write_drawing
    self._archive.writestr(drawing.path[1:], tostring(drawing._write()))

File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\drawing\spreadsheet_drawing.py", line 296, in _write
    self._rels.append(rel)

UnboundLocalError: local variable 'rel' referenced before assignment`

I do not really understand this error. If you could help would be grateful!


问:
Azure virtual machine in stopped state and can't start
I have a Azure VM that I created manually and deployed some services on it. Now all the sudden it is in a stopped state and I can't start it anymore. Below is the error message that I get when I try to start it.

Failed to start virtual machine Failed to start the virtual machine
  'xxxxxxxxx'. De bewerking d329ae99fc74571693e4e5590ad38ef4 is mislukt:
  Cannot perform the operation on a stopped deployment..

I didn't do any deployment. The machine was installed manually. Please tell me this can be recovered since a lot of hours went into this. Does anyone know how to solve this?

答:
I stumbled onto this issue today, and although it has been four years, this was the first post I found about it. Someone might be helped by this new trick I found to solve this.

I simply set the auto-shutdown schedule very close to the current time so that it could shuts the virtual machine properly. That did the trick! I could restart it afterwards without trouble.

Saved me the trouble of creating a new resource.


问:
How do I import a module from another project in Python?
I'm trying to to refer a old project module for the new project is there any possible way for referring the module easily.

```<code>project1/
    folder1/
        main.py
        secondary.py-----------
    folder2/                  |
        test.py               |
                              |
project2/                     |
    folder1/                  |
        main1.py              |
            <------------------
</code>```

Since, I tried to append the path,

I can't import it

```<code>import sys
sys.path.append('project1/folder1/secondary.py')

from project.folder1 import seconday

or someother formats
</code>```

答:
Don't append the Python file to the path, append the path where the entire package is located in. For example, if both of your projects are in a projects folder like so:

```<code>~/Documents/projects/project1/
~/Documents/projects/project2/
</code>```

Now you would do:

```<code>sys.path.append('~/Documents/projects')
from project1.folder1 import secondary
</code>```

You can also provide a relative path and use sys.path.abspath() to convert it:

```<code>sys.path.append(sys.path.abspath('../..'))
</code>```

Body:
I'm trying to to refer a old project module for the new project is there any possible way for referring the module easily.

project1/
    folder1/
        main.py
        secondary.py-----------
    folder2/                  |
        test.py               |
                              |
project2/                     |
    folder1/                  |
        main1.py              |
            <------------------

Since, I tried to append the path,

I can't import it

import sys
sys.path.append('project1/folder1/secondary.py')

from project.folder1 import seconday

or someother formats

Body:
Don't append the Python file to the path, append the path where the entire package is located in. For example, if both of your projects are in a projects folder like so:

~/Documents/projects/project1/
~/Documents/projects/project2/

Now you would do:

sys.path.append('~/Documents/projects')
from project1.folder1 import secondary

You can also provide a relative path and use sys.path.abspath() to convert it:

sys.path.append(sys.path.abspath('../..'))


问:
Binding DataTables to Datagrids on a WPF Tabcontrol
I have a wpf TabControl and a ListBox. If I click on one of the items in the ListBox I want to get data from a certain table on an SQL Server, add a new tab to the TabControl and display the data on a DataGrid on this new tab. So far I have this:

XAML for the TabControl and the ListBox:

```<code> <Grid>
    <ListBox x:Name="lb"  ItemsSource="{Binding Alltables}" MouseDoubleClick="opendata"/>

    <TabControl x:Name="tabControl"  ItemsSource="{Binding SelectedTables}">
        <TabControl.ContentTemplate >
            <DataTemplate >
                <Grid>
                    <DataGrid x:Name="dataGrid" AutoGenerateColumns="True" ItemsSource="{Binding Tablecontent}"/>
                </Grid>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</Grid>
</code>```

My ViewModel:

```<code>   public class MainViewModel : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string name)
        {

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }

        }

        private ObservableCollection<String> selectedtables;
    public ObservableCollection<String> SelectedTables
    {
        get { return selectedtables; }
        set
        {
            if (selectedtables != value)
            {

                selectedtables = value;
                OnPropertyChanged("SelectedTables");
            }
        }
    }

    private ObservableCollection<DataTable> tablecontent;
    public ObservableCollection<DataTable> Tablecontent
    {
        get { return tablecontent; }
        set
        {
            if (tablecontent != value)
            {
                tablecontent = value;
                OnPropertyChanged("Tablecontent");
            }
        }
    }

}
</code>```

The click event for the ListBox:

```<code>   private void opendata(object sender, MouseButtonEventArgs e)
    {
//...
 //Some preparations before querying the data etc.
//...

   DataTable mydata = new DataTable();

        using (connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            mydata.Load(reader);
        }

        string tabletoload = lb.SelectedItem.ToString();

        myview2.SelectedTables.Add(tabletoload); //myview2 is the instance of my ViewModel

        myview2.Tablecontent.Add(mydata); //myview2 is the instance of my ViewModel
    }
}
</code>```

What happens now is that when I click on one of the items in the ListBox there is correctly a new tab created with the text of the selected ListBox Item as Header and also a DataGrid - however the DataGrid remains empty.

Would be really amazing if you could help me. I have looked through all the similar questions here on SO but none of the solutions seems to solve my issue. If I don't use a tab control and simply add a DataGrid directly on the form everything works perfectly. Also creating and adding everything directly in code works fine but I would like to solve this in a more correct way.

答:
SelectedTables should return an IEnumerable<T> where the type T defines the name and the DataTable for the current tab:

```<code>public class TabViewModel
{
    public string Header { get; set; }
    public DataTable Tablecontent { get; set; }
}

public class MainViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

    private ObservableCollection<TabViewModel> selectedtables;
    public ObservableCollection<TabViewModel> SelectedTables
    {
        get { return selectedtables; }
        set
        {
            if (selectedtables != value)
            {

                selectedtables = value;
                OnPropertyChanged("SelectedTables");
            }
        }
    }
}
</code>```

You would then add a new T (named TabViewModel in the sample code above) to the MainViewModel in your opendata method:

```<code>string tabletoload = lb.SelectedItem.ToString();
myview2.SelectedTables.Add(new TabViewModel() { Header = tabletoload, Tablecontent = mydata });
</code>```

...and define an ItemTemplate for the TabControl in the view to display the header:

```<code><TabControl x:Name="tabControl"  ItemsSource="{Binding SelectedTables}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Header}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate >
        <DataTemplate >
            <Grid>
                <DataGrid x:Name="dataGrid" AutoGenerateColumns="True" ItemsSource="{Binding Tablecontent}"/>
            </Grid>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>
</code>```

Body:
I have a wpf TabControl and a ListBox. If I click on one of the items in the ListBox I want to get data from a certain table on an SQL Server, add a new tab to the TabControl and display the data on a DataGrid on this new tab. So far I have this:

XAML for the TabControl and the ListBox:

 <Grid>
    <ListBox x:Name="lb"  ItemsSource="{Binding Alltables}" MouseDoubleClick="opendata"/>

    <TabControl x:Name="tabControl"  ItemsSource="{Binding SelectedTables}">
        <TabControl.ContentTemplate >
            <DataTemplate >
                <Grid>
                    <DataGrid x:Name="dataGrid" AutoGenerateColumns="True" ItemsSource="{Binding Tablecontent}"/>
                </Grid>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</Grid>

My ViewModel:

   public class MainViewModel : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string name)
        {

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }

        }

        private ObservableCollection<String> selectedtables;
    public ObservableCollection<String> SelectedTables
    {
        get { return selectedtables; }
        set
        {
            if (selectedtables != value)
            {

                selectedtables = value;
                OnPropertyChanged("SelectedTables");
            }
        }
    }

    private ObservableCollection<DataTable> tablecontent;
    public ObservableCollection<DataTable> Tablecontent
    {
        get { return tablecontent; }
        set
        {
            if (tablecontent != value)
            {
                tablecontent = value;
                OnPropertyChanged("Tablecontent");
            }
        }
    }

}

The click event for the ListBox:

   private void opendata(object sender, MouseButtonEventArgs e)
    {
//...
 //Some preparations before querying the data etc.
//...

   DataTable mydata = new DataTable();

        using (connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            mydata.Load(reader);
        }

        string tabletoload = lb.SelectedItem.ToString();

        myview2.SelectedTables.Add(tabletoload); //myview2 is the instance of my ViewModel

        myview2.Tablecontent.Add(mydata); //myview2 is the instance of my ViewModel
    }
}

What happens now is that when I click on one of the items in the ListBox there is correctly a new tab created with the text of the selected ListBox Item as Header and also a DataGrid - however the DataGrid remains empty.

Would be really amazing if you could help me. I have looked through all the similar questions here on SO but none of the solutions seems to solve my issue. If I don't use a tab control and simply add a DataGrid directly on the form everything works perfectly. Also creating and adding everything directly in code works fine but I would like to solve this in a more correct way.

Body:
SelectedTables should return an IEnumerable<T> where the type T defines the name and the DataTable for the current tab:

public class TabViewModel
{
    public string Header { get; set; }
    public DataTable Tablecontent { get; set; }
}

public class MainViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

    private ObservableCollection<TabViewModel> selectedtables;
    public ObservableCollection<TabViewModel> SelectedTables
    {
        get { return selectedtables; }
        set
        {
            if (selectedtables != value)
            {

                selectedtables = value;
                OnPropertyChanged("SelectedTables");
            }
        }
    }
}

You would then add a new T (named TabViewModel in the sample code above) to the MainViewModel in your opendata method:

string tabletoload = lb.SelectedItem.ToString();
myview2.SelectedTables.Add(new TabViewModel() { Header = tabletoload, Tablecontent = mydata });

...and define an ItemTemplate for the TabControl in the view to display the header:

<TabControl x:Name="tabControl"  ItemsSource="{Binding SelectedTables}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Header}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate >
        <DataTemplate >
            <Grid>
                <DataGrid x:Name="dataGrid" AutoGenerateColumns="True" ItemsSource="{Binding Tablecontent}"/>
            </Grid>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>


问:
how to extract date from string in sql oracle 9i
I have column Explanation (VARCHAR2) in table:

```<code>No| Explanation
1 | Shipment of cabbage by agreement 29.04.2019 TAX Free
2 | Payment for screws (01.04.19) Tax: 13.55 %
3 | For reserch by deal dated 01.01.2015 Tax free
4 | Tax payment for the may 2019
</code>```

I need query thats will answer "Does entry have a date in some form in it?" Yes / No for each entry. Is it possible on Oracle 9i?

I tried some solutions. But run into issue:

"ORA-01858: a non-numeric character was found where a numeric was expected".

I don't clearly now where datestamp will be in field.

select to_char(to_date(EXPLANATION, 'DD.MM.YYYY')) from PAYMENTDOC

答:
You can do this using regular expression. Try below code :

```<code>  select No, Explanation,
  case when regexp_instr(Explanation,'\d{2}.\d{2}.\d{2}')!=1 then
              'Y'
              when regexp_instr(Explanation,'\d{2}.\d{2}.\d{4}')!=1 then
              'Y'
              when REGEXP_instr(Explanation, '(January|February|March|April|May|June|July|August|September|October|November|December) [0-9]{4}')!=1 then
              'Y'
             END Does_entry_have_a_date_in_some_form_in_it
  from table_name;
</code>```

Output :

```<code>No| Explanation                                          | Does_entry_have_a_date_in_some_form_in_it
1 | Shipment of cabbage by agreement 29.04.2019 TAX Free | Y
2 | Payment for screws (01.04.19) Tax: 13.55 %           | Y
3 | For reserch by deal dated 01.01.2015 Tax free        | Y
4 | Tax payment for the may 2019                         | Y
</code>```

Body:
I have column Explanation (VARCHAR2) in table:

No| Explanation
1 | Shipment of cabbage by agreement 29.04.2019 TAX Free
2 | Payment for screws (01.04.19) Tax: 13.55 %
3 | For reserch by deal dated 01.01.2015 Tax free
4 | Tax payment for the may 2019

I need query thats will answer "Does entry have a date in some form in it?" Yes / No for each entry. Is it possible on Oracle 9i?

I tried some solutions. But run into issue:

"ORA-01858: a non-numeric character was found where a numeric was expected".

I don't clearly now where datestamp will be in field.

select to_char(to_date(EXPLANATION, 'DD.MM.YYYY')) from PAYMENTDOC

Body:
You can do this using regular expression. Try below code :

  select No, Explanation,
  case when regexp_instr(Explanation,'\d{2}.\d{2}.\d{2}')!=1 then
              'Y'
              when regexp_instr(Explanation,'\d{2}.\d{2}.\d{4}')!=1 then
              'Y'
              when REGEXP_instr(Explanation, '(January|February|March|April|May|June|July|August|September|October|November|December) [0-9]{4}')!=1 then
              'Y'
             END Does_entry_have_a_date_in_some_form_in_it
  from table_name;

Output :

No| Explanation                                          | Does_entry_have_a_date_in_some_form_in_it
1 | Shipment of cabbage by agreement 29.04.2019 TAX Free | Y
2 | Payment for screws (01.04.19) Tax: 13.55 %           | Y
3 | For reserch by deal dated 01.01.2015 Tax free        | Y
4 | Tax payment for the may 2019                         | Y