问:
SQL error while converting varchar to int by joining two tables
I need to find missing numbers in my database. I am comparing two databases, tempdb created in query with numbers 1 - 999 and MYDAT.

MYDAT looks like:

```<code>+-------+
|  id   |
+-------+
| A-001 |
| A-002 |
| A-004 |
| A-... |
| A-952 |
| A-... |
+-------+
</code>```

I am running this query:

```<code>declare @tempid int

set @tempid = 1

create table tempdb (tempid int)

while @tempid < 1000
begin
    insert into tempdb values(@tempid)
    set @tempid = @tempid + 1
end

select tempdb.tempid from tempdb
left join MYDAT on tempdb.tempid = CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT)
where
MYDAT.ID IS NULL and
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'

drop table tempdb
</code>```

Without droping temdb, select * from tempdb looks good and i am getting what i want.

The part with selecting and converting data from MYDAT works good and i am getting only integers

```<code>select CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT) fom MYDAT
where
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'
</code>```

I am getting an error "converting varchar to int" but i have no idea why. When i change left join to right join, i get no errors.

I also checked both databases manually and there are no strings or characters, only integers.

I also tried the CONVERT() but with same result.

Any suggestions or ideas what is the problem?

Edit:

1 - I see one mistake as i tried it on rextester. I added MYDAT.ID IS NULL to the query so i get correct results.

2 - Examples
I need this: http://rextester.com/KFG73206

But CAST or CONVERT just does not seems to work http://rextester.com/WJIAH52304

答: You did say 'missing numbers' so things in tempdb that aren't in MYDAT are what you're after? If so see: http://rextester.com/HCB88714</p>

Body:
I need to find missing numbers in my database. I am comparing two databases, tempdb created in query with numbers 1 - 999 and MYDAT.

MYDAT looks like:

+-------+
|  id   |
+-------+
| A-001 |
| A-002 |
| A-004 |
| A-... |
| A-952 |
| A-... |
+-------+

I am running this query:

declare @tempid int

set @tempid = 1

create table tempdb (tempid int)

while @tempid < 1000
begin
    insert into tempdb values(@tempid)
    set @tempid = @tempid + 1
end

select tempdb.tempid from tempdb
left join MYDAT on tempdb.tempid = CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT)
where
MYDAT.ID IS NULL and
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'

drop table tempdb

Without droping temdb, select * from tempdb looks good and i am getting what i want.

The part with selecting and converting data from MYDAT works good and i am getting only integers

select CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT) fom MYDAT
where
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'

I am getting an error "converting varchar to int" but i have no idea why. When i change left join to right join, i get no errors.

I also checked both databases manually and there are no strings or characters, only integers.

I also tried the CONVERT() but with same result.

Any suggestions or ideas what is the problem?

Edit:

1 - I see one mistake as i tried it on rextester. I added MYDAT.ID IS NULL to the query so i get correct results.

2 - Examples
I need this: http://rextester.com/KFG73206

But CAST or CONVERT just does not seems to work http://rextester.com/WJIAH52304


来源: stackexchange

问:
grunt-mocha: PhantomJS timed out, possibly due to a missing Mocha run() call
I tried using grunt-mocha with requirejs, but I get this error:

```<code>Warning: PhantomJS timed out, possibly due to a missing Mocha run() call. Use --force to continue.
</code>```

If I try using the simplest example present on mochajs.org - it works, but for some reason not with requirejs.

Here are my files.

test/browser/runner.html:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Browser test</title>
    <link rel="stylesheet" media="all" href="./../../bower_components/mocha/mocha.css">
</head>
<body>

    <div id="mocha"></div>

    <script data-main="runner.js" src="./../../bower_components/requirejs/require.js"></script>
</body>
</html>
</code>```

test/browser/runner.js: (I tried multiple versions so far, this is the most recent, but still times out)

```<code>requirejs.config({
    baseUrl: './../../',
    paths: {
        'jquery': 'bower_components/jquery/dist/jquery',
        'chai': 'bower_components/chai/chai',
        'mocha': 'bower_components/mocha/mocha'
    },
    shim: {}
});

define(function(require) {

    require('chai');
    require('mocha');

    mocha.setup('bdd');

    require([
        'test/src/test.component'
    ], function() {
        console.log('component success');
        mocha.run();
        console.log('mocha should be running');
    }, function() {
        console.log('component error');
    });

});
</code>```

test/src/test.component.js:

```<code>define(function(require) {
    describe('Component', function() {
        it('test', function() {
            console.log('testing...');
        });
    });
});
</code>```

Gruntfile.js

```<code>module.exports = function(grunt) {

    grunt.initConfig({
        mocha: {
            options: {
                reporter: 'Spec',
                log: true,
                run: true
            },
            src: ['./test/**/*.html']
        }
    });

    grunt.loadNpmTasks('grunt-mocha');
};
</code>```

The output is this:

```<code>$ grunt mocha
Running "mocha:src" (mocha) task
Testing: ./test/browser/runner.html
component success
mocha should be running
testing...

Warning: PhantomJS timed out, possibly due to a missing Mocha run() call. Use --force to continue.

Aborted due to warnings.
</code>```

so I'm pretty sure there are no syntactical errors and it should work. I'm probably just having a brain fart :)

Any idea would be greatly appreciated.
Thanks guys

答:
I had same problem -- I solved it with the grunt-mocha-test plugin. I changed the task naming in the grunt file to mochaTest, and installed grunt-mocha-test with:

```<code>npm install grunt-mocha-test --save-dev
</code>```

Now it's working.

ContentLicense: CC BY-SA 3.0

Body:
I tried using grunt-mocha with requirejs, but I get this error:

Warning: PhantomJS timed out, possibly due to a missing Mocha run() call. Use --force to continue.

If I try using the simplest example present on mochajs.org - it works, but for some reason not with requirejs.

Here are my files.

test/browser/runner.html:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Browser test</title>
    <link rel="stylesheet" media="all" href="./../../bower_components/mocha/mocha.css">

test/browser/runner.js: (I tried multiple versions so far, this is the most recent, but still times out)

requirejs.config({
    baseUrl: './../../',
    paths: {
        'jquery': 'bower_components/jquery/dist/jquery',
        'chai': 'bower_components/chai/chai',
        'mocha': 'bower_components/mocha/mocha'
    },
    shim: {}
});

define(function(require) {

    require('chai');
    require('mocha');

    mocha.setup('bdd');

    require([
        'test/src/test.component'
    ], function() {
        console.log('component success');
        mocha.run();
        console.log('mocha should be running');
    }, function() {
        console.log('component error');
    });

});

test/src/test.component.js:

define(function(require) {
    describe('Component', function() {
        it('test', function() {
            console.log('testing...');
        });
    });
});

Gruntfile.js

module.exports = function(grunt) {

    grunt.initConfig({
        mocha: {
            options: {
                reporter: 'Spec',
                log: true,
                run: true
            },
            src: ['./test/**/*.html']
        }
    });

    grunt.loadNpmTasks('grunt-mocha');
};

The output is this:

$ grunt mocha
Running "mocha:src" (mocha) task
Testing: ./test/browser/runner.html
component success
mocha should be running
testing...

Warning: PhantomJS timed out, possibly due to a missing Mocha run() call. Use --force to continue.

Aborted due to warnings.

so I'm pretty sure there are no syntactical errors and it should work. I'm probably just having a brain fart :)

Any idea would be greatly appreciated.
Thanks guys

Body:
I had same problem -- I solved it with the grunt-mocha-test plugin. I changed the task naming in the grunt file to mochaTest, and installed grunt-mocha-test with:

npm install grunt-mocha-test --save-dev

Now it's working.

ContentLicense: CC BY-SA 4.0


问:
How to force breaking of non breakable strings?
I have an HTML page that I generate from the data contained in a database. The database sometimes contains long strings that the browser can't break because the strings don't contain breakable characters (space, point, comma, etc...).

Is there any way to fix this using html, css or even javascript?

See this link for an example of the problem.

答:
It is also possible to use word-break css property to cut every word on the element edge.

```<code>.selector_name {
  word-break: break-all;
}

<p class="selector_name">some words some words some words some words</p>

you can obtain:
some word|
s some wo|<-edge of the element
rds some |
words som|
e words  |
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It is also possible to use word-break css property to cut every word on the element edge.

.selector_name {
  word-break: break-all;
}

<p class="selector_name">some words some words some words some words</p>

you can obtain:
some word|
s some wo|<-edge of the element
rds some |
words som|
e words  |


问:
Infragistics XamGrid: How to prevent column filter from showing time?
We are using DateTime columns with time, but need the (excel style distinct elements) column filter to show only the dates, without time. Is that possible?

I found an article at Infragistics which describes how to add a custom filter but not how to change an existing one.

答:
Got the following code snipped from infragistics support (thanks Tacho!):</p>

```<code>private void XamDataGrid_RecordFilterDropDownOpening(object sender, RecordFilterDropDownOpeningEventArgs e)
{
    if (e.Field.DataType == typeof(DateTime))
    {
        List<FilterDropDownItem> cellValues = e.DropDownItems.Where(i => i.IsCellValue).ToList();
        foreach (FilterDropDownItem item in cellValues)
            e.DropDownItems.Remove(item);

        foreach (FilterDropDownItem item in cellValues)
        {
            item.DisplayText = (item.Value as DateTime?).Value.ToString("yyyy/MM/dd");
            if (!e.DropDownItems.Contains(e.DropDownItems.FirstOrDefault(i => i.DisplayText == item.DisplayText)))
            {
                var newItem = new FilterDropDownItem(new Infragistics.Windows.Controls.ComparisonCondition(
                    Infragistics.Windows.Controls.ComparisonOperator.Contains, item.DisplayText), item.DisplayText);
                e.DropDownItems.Add(newItem);
            }
        }
    }
}
</code>```

Body:
Got the following code snipped from infragistics support (thanks Tacho!):

private void XamDataGrid_RecordFilterDropDownOpening(object sender, RecordFilterDropDownOpeningEventArgs e)
{
    if (e.Field.DataType == typeof(DateTime))
    {
        List<FilterDropDownItem> cellValues = e.DropDownItems.Where(i => i.IsCellValue).ToList();
        foreach (FilterDropDownItem item in cellValues)
            e.DropDownItems.Remove(item);

        foreach (FilterDropDownItem item in cellValues)
        {
            item.DisplayText = (item.Value as DateTime?).Value.ToString("yyyy/MM/dd");
            if (!e.DropDownItems.Contains(e.DropDownItems.FirstOrDefault(i => i.DisplayText == item.DisplayText)))
            {
                var newItem = new FilterDropDownItem(new Infragistics.Windows.Controls.ComparisonCondition(
                    Infragistics.Windows.Controls.ComparisonOperator.Contains, item.DisplayText), item.DisplayText);
                e.DropDownItems.Add(newItem);
            }
        }
    }
}


问:
Angular Service passing variable value to app.component
I have a service which contains a variable called url.

Here is the code:

```<code>//service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import  'rxjs/add/operator/map';
import  'rxjs/add/operator/do';
import  'rxjs/add/operator/catch';

@Injectable()
export class DataService {

  private url = 'http://someurl.com/';

  constructor (private _http:Http){}

  getDataHttp():Observable<any> {
    return this._http.get(this.url)
      .map((response: Response) => <any> response.json())
      .do(data => console.log('All: ' +  JSON.stringify(data)))
      .catch(this.handleError);
  }

  private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

}
</code>```

Here is the file where I want to call the url variable from the service:

```<code>// app.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  errorMessage;
  data;

  constructor(private service:DataService)  {}

  ngOnInit() {
    this.service.getDataHttp()
      .subscribe(data => this.data = data,
        error => this.errorMessage = <any>error);

  }

}
</code>```

My question is ... How can I pass the url value from the service.ts to app.component.ts ?

答:
For instance add getter/setter methods to DataService:

```<code>public getUrl(){
    return this.url;
}

public setUrl(url:string){
    this.url = url;
    return this.url;
}
</code>```

and then call them like this from AppComponent:

```<code>let url = this.service.getUrl();
</code>```

to retrieve the value, and:

```<code>this.service.setUrl(another_url);
</code>```

to set it.

Body:
I have a service which contains a variable called url.

Here is the code:

//service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import  'rxjs/add/operator/map';
import  'rxjs/add/operator/do';
import  'rxjs/add/operator/catch';

@Injectable()
export class DataService {

  private url = 'http://someurl.com/';

  constructor (private _http:Http){}

  getDataHttp():Observable<any> {
    return this._http.get(this.url)
      .map((response: Response) => <any> response.json())
      .do(data => console.log('All: ' +  JSON.stringify(data)))
      .catch(this.handleError);
  }

  private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

}

Here is the file where I want to call the url variable from the service:

// app.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  errorMessage;
  data;

  constructor(private service:DataService)  {}

  ngOnInit() {
    this.service.getDataHttp()
      .subscribe(data => this.data = data,
        error => this.errorMessage = <any>error);

  }

}

My question is ... How can I pass the url value from the service.ts to app.component.ts ?

Body:
For instance add getter/setter methods to DataService:

public getUrl(){
    return this.url;
}

public setUrl(url:string){
    this.url = url;
    return this.url;
}

and then call them like this from AppComponent:

let url = this.service.getUrl();

to retrieve the value, and:

this.service.setUrl(another_url);

to set it.


问:
Regex - match words which only consists of certain characters and certain char is repeated certain times
I have words database containing of 300 000+ words

I want to match words which length is known (7 for example) and it contains
only certain characters and some of them can be repeated certain times but not all of them

for example

I have a,p,p,l,e,r,t,h,o  chars and I want to find words which length is 5

so, it can match

apple

earth

but not

hello because l is specified more than one time

My attempts

```<code> ^([a,p,p,l,e,r,t,h,o]{1}) # capture first char

 (!/1 [a,p,p,l,e,r,t,h,o]{1}) # capture second char but without firstly captured symbol

 (!/1 !/2 [a,p,p,l,e,r,t,h,o]{1}) # capture third char but without first and second captured symbol

and so on  ...
</code>```

答:
I know that this is not a regex solution to the problem, but sometimes regex isn't the solution.

```<code>public class WordChecker
{
    public WordChecker(params char[] letters)
    {
        Counters = letters.GroupBy(c => c).ToDictionary(g => g.Key, g => new Counter(g.Count()));
    }
    public WordChecker(string letters) : this(letters.ToArray())
    {
    }

    public bool CheckWord(string word)
    {
        Initialize();
        foreach (var c in word)
        {
            Counter counter;
            if (!Counters.TryGetValue(c, out counter)) return false;
            if (!counter.Add()) return false;
        }
        return true;
    }

    private void Initialize()
    {
        foreach (var counter in Counters)
            counter.Value.Initialize();
    }
    private Dictionary<char, Counter> Counters;
    private class Counter
    {
        public Counter(int maxCount)
        {
            MaxCount = maxCount;
            Count = 0;
        }
        public void Initialize()
        {
            Count = 0;
        }
        public bool Add()
        {
            Count++;
            return Count <= MaxCount;
        }
        public int MaxCount { get; private set; }
        public int Count { get; private set; }
    }
}
</code>```

And the way to use it is like this:

```<code>    WordChecker checker = new WordChecker("applertho");
    List<string> words = new List<string>(){"apple", "giraf", "earth", "hello"};
    foreach (var word in words)
        if (checker.CheckWord(word))
        {
            // The word is valid!
        }
</code>```

Body:
I have words database containing of 300 000+ words

I want to match words which length is known (7 for example) and it contains
only certain characters and some of them can be repeated certain times but not all of them

for example

I have a,p,p,l,e,r,t,h,o  chars and I want to find words which length is 5

so, it can match

apple

earth

but not

hello because l is specified more than one time

My attempts

 ^([a,p,p,l,e,r,t,h,o]{1}) # capture first char

 (!/1 [a,p,p,l,e,r,t,h,o]{1}) # capture second char but without firstly captured symbol

 (!/1 !/2 [a,p,p,l,e,r,t,h,o]{1}) # capture third char but without first and second captured symbol

and so on  ...

Body:
I know that this is not a regex solution to the problem, but sometimes regex isn't the solution.

public class WordChecker
{
    public WordChecker(params char[] letters)
    {
        Counters = letters.GroupBy(c => c).ToDictionary(g => g.Key, g => new Counter(g.Count()));
    }
    public WordChecker(string letters) : this(letters.ToArray())
    {
    }

    public bool CheckWord(string word)
    {
        Initialize();
        foreach (var c in word)
        {
            Counter counter;
            if (!Counters.TryGetValue(c, out counter)) return false;
            if (!counter.Add()) return false;
        }
        return true;
    }

    private void Initialize()
    {
        foreach (var counter in Counters)
            counter.Value.Initialize();
    }
    private Dictionary<char, Counter> Counters;
    private class Counter
    {
        public Counter(int maxCount)
        {
            MaxCount = maxCount;
            Count = 0;
        }
        public void Initialize()
        {
            Count = 0;
        }
        public bool Add()
        {
            Count++;
            return Count <= MaxCount;
        }
        public int MaxCount { get; private set; }
        public int Count { get; private set; }
    }
}

And the way to use it is like this:

    WordChecker checker = new WordChecker("applertho");
    List<string> words = new List<string>(){"apple", "giraf", "earth", "hello"};
    foreach (var word in words)
        if (checker.CheckWord(word))
        {
            // The word is valid!
        }


问:
'Models' object has no attribute 'update'
I'm trying to create a new function but I'm getting this Django error :

'SocieteIntervention' object has no attribute 'update'

I have several models in my application :

```<code>class Societe(models.Model):

    Nom = models.CharField(null= False, max_length=30, verbose_name='Nom de Société')
    Etat = models.CharField(max_length = 30, choices = CHOIX_ETAT_SOCIETE, null=False, verbose_name="Etat")
    Adresse = models.CharField(max_length=30, verbose_name='Adresse')
    Ville = models.CharField(max_length=30, verbose_name='Ville')
    Zip = models.IntegerField(verbose_name='Code Postal')
    Region = models.CharField(max_length=30, verbose_name='Région')
    Pays = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays')
    Mail = models.CharField(max_length=40, verbose_name='Email')
    Web = models.CharField(max_length=40, verbose_name='Site Web')
    Telephone = models.CharField(max_length=20, verbose_name='Téléphone Fixe')
    Fax = models.CharField(max_length=20, verbose_name='Fax')
    SIREN = models.BigIntegerField(verbose_name='N° SIREN')
    SIRET = models.BigIntegerField(verbose_name='N° SIRET')
    NAF_APE = models.CharField(max_length=5, verbose_name='Code NAF-APE')
    RCS = models.CharField(max_length = 30, verbose_name='Code RCS')
    CHOIX_TVA = models.CharField(max_length = 30, choices=CHOIX_TVA, verbose_name='Assujeti à la TVA')
    TVA = models.CharField(max_length=13, verbose_name='N° TVA Intracommunautaire')
    Type = models.CharField(max_length = 30, choices = CHOIX_SOCIETE, verbose_name = 'Type de Société')
    Effectif = models.CharField(max_length = 30, choices = CHOIX_EFFECTIF, verbose_name = 'Effectif')
    Capital = models.IntegerField(verbose_name = 'Capital de la Société (euros)')
    Creation = models.DateTimeField(auto_now_add=True)
    InformationsInstitution = models.CharField(max_length=30, null=False, verbose_name='Informations Institution')
    Utilisateur = models.CharField(max_length=100, null=False, verbose_name="Utilisateur", default=" ")

    def save(self, *args, **kwargs):
        for field_name in ['Nom', 'Ville', 'Region']:
            val = getattr(self, field_name, False)
            if val:
                setattr(self, field_name, val.upper())

        super(Societe, self).save(*args, **kwargs)

class SocieteContrat(models.Model):

    Societe = models.ForeignKey(Societe, related_name="Societe", verbose_name="Société")
    PointsTotal = models.FloatField(verbose_name="Nombre points total")
    PointsRestant = models.FloatField(verbose_name="Nombre points restants", null=True)

    def __unicode__(self):
        return unicode (self.id, self.Societe, self.PointsTotal, self.PointsRestant)

class SocieteIntervention(models.Model):

    Societe = models.ForeignKey(Societe, related_name="Societe1", verbose_name="Société")
    Date = models.DateField(verbose_name="Date de l'Intervention")
    Temps = models.IntegerField(verbose_name="Durée Intervention (min)")
    Description = models.CharField(max_length=200, verbose_name="Description")
    Niveau = models.CharField(max_length = 30, choices = CHOIX_NIVEAU, verbose_name = 'Niveau Intervention/Intervenant')
    PointsConsommes = models.FloatField(verbose_name=u"Nombre points consommés", null=True)

class CoefficientIntervention(models.Model):

    Technicien = models.FloatField(verbose_name="Coefficient Technicien")
    Ingenieur = models.FloatField(verbose_name="Coefficient Ingénieur")
    Consultant = models.FloatField(verbose_name="Coefficient Consultant")
    Architecte = models.FloatField(verbose_name="Coefficient Architecte")

    def __unicode__(self):
        return unicode (self.id, self.Technicien, self.Ingenieur, self.Consultant, self.Architecte)
</code>```

My objective is : Create service contracts with a number of points. Points are deducted according to a coefficient. This coefficient depending on your status : Technician, Engineer, ...

I create this function in my view :

```<code>@login_required
def Identity_Contrat(request, id) :

    societe = get_object_or_404(Societe, pk=id)
    contrat = get_object_or_404(SocieteContrat, pk=id)
    coefficient = CoefficientIntervention.objects.last()

    if request.method == 'POST':

        form = InterventionFormulaire(request.POST or None)

        if form.is_valid() :
            post = form.save()

            Liste_Intervention = SocieteIntervention.objects.filter(Societe__id=id).values_list("Temps")
            Value = Liste_Intervention.last()[0]

            Type_Intervention = SocieteIntervention.objects.filter(Societe__id=id).values_list("Niveau")

            if Type_Intervention.last() == (u'Ing\xe9nieur',) :
                Consomme = Value * coefficient.Ingenieur

            elif Type_Intervention.last() == ('Technicien',) :
                Consomme = Value * coefficient.Technicien

            elif Type_Intervention.last() == ('Consultant',) :
                Consomme = Value * coefficient.Consultant

            elif Type_Intervention.last() == ('Architecte',) :
                Consomme = Value * coefficient.Architecte

            PointsConsommes = SocieteIntervention.objects.latest('id').update(PointsConsommes=Consomme)

            messages.success(request, 'Le formulaire a été enregistré !')
            return HttpResponseRedirect('http://localhost:8000/Identity/Contrat/Societe/'+id)

        else:
            messages.error(request, "Le formulaire est invalide !")

    else:
        form = InterventionFormulaire()

    context = {
        "coefficient" : coefficient,
        "societe" : societe,
        "contrat" : contrat,
        "form" : form,
    }

    return render(request, 'Identity_Societe_Contrat.html', context)
</code>```

I fill the form, I save it with PointsConsommes == NULL,then I'm trying to update it with the value calculated previously.

How I can update the field PointsConsommes when the form is saved ? I don't overcome to update it with .update.

答:
You can try to use update_fields:

```<code>PointsConsommes = SocieteIntervention.objects.latest('id')
PointsConsommes.PointsConsommes = Consomme
PointsConsommes.save(update_fields=['PointsConsommes'])
</code>```

Body:
I'm trying to create a new function but I'm getting this Django error :

'SocieteIntervention' object has no attribute 'update'

I have several models in my application :

class Societe(models.Model):

    Nom = models.CharField(null= False, max_length=30, verbose_name='Nom de Société')
    Etat = models.CharField(max_length = 30, choices = CHOIX_ETAT_SOCIETE, null=False, verbose_name="Etat")
    Adresse = models.CharField(max_length=30, verbose_name='Adresse')
    Ville = models.CharField(max_length=30, verbose_name='Ville')
    Zip = models.IntegerField(verbose_name='Code Postal')
    Region = models.CharField(max_length=30, verbose_name='Région')
    Pays = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays')
    Mail = models.CharField(max_length=40, verbose_name='Email')
    Web = models.CharField(max_length=40, verbose_name='Site Web')
    Telephone = models.CharField(max_length=20, verbose_name='Téléphone Fixe')
    Fax = models.CharField(max_length=20, verbose_name='Fax')
    SIREN = models.BigIntegerField(verbose_name='N° SIREN')
    SIRET = models.BigIntegerField(verbose_name='N° SIRET')
    NAF_APE = models.CharField(max_length=5, verbose_name='Code NAF-APE')
    RCS = models.CharField(max_length = 30, verbose_name='Code RCS')
    CHOIX_TVA = models.CharField(max_length = 30, choices=CHOIX_TVA, verbose_name='Assujeti à la TVA')
    TVA = models.CharField(max_length=13, verbose_name='N° TVA Intracommunautaire')
    Type = models.CharField(max_length = 30, choices = CHOIX_SOCIETE, verbose_name = 'Type de Société')
    Effectif = models.CharField(max_length = 30, choices = CHOIX_EFFECTIF, verbose_name = 'Effectif')
    Capital = models.IntegerField(verbose_name = 'Capital de la Société (euros)')
    Creation = models.DateTimeField(auto_now_add=True)
    InformationsInstitution = models.CharField(max_length=30, null=False, verbose_name='Informations Institution')
    Utilisateur = models.CharField(max_length=100, null=False, verbose_name="Utilisateur", default=" ")

    def save(self, *args, **kwargs):
        for field_name in ['Nom', 'Ville', 'Region']:
            val = getattr(self, field_name, False)
            if val:
                setattr(self, field_name, val.upper())

        super(Societe, self).save(*args, **kwargs)

class SocieteContrat(models.Model):

    Societe = models.ForeignKey(Societe, related_name="Societe", verbose_name="Société")
    PointsTotal = models.FloatField(verbose_name="Nombre points total")
    PointsRestant = models.FloatField(verbose_name="Nombre points restants", null=True)

    def __unicode__(self):
        return unicode (self.id, self.Societe, self.PointsTotal, self.PointsRestant)

class SocieteIntervention(models.Model):

    Societe = models.ForeignKey(Societe, related_name="Societe1", verbose_name="Société")
    Date = models.DateField(verbose_name="Date de l'Intervention")
    Temps = models.IntegerField(verbose_name="Durée Intervention (min)")
    Description = models.CharField(max_length=200, verbose_name="Description")
    Niveau = models.CharField(max_length = 30, choices = CHOIX_NIVEAU, verbose_name = 'Niveau Intervention/Intervenant')
    PointsConsommes = models.FloatField(verbose_name=u"Nombre points consommés", null=True)

class CoefficientIntervention(models.Model):

    Technicien = models.FloatField(verbose_name="Coefficient Technicien")
    Ingenieur = models.FloatField(verbose_name="Coefficient Ingénieur")
    Consultant = models.FloatField(verbose_name="Coefficient Consultant")
    Architecte = models.FloatField(verbose_name="Coefficient Architecte")

    def __unicode__(self):
        return unicode (self.id, self.Technicien, self.Ingenieur, self.Consultant, self.Architecte)

My objective is : Create service contracts with a number of points. Points are deducted according to a coefficient. This coefficient depending on your status : Technician, Engineer, ...

I create this function in my view :

@login_required
def Identity_Contrat(request, id) :

    societe = get_object_or_404(Societe, pk=id)
    contrat = get_object_or_404(SocieteContrat, pk=id)
    coefficient = CoefficientIntervention.objects.last()

    if request.method == 'POST':

        form = InterventionFormulaire(request.POST or None)

        if form.is_valid() :
            post = form.save()

            Liste_Intervention = SocieteIntervention.objects.filter(Societe__id=id).values_list("Temps")
            Value = Liste_Intervention.last()[0]

            Type_Intervention = SocieteIntervention.objects.filter(Societe__id=id).values_list("Niveau")

            if Type_Intervention.last() == (u'Ing\xe9nieur',) :
                Consomme = Value * coefficient.Ingenieur

            elif Type_Intervention.last() == ('Technicien',) :
                Consomme = Value * coefficient.Technicien

            elif Type_Intervention.last() == ('Consultant',) :
                Consomme = Value * coefficient.Consultant

            elif Type_Intervention.last() == ('Architecte',) :
                Consomme = Value * coefficient.Architecte

            PointsConsommes = SocieteIntervention.objects.latest('id').update(PointsConsommes=Consomme)

            messages.success(request, 'Le formulaire a été enregistré !')
            return HttpResponseRedirect('http://localhost:8000/Identity/Contrat/Societe/'+id)

        else:
            messages.error(request, "Le formulaire est invalide !")

    else:
        form = InterventionFormulaire()

    context = {
        "coefficient" : coefficient,
        "societe" : societe,
        "contrat" : contrat,
        "form" : form,
    }

    return render(request, 'Identity_Societe_Contrat.html', context)

I fill the form, I save it with PointsConsommes == NULL,then I'm trying to update it with the value calculated previously.

How I can update the field PointsConsommes when the form is saved ? I don't overcome to update it with .update.

Body:
You can try to use update_fields:

PointsConsommes = SocieteIntervention.objects.latest('id')
PointsConsommes.PointsConsommes = Consomme
PointsConsommes.save(update_fields=['PointsConsommes'])


问:
Does facebook support oEmbed?
Anyone know whether Facebook supports oEmbed for embedding videos (or other media) when a link is shared. I googled but cant get a definitive answer for this.

My question Facebook developer forum has no answer. http://forum.developers.facebook.net/viewtopic.php?pid=334549

答: Yes it does, but has few hiccups when implementing. I'd recommend you to try solution I wrote to overcome this: https://shobhitsharma.github.io/embedo </p>

Title: Does facebook support oEmbed?


问:
Facebook PHP SDK problem with getLoginUrl()
I am having a trouble with PHP SDK logging in using getLoginUrl(). when the user click the link generated by that function it does not show the permission dialog instead it shows a facebook logo you must click it before showing the permission  dialog please help me!</p>

答: Facebook does not allow the user to login via an iframe, as with most oAuth.</p>


问:
SQL SERVER 2008. How to select one row only based on dates
```<code>Select MIN([appdate]), CustID, CustAtt, Surname, Firstname, itemType
From table
Where appDate > (getdate())
Group by CustID, CustAtt

CustAtt CustID  Surname Firstname   appDate      itemType
 53247   20675    A        AX
 49535   12/FX08  B        BX      14/08/2017     solid
 70433   400039   C        CX
 67119   413555   D        DX
 51406   27/EY07  E        EX      14/07/2017     Liquid
 51406   27/EY08  E        EX      13/09/2017     Gas
 51406   27/EY09  E        EX      11/12/2017     Solid A
 51406   27/EY10  E        EX      06/06/2018     Liquid A
 82820   410053   F        FX
 52395   29/FA72  G        GX      25/09/2017     Gas A
 89488   414282   H        HX
 55855   412799   I        IX      30/08/2017     Solid
 55855   412799   I        IX      21/08/2017     Liquid
 53248   16/EK15  J        JX      06/07/2017     Gas
 53248   16/EK15  J        JX      17/07/2017     Solid B
 89835   911528   K        KX      08/05/2018     Solid B
</code>```

The above is a snippet of my output from the above script,  but isn't giving me the desired output. I want to only select one row for each CustID & CustAtt from my dataset based on the appdate column.

The desired output should include the next earliest date from current date, in the case the dates are the same any given row is acceptable:
The output table should yield:

```<code>CustAtt CustID  Surname Firstname   appDate      itemType
 53247   20675    A        AX
 49535   12/FX08  B        BX      14/08/2017     solid
 70433   400039   C        CX
 67119   413555   D        DX
 51406   27/EY07  E        EX      14/07/2017     Liquid
 82820   410053   F        FX
 52395   29/FA72  G        GX      25/09/2017     Gas A
 89488   414282   H        HX
 55855   412799   I        IX      21/08/2017     Liquid
 53248   16/EK15  J        JX      06/07/2017     Gas
 89835   911528   K        KX      08/05/2018     Solid B
</code>```

答:
Example: http://sqlfiddle.com/#!6/c35e2/1</p>

```<code>create table t(
    id int,
    x int,
    y int,
    z int,
    a int,
    b int,
    c datetime
);

-- Build t table
INSERT INTO t values
(1, 1, 2, 3, 4, 5, getdate()),
(2, 1, 2, 3, 4, 5, dateadd(hh,+3,getdate())),
(3, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate())),
(4, 1, 2, 3, 4, 5, dateadd(hh,+2,getdate())),
(5, 1, 2, 3, 4, 5, dateadd(hh,-2,getdate())),
(6, 1, 2, 3, 4, 5, dateadd(hh,-1,getdate())),
(7, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate())),
(8, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate())),
(9, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate()));

select top 1 t.id, s.*, t.c
from t
join (
    select x,y,z,a,b
    from t
    group by x,y,z,a,b
    having count(*) > 1
) s
on s.x = t.x
    and s.y = t.y
    and s.z = t.z
    and s.a = t.a
    and s.b = t.b
    and (getdate() < t.c)
order by t.c
</code>```

Body:
Select MIN([appdate]), CustID, CustAtt, Surname, Firstname, itemType
From table
Where appDate > (getdate())
Group by CustID, CustAtt

CustAtt CustID  Surname Firstname   appDate      itemType
 53247   20675    A        AX
 49535   12/FX08  B        BX      14/08/2017     solid
 70433   400039   C        CX
 67119   413555   D        DX
 51406   27/EY07  E        EX      14/07/2017     Liquid
 51406   27/EY08  E        EX      13/09/2017     Gas
 51406   27/EY09  E        EX      11/12/2017     Solid A
 51406   27/EY10  E        EX      06/06/2018     Liquid A
 82820   410053   F        FX
 52395   29/FA72  G        GX      25/09/2017     Gas A
 89488   414282   H        HX
 55855   412799   I        IX      30/08/2017     Solid
 55855   412799   I        IX      21/08/2017     Liquid
 53248   16/EK15  J        JX      06/07/2017     Gas
 53248   16/EK15  J        JX      17/07/2017     Solid B
 89835   911528   K        KX      08/05/2018     Solid B

The above is a snippet of my output from the above script,  but isn't giving me the desired output. I want to only select one row for each CustID & CustAtt from my dataset based on the appdate column.

The desired output should include the next earliest date from current date, in the case the dates are the same any given row is acceptable:
The output table should yield:

CustAtt CustID  Surname Firstname   appDate      itemType
 53247   20675    A        AX
 49535   12/FX08  B        BX      14/08/2017     solid
 70433   400039   C        CX
 67119   413555   D        DX
 51406   27/EY07  E        EX      14/07/2017     Liquid
 82820   410053   F        FX
 52395   29/FA72  G        GX      25/09/2017     Gas A
 89488   414282   H        HX
 55855   412799   I        IX      21/08/2017     Liquid
 53248   16/EK15  J        JX      06/07/2017     Gas
 89835   911528   K        KX      08/05/2018     Solid B

Body:
Example: http://sqlfiddle.com/#!6/c35e2/1

create table t(
    id int,
    x int,
    y int,
    z int,
    a int,
    b int,
    c datetime
);

-- Build t table
INSERT INTO t values
(1, 1, 2, 3, 4, 5, getdate()),
(2, 1, 2, 3, 4, 5, dateadd(hh,+3,getdate())),
(3, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate())),
(4, 1, 2, 3, 4, 5, dateadd(hh,+2,getdate())),
(5, 1, 2, 3, 4, 5, dateadd(hh,-2,getdate())),
(6, 1, 2, 3, 4, 5, dateadd(hh,-1,getdate())),
(7, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate())),
(8, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate())),
(9, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate()));

select top 1 t.id, s.*, t.c
from t
join (
    select x,y,z,a,b
    from t
    group by x,y,z,a,b
    having count(*) > 1
) s
on s.x = t.x
    and s.y = t.y
    and s.z = t.z
    and s.a = t.a
    and s.b = t.b
    and (getdate() < t.c)
order by t.c


问:
com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/iid/zzc.class
I am making an app in which can edit photos and videos.It also shares edited photos via timeline which is made using Recycler view and Card view.

I am having an error whenever I try to run my app in Android SDK 22 but it is working file in Android SDK 23 and above.

Execution failed for task ':app:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/iid/zzc.class

It occurs also I am building apk.

Gradle File for my app

```<code> apply plugin: 'com.android.application'
 apply plugin: 'me.tatarka.retrolambda'

android {

     compileSdkVersion 25
     buildToolsVersion '25.0.3'
     defaultConfig {
     applicationId "com.practice.android.moments"
    minSdkVersion 18
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    manifestPlaceholders = [appPackageName: "${applicationId}"]
}

buildTypes {

    release {

        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

dexOptions {

    jumboMode true
}
 compileOptions {

    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

/* 3)(Creative SDK) Exclude duplicate licenses */

packagingOptions {
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/LICENSE'
    //help
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/DEPENDENCIES'
    pickFirst 'AndroidManifest.xml'
}
}

repositories {
mavenCentral()
}
dependencies {

compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.google.android.gms:play-services-auth:11.0.1'
compile 'com.google.firebase:firebase-core:11.0.1'
compile 'com.google.firebase:firebase-messaging:11.0.1'
compile 'com.google.firebase:firebase-auth:11.0.1'
compile 'com.google.firebase:firebase-database:11.0.1'
compile 'com.google.firebase:firebase-storage:11.0.1'
compile 'com.google.firebase:firebase-ads:11.0.1'
compile 'com.google.firebase:firebase-invites:11.0.1'
compile 'com.google.firebase:firebase-appindexing:11.0.1'
compile 'com.google.firebase:firebase-crash:11.0.1'

compile ('com.facebook.android:audience-network-sdk:4.11.0'){

    exclude group: 'com.google.android.gms'

}

compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.android.support:multidex:1.0.1'

compile 'com.adobe.creativesdk.foundation:auth:0.9.1251'
compile 'com.adobe.creativesdk:image:4.8.4'
compile 'com.localytics.android:library:3.8.0'

testCompile 'junit:junit:4.12'}

configurations.all {

resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1'}

apply plugin: 'com.google.gms.google-services'
</code>```

Can any one please help me...

Phone used for testing

Meizu M2 Note        OS version 5.1       Lollipop          API 22

Redmi Note 3         OS version 6.0.1     Marshmallow       API 23

Samsung Note 5       OS version 7.0       Nougat            API 24

答:
In my case,this error occurs because I have two different version of google-play-service lib.
I remove one of them,bingo!
Try move this compile
    compile 'com.google.android.gms:play-services-auth:11.0.1'</p>

Body:
I am making an app in which can edit photos and videos.It also shares edited photos via timeline which is made using Recycler view and Card view.

I am having an error whenever I try to run my app in Android SDK 22 but it is working file in Android SDK 23 and above.

Execution failed for task ':app:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/iid/zzc.class

It occurs also I am building apk.

Gradle File for my app

 apply plugin: 'com.android.application'
 apply plugin: 'me.tatarka.retrolambda'

android {

     compileSdkVersion 25
     buildToolsVersion '25.0.3'
     defaultConfig {
     applicationId "com.practice.android.moments"
    minSdkVersion 18
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    manifestPlaceholders = [appPackageName: "${applicationId}"]
}

buildTypes {

    release {

        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

dexOptions {

    jumboMode true
}
 compileOptions {

    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

/* 3)(Creative SDK) Exclude duplicate licenses */

packagingOptions {
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/LICENSE'
    //help
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/DEPENDENCIES'
    pickFirst 'AndroidManifest.xml'
}
}

repositories {
mavenCentral()
}
dependencies {

compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.google.android.gms:play-services-auth:11.0.1'
compile 'com.google.firebase:firebase-core:11.0.1'
compile 'com.google.firebase:firebase-messaging:11.0.1'
compile 'com.google.firebase:firebase-auth:11.0.1'
compile 'com.google.firebase:firebase-database:11.0.1'
compile 'com.google.firebase:firebase-storage:11.0.1'
compile 'com.google.firebase:firebase-ads:11.0.1'
compile 'com.google.firebase:firebase-invites:11.0.1'
compile 'com.google.firebase:firebase-appindexing:11.0.1'
compile 'com.google.firebase:firebase-crash:11.0.1'

compile ('com.facebook.android:audience-network-sdk:4.11.0'){

    exclude group: 'com.google.android.gms'

}

compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.android.support:multidex:1.0.1'

compile 'com.adobe.creativesdk.foundation:auth:0.9.1251'
compile 'com.adobe.creativesdk:image:4.8.4'
compile 'com.localytics.android:library:3.8.0'

testCompile 'junit:junit:4.12'}

configurations.all {

resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1'}

apply plugin: 'com.google.gms.google-services'

Can any one please help me...

Phone used for testing

Meizu M2 Note        OS version 5.1       Lollipop          API 22

Redmi Note 3         OS version 6.0.1     Marshmallow       API 23

Samsung Note 5       OS version 7.0       Nougat            API 24


问:
Tap Gesture on List View Items
I am trying to open another view after tapping on an item in the list view.
I have tried adding a TapGestureRegonizer and even adding ViewCell with grids etc. None of these seem to work. I have added a tap gesture to a label and that seemed to work but the same does not work for list view items. This seems like a simple problem for something like list view, but there doesnt seem to be a built in functionality for this.

The Xaml:

```<code><ListView x:Name="dataList"
      ItemsSource="{Binding routeLabels}"
      HasUnevenRows="True"
      Grid.Row="1"
      Grid.Column="0"
      Grid.ColumnSpan="3">
</ListView>
</code>```

The code behind:

```<code>var listviewgesture = new TapGestureRecognizer();
listviewgesture.SetBinding(TapGestureRecognizer.CommandProperty,"LoadRoutePage");
dataList.GestureRecognizers.Add(listviewgesture);
</code>```

The view model:

```<code>public ICommand LoadRoutePage { get; protected set; }

public DriverDashboardViewModel(INavigation navigation,MessagDatabase database)
    {
        this._database = database;
        this.Navigation = navigation;
        this.LoadNotifications = new Command(async () => await OpenNotificationsPage());
        this.LoadRoutePage = new Command(async () => await OpenRoutePage());

    }

public async Task OpenRoutePage()
    {

        await Navigation.PushAsync(new RoutePageView());
    }
</code>```

Just to be clear the LoadNotifications method does work in opening a page but LoadRoutePage does not. So I know there is some level of communication between the view and viewmodel.

答:
Not sure if I understand you correctly but you are trying to get an event going when someone taps on anelement of a listview?

If so you don't need a recognizer you simply have to add ItemTapped in your XAML:

```<code><ListView x:Name="dataList"
      ItemsSource="{Binding routeLabels}"
      HasUnevenRows="True"
      Grid.Row="1"
      Grid.Column="0"
      ItemTapped="Name of event"
      Grid.ColumnSpan="3">
</ListView>
</code>```

This will generate an event for you ( just do double tab when creating the ItemTapped ) and here you can place your code

Title: Tap Gesture on List View Items

Body:
I am trying to open another view after tapping on an item in the list view.
I have tried adding a TapGestureRegonizer and even adding ViewCell with grids etc. None of these seem to work. I have added a tap gesture to a label and that seemed to work but the same does not work for list view items. This seems like a simple problem for something like list view, but there doesnt seem to be a built in functionality for this.

The Xaml:

<ListView x:Name="dataList"
      ItemsSource="{Binding routeLabels}"
      HasUnevenRows="True"
      Grid.Row="1"
      Grid.Column="0"
      Grid.ColumnSpan="3">
</ListView>

The code behind:

var listviewgesture = new TapGestureRecognizer();
listviewgesture.SetBinding(TapGestureRecognizer.CommandProperty,"LoadRoutePage");
dataList.GestureRecognizers.Add(listviewgesture);

The view model:

public ICommand LoadRoutePage { get; protected set; }

public DriverDashboardViewModel(INavigation navigation,MessagDatabase database)
    {
        this._database = database;
        this.Navigation = navigation;
        this.LoadNotifications = new Command(async () => await OpenNotificationsPage());
        this.LoadRoutePage = new Command(async () => await OpenRoutePage());

    }

public async Task OpenRoutePage()
    {

        await Navigation.PushAsync(new RoutePageView());
    }

Just to be clear the LoadNotifications method does work in opening a page but LoadRoutePage does not. So I know there is some level of communication between the view and viewmodel.

Body:
Not sure if I understand you correctly but you are trying to get an event going when someone taps on anelement of a listview?

If so you don't need a recognizer you simply have to add ItemTapped in your XAML:

<ListView x:Name="dataList"
      ItemsSource="{Binding routeLabels}"
      HasUnevenRows="True"
      Grid.Row="1"
      Grid.Column="0"
      ItemTapped="Name of event"
      Grid.ColumnSpan="3">
</ListView>

This will generate an event for you ( just do double tab when creating the ItemTapped ) and here you can place your code


问:
React Router 4 / path-to-regexp multiple optional segments
In React router 3 I could have path like this:

```<code>/root(/id/:id)(/di/:di)
</code>```

That would match

```<code>/root
/root/id/1
/root/di/2
/root/id/1/di/2
</code>```

Perfect.

I can't figure out how to do it in React Router 4. All examples are doing only one thing.

Using Express Route tester I can come up with a route like

```<code>/root/id/:id?/di/:di?
</code>```

But that would match only

```<code>/root/id/1/di/2
</code>```

Is there a solution for this?

答:
In react router v4 you can enclose your regex inside (). So this regex should work and match all the paths you gave : /root(/id/|/di/):id*(/id/|/di/)?:di*. In the Express router Tester tool that you gave the link to, the keys wont show up with this regex but it does work, I tested on localhost and keys works just fine.

Note that I didn't use ? after first capturing group, i.e., (/id/|/di/) because if I did then it would become optional and then path like /root/12 would be matched too.

Body:
In React router 3 I could have path like this:

/root(/id/:id)(/di/:di)

That would match

/root
/root/id/1
/root/di/2
/root/id/1/di/2

Perfect.

I can't figure out how to do it in React Router 4. All examples are doing only one thing.

Using Express Route tester I can come up with a route like

/root/id/:id?/di/:di?

But that would match only

/root/id/1/di/2

Is there a solution for this?


问:
Problems with SQLite database, error when creating
i got this error when i start my app:

12-20 22:27:01.447: ERROR/Database(716): Failure 1 (near ":00": syntax error) on 0x1a4338 when preparing 'CREATE TABLE permission ( fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, validated tinyint(4) default 0, hour1 time default 08:00:00, hour2 time default 20:00:00, date1 date default NULL, date2 date default NULL, weekend tinyint(4) default 0, fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))'.

here is the code where i am creating the database:

```<code>private static final String PERMISSION_TABLE_CREATE =
"CREATE TABLE permission ("
"fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, "
"validated tinyint(4) default 0, hour1 time default 08:00:00, "
"hour2 time default 20:00:00, date1 date default NULL, "
"date2 date default NULL, weekend tinyint(4) default 0, "
"fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))";

private static final String USER_TABLE_CREATE = "CREATE TABLE user ( "
"email varchar(100) NOT NULL, password varchar(45) default NULL, "
"fullName varchar(80) default NULL, "
"mobilePhone varchar(14) default NULL, "
"mobileOperatingSystem varchar(20) default NULL, PRIMARY KEY  (email))";
</code>```

what i am doing bad?

答:
Check the SQLLite documentation.  I don't believe it has a type affinity for the "TIME" datatype.  If it does, the defaults will probably have to be in quotes.

SQLite is very funny about datatypes (essentially, all data is untyped) and you can substantially shorten your DDL by getting rid of VARCHAR lengths (or even VARCHAR in favor of TEXT).

Body:
i got this error when i start my app:

12-20 22:27:01.447: ERROR/Database(716): Failure 1 (near ":00": syntax error) on 0x1a4338 when preparing 'CREATE TABLE permission ( fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, validated tinyint(4) default 0, hour1 time default 08:00:00, hour2 time default 20:00:00, date1 date default NULL, date2 date default NULL, weekend tinyint(4) default 0, fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))'.

here is the code where i am creating the database:

private static final String PERMISSION_TABLE_CREATE =
"CREATE TABLE permission ("
"fk_email1 varchar(100) NOT NULL, fk_email2 varchar(100) NOT NULL, "
"validated tinyint(4) default 0, hour1 time default 08:00:00, "
"hour2 time default 20:00:00, date1 date default NULL, "
"date2 date default NULL, weekend tinyint(4) default 0, "
"fk_type varchar(45) default NULL, PRIMARY KEY  (fk_email1,fk_email2))";

private static final String USER_TABLE_CREATE = "CREATE TABLE user ( "
"email varchar(100) NOT NULL, password varchar(45) default NULL, "
"fullName varchar(80) default NULL, "
"mobilePhone varchar(14) default NULL, "
"mobileOperatingSystem varchar(20) default NULL, PRIMARY KEY  (email))";

what i am doing bad?


问:
Javaparser: Curly braces for one-line blocks?
I am using Javaparser to parse/write source code.

I noticed that if I create an IfStmt with a one-line thenStmt, then the toString method does not use curly braces to enclose the block. This makes the output source code hard to read because everything is put on one line as seen below.

```<code>if (cond) thenStmt; else elseStmt;
</code>```

Is there a way to enable curly braces for one-line if-blocks?
So the toString method would instead output:

```<code>if (cond) {
  thenStmt;
} else {
  elseStmt;
}
</code>```

答: You want to wrap your thenStmt in a BlockStmt. The BlockStmt will supply the braces.

Body:
I am using Javaparser to parse/write source code.

I noticed that if I create an IfStmt with a one-line thenStmt, then the toString method does not use curly braces to enclose the block. This makes the output source code hard to read because everything is put on one line as seen below.

if (cond) thenStmt; else elseStmt;

Is there a way to enable curly braces for one-line if-blocks?
So the toString method would instead output:

if (cond) {
  thenStmt;
} else {
  elseStmt;
}


问:
Scala return variable type after future is complete Add Comment Collapse
I've got a problem with returning a list after handling futures in scala. My code looks like this:

```<code>def getElements(arrayOfIds: Future[Seq[Int]]): Future[Seq[Element]] = {
    var elementArray: Seq[Element] = Seq()

    arrayOfIds.map {
      ids => ids.map(id => dto.getElementById(id).map {
                    case Some(element) => elementArray = elementArray :+ element
                    case None => println("Element not found")
                  })
    }
    arrayOfIds.onComplete(_ => elementArray)
  }
</code>```

I'd like to do something like .onComplete, however the return type is
 Unit and I'd like to return a Future[Seq[Whatever]]. Is there clean way to handle futures like this? Thanks!

答:
Instead of assigning the result to a mutable variable, return it from the continuation of the Future. You can use flatMap to extract only the Element results which actually contain a value:

```<code>def getElements(arrayOfIds: Future[Seq[Int]]): Future[Seq[Element]] = {
  arrayOfIds.flatMap(id => Future.fold(id.map(getElementById))(Seq.empty[Element])(_ ++ _))
}
</code>```

Body:
I've got a problem with returning a list after handling futures in scala. My code looks like this:

def getElements(arrayOfIds: Future[Seq[Int]]): Future[Seq[Element]] = {
    var elementArray: Seq[Element] = Seq()

    arrayOfIds.map {
      ids => ids.map(id => dto.getElementById(id).map {
                    case Some(element) => elementArray = elementArray :+ element
                    case None => println("Element not found")
                  })
    }
    arrayOfIds.onComplete(_ => elementArray)
  }

I'd like to do something like .onComplete, however the return type is
 Unit and I'd like to return a Future[Seq[Whatever]]. Is there clean way to handle futures like this? Thanks!

Body:
Instead of assigning the result to a mutable variable, return it from the continuation of the Future. You can use flatMap to extract only the Element results which actually contain a value:

def getElements(arrayOfIds: Future[Seq[Int]]): Future[Seq[Element]] = {
  arrayOfIds.flatMap(id => Future.fold(id.map(getElementById))(Seq.empty[Element])(_ ++ _))
}


问:
Can I generate Toast with a static method used in many Activities?
I created a class to generate Toast. I want it because I need to cancel a previous Toast when I'm showing a new one.

My doubt is that in my class I have

a static method

a Toast static class field

and, at the same time,  I'm passing the static method different Context, depending on the Activity in which I call the static method:ToastUtility.generateToast(activity_context, "message", Toast.LENGTH_LONG);

This is the class:

```<code>public class ToastUtility {

    private static Toast myToast;

    public static void generateToast(Context context, String message, int duration){
        if(myToast != null)myToast.cancel();
        myToast = Toast.makeText(context, message, duration);
        myToast.show();
    }
}
</code>```

I'm afraid, I didn't think about some problems that may occur when using  static method and field but different Context.

Thank you in advance.

答:
Yes you can use this statement in your activity as:

```<code> Utils.showToast(this, "" + model.getMessage());
</code>```

and in Utils class you can create a method like:

```<code>public static void showToast(Activity activity, String message) {
        Toast toast = Toast.makeText(activity, message, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM, 0, 0);
        toast.show();
    }
</code>```

Body:
I created a class to generate Toast. I want it because I need to cancel a previous Toast when I'm showing a new one.

My doubt is that in my class I have

a static method

a Toast static class field

and, at the same time,  I'm passing the static method different Context, depending on the Activity in which I call the static method:ToastUtility.generateToast(activity_context, "message", Toast.LENGTH_LONG);

This is the class:

public class ToastUtility {

    private static Toast myToast;

    public static void generateToast(Context context, String message, int duration){
        if(myToast != null)myToast.cancel();
        myToast = Toast.makeText(context, message, duration);
        myToast.show();
    }
}

I'm afraid, I didn't think about some problems that may occur when using  static method and field but different Context.

Thank you in advance.

Body:
Yes you can use this statement in your activity as:

 Utils.showToast(this, "" + model.getMessage());

and in Utils class you can create a method like:

public static void showToast(Activity activity, String message) {
        Toast toast = Toast.makeText(activity, message, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM, 0, 0);
        toast.show();
    }


问:
foreign key and mysql with hibernate
I am using Hibernate to create table in mySql database.
I have two table "conge" and "employee" and I have a manytoone relationship. the "conge" table have a foreign key of the employee id.

I notice that after inserting exactly two row in my table "conge" I get a foreign key problem. I have used hibernate and also the phpmyadmin to insert and I have always the same problem after inserting two row.

this is my error

Cannot add or update a child row: a foreign key constraint fails (concretepage.Conge, CONSTRAINT FKk1p9i6bbic92cgaad05k4smsg FOREIGN KEY (id) REFERENCES EMPLOYE (id))

Thanks,

Update
I have exported the database this is the sql file

```<code>-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Jul 06, 2017 at 11:50 AM
-- Server version: 10.1.24-MariaDB
-- PHP Version: 7.1.6

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `concretepage`
--

-- --------------------------------------------------------

--
-- Table structure for table `Conge`
--

CREATE TABLE `Conge` (
  `id` int(11) NOT NULL,
  `date` datetime DEFAULT CURRENT_TIMESTAMP,
  `dateDebut` date DEFAULT NULL,
  `dateFin` date DEFAULT NULL,
  `numero` int(11) NOT NULL,
  `status` varchar(255) DEFAULT NULL,
  `employe_id` int(11) DEFAULT NULL,
  `typeConge_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `Conge`
--

INSERT INTO `Conge` (`id`, `date`, `dateDebut`, `dateFin`, `numero`, `status`, `employe_id`, `typeConge_id`) VALUES
(1, '2017-07-06 10:46:30', NULL, NULL, 0, NULL, NULL, NULL),
(2, '2017-07-06 10:46:34', NULL, NULL, 0, NULL, NULL, NULL);

-- --------------------------------------------------------

--
-- Table structure for table `EMPLOYE`
--

CREATE TABLE `EMPLOYE` (
  `id` int(11) NOT NULL,
  `nom` varchar(255) DEFAULT NULL,
  `post_id` int(11) DEFAULT NULL,
  `userInfo_login` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `EMPLOYE`
--

INSERT INTO `EMPLOYE` (`id`, `nom`, `post_id`, `userInfo_login`) VALUES
(1, 'foulen', NULL, 'user'),
(2, 'falten', NULL, 'user');

-- --------------------------------------------------------

--
-- Table structure for table `POST`
--

CREATE TABLE `POST` (
  `id` int(11) NOT NULL,
  `code` varchar(255) DEFAULT NULL,
  `intituler` varchar(255) DEFAULT NULL,
  `employe_id` int(11) DEFAULT NULL,
  `id_superieur` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `TypeConge`
--

CREATE TABLE `TypeConge` (
  `id` int(11) NOT NULL,
  `code` int(11) NOT NULL,
  `intituler` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `TypeConge`
--

INSERT INTO `TypeConge` (`id`, `code`, `intituler`) VALUES
(1, 5757, 'Annuel'),
(2, 2, 'Maladie');

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `login` varchar(255) NOT NULL,
  `country` varchar(255) DEFAULT NULL,
  `enabled` smallint(6) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `role` varchar(255) DEFAULT NULL,
  `employe_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`login`, `country`, `enabled`, `password`, `role`, `employe_id`) VALUES
('admin', NULL, 1, '$2a$10$OlJFlkoM9/nCAK1DUhcE7OvitoDHDip8GuoDt5NrSqWgV5aP7tMeC', 'ROLE_ADMIN', NULL),
('user', NULL, 1, '$2a$10$OlJFlkoM9/nCAK1DUhcE7OvitoDHDip8GuoDt5NrSqWgV5aP7tMeC', 'ROLE_USER', 1);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `Conge`
--
ALTER TABLE `Conge`
  ADD PRIMARY KEY (`id`),
  ADD KEY `FKov9s99mmo220hv4d8ppeobut` (`employe_id`),
  ADD KEY `FKocvumeoahniu5uvsjlwq5mvnp` (`typeConge_id`);

--
-- Indexes for table `EMPLOYE`
--
ALTER TABLE `EMPLOYE`
  ADD PRIMARY KEY (`id`),
  ADD KEY `FKpe9llqbqsni2xqg1vms2h716j` (`post_id`),
  ADD KEY `FKioxxmg7s2j18x2fo7ahnclmcd` (`userInfo_login`);

--
-- Indexes for table `POST`
--
ALTER TABLE `POST`
  ADD PRIMARY KEY (`id`),
  ADD KEY `FKl6st4h0ujkdiun27r7tak7t7n` (`employe_id`),
  ADD KEY `FK3x5ro8omrg46k9jaihue19o8q` (`id_superieur`);

--
-- Indexes for table `TypeConge`
--
ALTER TABLE `TypeConge`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`login`),
  ADD KEY `FK82xfucsr861ymb3t5sp2hulo3` (`employe_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `Conge`
--
ALTER TABLE `Conge`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `EMPLOYE`
--
ALTER TABLE `EMPLOYE`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `POST`
--
ALTER TABLE `POST`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `TypeConge`
--
ALTER TABLE `TypeConge`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Constraints for dumped tables
--

--
-- Constraints for table `Conge`
--
ALTER TABLE `Conge`
  ADD CONSTRAINT `FKk1p9i6bbic92cgaad05k4smsg` FOREIGN KEY (`id`) REFERENCES `EMPLOYE` (`id`),
  ADD CONSTRAINT `FKlm34pn7fv5rcolnjgjyjnuj9l` FOREIGN KEY (`id`) REFERENCES `TypeConge` (`id`),
  ADD CONSTRAINT `FKocvumeoahniu5uvsjlwq5mvnp` FOREIGN KEY (`typeConge_id`) REFERENCES `TypeConge` (`id`),
  ADD CONSTRAINT `FKov9s99mmo220hv4d8ppeobut` FOREIGN KEY (`employe_id`) REFERENCES `EMPLOYE` (`id`);

--
-- Constraints for table `EMPLOYE`
--
ALTER TABLE `EMPLOYE`
  ADD CONSTRAINT `FKioxxmg7s2j18x2fo7ahnclmcd` FOREIGN KEY (`userInfo_login`) REFERENCES `users` (`login`),
  ADD CONSTRAINT `FKpe9llqbqsni2xqg1vms2h716j` FOREIGN KEY (`post_id`) REFERENCES `POST` (`id`);

--
-- Constraints for table `POST`
--
ALTER TABLE `POST`
  ADD CONSTRAINT `FK3x5ro8omrg46k9jaihue19o8q` FOREIGN KEY (`id_superieur`) REFERENCES `POST` (`id`),
  ADD CONSTRAINT `FKl6st4h0ujkdiun27r7tak7t7n` FOREIGN KEY (`employe_id`) REFERENCES `EMPLOYE` (`id`);

--
-- Constraints for table `users`
--
ALTER TABLE `users`
  ADD CONSTRAINT `FK82xfucsr861ymb3t5sp2hulo3` FOREIGN KEY (`employe_id`) REFERENCES `EMPLOYE` (`id`);
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
</code>```

答: Because the foreign key is on column ID not employee_id ... look :  FOREIGN KEY (id) REFERENCES EMPLOYE (id)) ... and you have only two rows in Employee table

Title: foreign key and mysql with hibernate

Body:
I am using Hibernate to create table in mySql database.
I have two table "conge" and "employee" and I have a manytoone relationship. the "conge" table have a foreign key of the employee id.

I notice that after inserting exactly two row in my table "conge" I get a foreign key problem. I have used hibernate and also the phpmyadmin to insert and I have always the same problem after inserting two row.

this is my error

Cannot add or update a child row: a foreign key constraint fails (concretepage.Conge, CONSTRAINT FKk1p9i6bbic92cgaad05k4smsg FOREIGN KEY (id) REFERENCES EMPLOYE (id))

Thanks,

Update
I have exported the database this is the sql file

-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Jul 06, 2017 at 11:50 AM
-- Server version: 10.1.24-MariaDB
-- PHP Version: 7.1.6

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `concretepage`
--

-- --------------------------------------------------------

--
-- Table structure for table `Conge`
--

CREATE TABLE `Conge` (
  `id` int(11) NOT NULL,
  `date` datetime DEFAULT CURRENT_TIMESTAMP,
  `dateDebut` date DEFAULT NULL,
  `dateFin` date DEFAULT NULL,
  `numero` int(11) NOT NULL,
  `status` varchar(255) DEFAULT NULL,
  `employe_id` int(11) DEFAULT NULL,
  `typeConge_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `Conge`
--

INSERT INTO `Conge` (`id`, `date`, `dateDebut`, `dateFin`, `numero`, `status`, `employe_id`, `typeConge_id`) VALUES
(1, '2017-07-06 10:46:30', NULL, NULL, 0, NULL, NULL, NULL),
(2, '2017-07-06 10:46:34', NULL, NULL, 0, NULL, NULL, NULL);

-- --------------------------------------------------------

--
-- Table structure for table `EMPLOYE`
--

CREATE TABLE `EMPLOYE` (
  `id` int(11) NOT NULL,
  `nom` varchar(255) DEFAULT NULL,
  `post_id` int(11) DEFAULT NULL,
  `userInfo_login` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `EMPLOYE`
--

INSERT INTO `EMPLOYE` (`id`, `nom`, `post_id`, `userInfo_login`) VALUES
(1, 'foulen', NULL, 'user'),
(2, 'falten', NULL, 'user');

-- --------------------------------------------------------

--
-- Table structure for table `POST`
--

CREATE TABLE `POST` (
  `id` int(11) NOT NULL,
  `code` varchar(255) DEFAULT NULL,
  `intituler` varchar(255) DEFAULT NULL,
  `employe_id` int(11) DEFAULT NULL,
  `id_superieur` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `TypeConge`
--

CREATE TABLE `TypeConge` (
  `id` int(11) NOT NULL,
  `code` int(11) NOT NULL,
  `intituler` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `TypeConge`
--

INSERT INTO `TypeConge` (`id`, `code`, `intituler`) VALUES
(1, 5757, 'Annuel'),
(2, 2, 'Maladie');

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `login` varchar(255) NOT NULL,
  `country` varchar(255) DEFAULT NULL,
  `enabled` smallint(6) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `role` varchar(255) DEFAULT NULL,
  `employe_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`login`, `country`, `enabled`, `password`, `role`, `employe_id`) VALUES
('admin', NULL, 1, '$2a$10$OlJFlkoM9/nCAK1DUhcE7OvitoDHDip8GuoDt5NrSqWgV5aP7tMeC', 'ROLE_ADMIN', NULL),
('user', NULL, 1, '$2a$10$OlJFlkoM9/nCAK1DUhcE7OvitoDHDip8GuoDt5NrSqWgV5aP7tMeC', 'ROLE_USER', 1);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `Conge`
--
ALTER TABLE `Conge`
  ADD PRIMARY KEY (`id`),
  ADD KEY `FKov9s99mmo220hv4d8ppeobut` (`employe_id`),
  ADD KEY `FKocvumeoahniu5uvsjlwq5mvnp` (`typeConge_id`);

--
-- Indexes for table `EMPLOYE`
--
ALTER TABLE `EMPLOYE`
  ADD PRIMARY KEY (`id`),
  ADD KEY `FKpe9llqbqsni2xqg1vms2h716j` (`post_id`),
  ADD KEY `FKioxxmg7s2j18x2fo7ahnclmcd` (`userInfo_login`);

--
-- Indexes for table `POST`
--
ALTER TABLE `POST`
  ADD PRIMARY KEY (`id`),
  ADD KEY `FKl6st4h0ujkdiun27r7tak7t7n` (`employe_id`),
  ADD KEY `FK3x5ro8omrg46k9jaihue19o8q` (`id_superieur`);

--
-- Indexes for table `TypeConge`
--
ALTER TABLE `TypeConge`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`login`),
  ADD KEY `FK82xfucsr861ymb3t5sp2hulo3` (`employe_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `Conge`
--
ALTER TABLE `Conge`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `EMPLOYE`
--
ALTER TABLE `EMPLOYE`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `POST`
--
ALTER TABLE `POST`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `TypeConge`
--
ALTER TABLE `TypeConge`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Constraints for dumped tables
--

--
-- Constraints for table `Conge`
--
ALTER TABLE `Conge`
  ADD CONSTRAINT `FKk1p9i6bbic92cgaad05k4smsg` FOREIGN KEY (`id`) REFERENCES `EMPLOYE` (`id`),
  ADD CONSTRAINT `FKlm34pn7fv5rcolnjgjyjnuj9l` FOREIGN KEY (`id`) REFERENCES `TypeConge` (`id`),
  ADD CONSTRAINT `FKocvumeoahniu5uvsjlwq5mvnp` FOREIGN KEY (`typeConge_id`) REFERENCES `TypeConge` (`id`),
  ADD CONSTRAINT `FKov9s99mmo220hv4d8ppeobut` FOREIGN KEY (`employe_id`) REFERENCES `EMPLOYE` (`id`);

--
-- Constraints for table `EMPLOYE`
--
ALTER TABLE `EMPLOYE`
  ADD CONSTRAINT `FKioxxmg7s2j18x2fo7ahnclmcd` FOREIGN KEY (`userInfo_login`) REFERENCES `users` (`login`),
  ADD CONSTRAINT `FKpe9llqbqsni2xqg1vms2h716j` FOREIGN KEY (`post_id`) REFERENCES `POST` (`id`);

--
-- Constraints for table `POST`
--
ALTER TABLE `POST`
  ADD CONSTRAINT `FK3x5ro8omrg46k9jaihue19o8q` FOREIGN KEY (`id_superieur`) REFERENCES `POST` (`id`),
  ADD CONSTRAINT `FKl6st4h0ujkdiun27r7tak7t7n` FOREIGN KEY (`employe_id`) REFERENCES `EMPLOYE` (`id`);

--
-- Constraints for table `users`
--
ALTER TABLE `users`
  ADD CONSTRAINT `FK82xfucsr861ymb3t5sp2hulo3` FOREIGN KEY (`employe_id`) REFERENCES `EMPLOYE` (`id`);
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


问:
GameKit, GKGameSession how to add players to the session and send data?
I created a session, shared it to another player and now I want to start a game.
I can see a session with two players on both devices. So, it looks like we're ready to game but I need to change connected status before the game and I can do this on both devices.

But... when I do this on device A, I see that user A is connected and user B isn't. And after that, when I repeat the process on device B, I see vice versa situation. B is connected and A is not.

Here is my code that connect player and send the data:

```<code>session.setConnectionState(.connected) { (error) in
   if let err = error {
      assertionFailure(err.localizedDescription)
   }
   else {

      print("NC:",session.players(with: .notConnected))
      print(" C:",session.players(with: .connected))

      let m = MoveTransfer(move:1) // test struct to send/receive data

      session.send(m.data(), with: .reliable) { (error) in
         if let err = error {
            assertionFailure(err.localizedDescription)
         }
      }
   }
}
</code>```

I'm getting error:

The requested operation could not be completed because there are no recipients connected to the session

By the way, I'm unable to change connected state on the simulator (iCloud is logged in).

I forgot to mention, that I'm working on a turn based game.

Edit

Tried again and now after several iterations I got this:

I have both players connected to session. But send data still doesn't work.

here is console output:

```<code>NC: [] // not connected array and connected array below
C: [<GKCloudPlayer: 0x17402e700>, id: playerID1, name: Player1,<GKCloudPlayer: 0x17402e900>, id: playerID2, name: Player2]

fatal error: The requested operation could not be completed because there are no recipients connected to the session.
</code>```

Got this on two real devices.

答:
I was able to send data and receive it on the other device. I used loadSessions function to load all session (I think that loadSession by id would do the trick too).
I did the following, D1 is a device 1 and D2 device 2:

```<code>1. D1: load all sessions and set player state to connected
2. D2: load all sessions and set player state to connected
3. D1: load all sessions again and set player state to connected
4. D1 || D2: send data
5. D2 || D1: data 256 bytes from player: <GKCloudPlayer: 0x1c022b380>, id: playerID, name: (null)
</code>```

Although, I wasn't able to transfer data back and forth on both devices since if we'll add step 6. that sends data from device that just received it, we'll get an error: The requested operation could not be completed because there are no recipients connected to the session.

I do not sure what is the reason of it but I stop my efforts on this stage, since I think now, that I don't need to be connected to session to play turn based game.

I found this "new" iOS 10 APIs abandoned. By Apple and by devs consequently. If you one of those who still trying to use it drop me a note at my twitter (link in my bio) if you want to discuss GKGameSession and related topics.

Body:
I created a session, shared it to another player and now I want to start a game.
I can see a session with two players on both devices. So, it looks like we're ready to game but I need to change connected status before the game and I can do this on both devices.

But... when I do this on device A, I see that user A is connected and user B isn't. And after that, when I repeat the process on device B, I see vice versa situation. B is connected and A is not.

Here is my code that connect player and send the data:

session.setConnectionState(.connected) { (error) in
   if let err = error {
      assertionFailure(err.localizedDescription)
   }
   else {

      print("NC:",session.players(with: .notConnected))
      print(" C:",session.players(with: .connected))

      let m = MoveTransfer(move:1) // test struct to send/receive data

      session.send(m.data(), with: .reliable) { (error) in
         if let err = error {
            assertionFailure(err.localizedDescription)
         }
      }
   }
}

I'm getting error:

The requested operation could not be completed because there are no recipients connected to the session

By the way, I'm unable to change connected state on the simulator (iCloud is logged in).

I forgot to mention, that I'm working on a turn based game.

Edit

Tried again and now after several iterations I got this:

I have both players connected to session. But send data still doesn't work.

here is console output:

NC: [] // not connected array and connected array below
C: [<GKCloudPlayer: 0x17402e700>, id: playerID1, name: Player1,<GKCloudPlayer: 0x17402e900>, id: playerID2, name: Player2]

fatal error: The requested operation could not be completed because there are no recipients connected to the session.

Got this on two real devices.

Body:
I was able to send data and receive it on the other device. I used loadSessions function to load all session (I think that loadSession by id would do the trick too).
I did the following, D1 is a device 1 and D2 device 2:

1. D1: load all sessions and set player state to connected
2. D2: load all sessions and set player state to connected
3. D1: load all sessions again and set player state to connected
4. D1 || D2: send data
5. D2 || D1: data 256 bytes from player: <GKCloudPlayer: 0x1c022b380>, id: playerID, name: (null)

Although, I wasn't able to transfer data back and forth on both devices since if we'll add step 6. that sends data from device that just received it, we'll get an error: The requested operation could not be completed because there are no recipients connected to the session.

I do not sure what is the reason of it but I stop my efforts on this stage, since I think now, that I don't need to be connected to session to play turn based game.

I found this "new" iOS 10 APIs abandoned. By Apple and by devs consequently. If you one of those who still trying to use it drop me a note at my twitter (link in my bio) if you want to discuss GKGameSession and related topics.


问:
Parsing date strings: some correctly formatted strings return errors
While trying to retrieve day of the week from the string, sometimes an error occurs although the string corresponds to the predefined format.

Below is the function that is used to parse strings and format definition:

```<code>val dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
def getDayOfWeek(date: String): Int = {
    val stringToParse = date.substring(0, 19)
    try {
      val now = Calendar.getInstance()
      now.setTime(dateFormat.parse(stringToParse))
      println("Correct time string: " + stringToParse)
      now.get(Calendar.DAY_OF_WEEK)
    } catch {
      case _: Throwable => println("Wrong time string: " + stringToParse)
        -1
    }
}
</code>```

Below are the examples of successfully/unsuccessfully parsed strings:

```<code>Correct time string: 2017-01-01 04:00:00
Wrong time string: 2017-05-04 15:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 15:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-05-04 15:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 15:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Wrong time string: 2017-06-13 07:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-05-04 16:00:00
</code>```

Does anyone know what could cause the error in the above cases? I don't spot any differences between the successful/unsuccessful examples.

Thanks!

答:
Problem is your SimpleDateFormat is declared globally.

Bring your line

```<code>val dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
</code>```

inside the function.

SimpleDateFormat is not thread safe, and I assume you must be calling getDayoftheweek() function from outside non-synchronized code.

Body:
While trying to retrieve day of the week from the string, sometimes an error occurs although the string corresponds to the predefined format.

Below is the function that is used to parse strings and format definition:

val dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
def getDayOfWeek(date: String): Int = {
    val stringToParse = date.substring(0, 19)
    try {
      val now = Calendar.getInstance()
      now.setTime(dateFormat.parse(stringToParse))
      println("Correct time string: " + stringToParse)
      now.get(Calendar.DAY_OF_WEEK)
    } catch {
      case _: Throwable => println("Wrong time string: " + stringToParse)
        -1
    }
}

Below are the examples of successfully/unsuccessfully parsed strings:

Correct time string: 2017-01-01 04:00:00
Wrong time string: 2017-05-04 15:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 15:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-05-04 15:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 15:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Wrong time string: 2017-06-13 07:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-05-04 16:00:00

Does anyone know what could cause the error in the above cases? I don't spot any differences between the successful/unsuccessful examples.

Thanks!

Body:
Problem is your SimpleDateFormat is declared globally.

Bring your line

val dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

inside the function.

SimpleDateFormat is not thread safe, and I assume you must be calling getDayoftheweek() function from outside non-synchronized code.


问:
Learning CIL
Does anybody know any good resources for learning how to program CIL with in-depth descriptions of commands, etc.? I have looked around but not found anything particularly good.</p>

答:
The only CIL book on my shelf is Expert .NET 2.0 IL Assembler by Serge Lidin.  In terms of what the individual opcodes do or mean, the Microsoft documentation on System.Reflection.Emit has some pretty good information.  And it's always useful to look at existing IL with Reflector.

Edit: CIL (and indeed the CLR in general) has not changed at all between .NET 2.0 and .NET 3.5 -- the underlying runtime is basically the same, modulo fixes and performance improvements.  So there's nothing newer available on a CIL level than what would be in a book on 2.0

OwnerDisplayName: kronoz

Title: Learning CIL

LastEditorDisplayName: Eric Z Beard

OwnerDisplayName: Curt Hagenlocher

LastEditorDisplayName: Curt Hagenlocher


问:
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.

This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.

Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?

Thought about web for a second but it would not work for business reasons.

答:
Using PAR, the Perl Aachiver has already been mentioned in other answers, and is an excellent solution.  There's a short tutorial on building executables using PAR that was published as a Perl Tip last year.

In most cases, if you have PAR::Packer already installed on your build system, you can create a stand-alone executable with no external dependencies or requirements with:

```<code>pp -o example.exe example.pl
</code>```

In most cases PAR will do all the hard work of determining your module dependencies for you, but if it gets anything wrong there are additional command line options you can use to ensure they get included.  See the pp documentation for more details.

All the best,

Paul

OwnerDisplayName: Brian G

LastEditorDisplayName: brian d foy

Body:
Using PAR, the Perl Aachiver has already been mentioned in other answers, and is an excellent solution.  There's a short tutorial on building executables using PAR that was published as a Perl Tip last year.

In most cases, if you have PAR::Packer already installed on your build system, you can create a stand-alone executable with no external dependencies or requirements with:

pp -o example.exe example.pl

In most cases PAR will do all the hard work of determining your module dependencies for you, but if it gets anything wrong there are additional command line options you can use to ensure they get included.  See the pp documentation for more details.

All the best,

Paul

OwnerDisplayName: pjf


问:
Find large number of consecutive values fulfilling condition in a numpy array
I have some audio data loaded in a numpy array and I wish to segment the data by finding silent parts, i.e. parts where the audio amplitude is below a certain threshold over a period in time.

An extremely simple way to do this is something like this:

```<code>values = ''.join(("1" if (abs(x) < SILENCE_THRESHOLD) else "0" for x in samples))
pattern = re.compile('1{%d,}'%int(MIN_SILENCE))
for match in pattern.finditer(values):
   # code goes here
</code>```

The code above finds parts where there are at least MIN_SILENCE consecutive elements smaller than SILENCE_THRESHOLD.

Now, obviously, the above code is horribly inefficient and a terrible abuse of regular expressions. Is there some other method that is more efficient, but still results in equally simple and short code?

答:
This should return a list of (start,length) pairs:

```<code>def silent_segs(samples,threshold,min_dur):
  start = -1
  silent_segments = []
  for idx,x in enumerate(samples):
    if start < 0 and abs(x) < threshold:
      start = idx
    elif start >= 0 and abs(x) >= threshold:
      dur = idx-start
      if dur >= min_dur:
        silent_segments.append((start,dur))
      start = -1
  return silent_segments
</code>```

And a simple test:

```<code>>>> s = [-1,0,0,0,-1,10,-10,1,2,1,0,0,0,-1,-10]
>>> silent_segs(s,2,2)
[(0, 5), (9, 5)]
</code>```

Body:
I have some audio data loaded in a numpy array and I wish to segment the data by finding silent parts, i.e. parts where the audio amplitude is below a certain threshold over a period in time.

An extremely simple way to do this is something like this:

values = ''.join(("1" if (abs(x) < SILENCE_THRESHOLD) else "0" for x in samples))
pattern = re.compile('1{%d,}'%int(MIN_SILENCE))
for match in pattern.finditer(values):
   # code goes here

The code above finds parts where there are at least MIN_SILENCE consecutive elements smaller than SILENCE_THRESHOLD.

Now, obviously, the above code is horribly inefficient and a terrible abuse of regular expressions. Is there some other method that is more efficient, but still results in equally simple and short code?

Body:
This should return a list of (start,length) pairs:

def silent_segs(samples,threshold,min_dur):
  start = -1
  silent_segments = []
  for idx,x in enumerate(samples):
    if start < 0 and abs(x) < threshold:
      start = idx
    elif start >= 0 and abs(x) >= threshold:
      dur = idx-start
      if dur >= min_dur:
        silent_segments.append((start,dur))
      start = -1
  return silent_segments

And a simple test:

>>> s = [-1,0,0,0,-1,10,-10,1,2,1,0,0,0,-1,-10]
>>> silent_segs(s,2,2)
[(0, 5), (9, 5)]


问:
Reference a constant from one function in another
I am attempting to send user information gathered from the facebookSDK and perform an HTTP POST sending the details I gathered stored in constants.

I am new to swift development and although this solution may be straight forward I am unable to configure a workable solution.

I need to pass the data in the fetchProfile() function into the data_request() function to pass data to the API.

The image shows the data_request function, highlighted is the line where i need to reference the data stored in constants within the fetchProfile() function

This image shows the fetchProfile() function holding the data needed to be passed to data_request()

Any feedback or guidance is greatly appreciated.

答:
Improving upon the answer posted by Fangming, you need to pass the data received in fetchProfile() to data_request() and call it at the end of the completion block of FBSDKGraphRequest.start. This is how it should look like:

```<code>func fetchProfile() {
    FBSDKGraphRequest(...).start {
        // create a dictionary to hold all the values returned
        let values: [String: Any]

        // fetch all values in to the dictionary
        // ...

        // call data_request by passing URL and the dictionary
        data_request(url, params: values)
    }
}
</code>```

Now the data_request function should look like this now:

```<code>func data_request(url: String, params: [String: Any]) {
    // your implementation here
}
</code>```

Body:
Improving upon the answer posted by Fangming, you need to pass the data received in fetchProfile() to data_request() and call it at the end of the completion block of FBSDKGraphRequest.start. This is how it should look like:

func fetchProfile() {
    FBSDKGraphRequest(...).start {
        // create a dictionary to hold all the values returned
        let values: [String: Any]

        // fetch all values in to the dictionary
        // ...

        // call data_request by passing URL and the dictionary
        data_request(url, params: values)
    }
}

Now the data_request function should look like this now:

func data_request(url: String, params: [String: Any]) {
    // your implementation here
}


问:
TypeError: __init__() got an unexpected keyword argument 'shape'
I am new to Tensorflow and I met an error while trying to run some sample codes.

```<code>import tensorflow as tf

g1 = tf.Graph()
with g1.as_default():
    v = tf.get_variable("v", initializer=tf.zeros_initializer(shape=[1]))
</code>```

Running the code above gives the error:
TypeError: __init__() got an unexpected keyword argument 'shape'.

The comment below says that tf.zeros_initializer does not accept 'shape' argument according to the documentation. I tried

```<code>v = tf.get_variable("v", initializer=tf.zeros_initializer())
</code>```

and it says ValueError: Shape of a new variable (v) must be fully defined, but instead was .

So, what kind of argument/expression should I use to define the shape without causing a type error?

I cannot find how to solve it online. Please help. Thank you

答:
It appears that the book I'm using is a bit out of date. The following code appears to work so far.

```<code>v = tf.get_variable("v", shape=[1], initializer=tf.zeros_initializer)
</code>```

I will check if it actually works with more code added later.

Body:
I am new to Tensorflow and I met an error while trying to run some sample codes.

import tensorflow as tf

g1 = tf.Graph()
with g1.as_default():
    v = tf.get_variable("v", initializer=tf.zeros_initializer(shape=[1]))

Running the code above gives the error:
TypeError: __init__() got an unexpected keyword argument 'shape'.

The comment below says that tf.zeros_initializer does not accept 'shape' argument according to the documentation. I tried

v = tf.get_variable("v", initializer=tf.zeros_initializer())

and it says ValueError: Shape of a new variable (v) must be fully defined, but instead was .

So, what kind of argument/expression should I use to define the shape without causing a type error?

I cannot find how to solve it online. Please help. Thank you

Body:
It appears that the book I'm using is a bit out of date. The following code appears to work so far.

v = tf.get_variable("v", shape=[1], initializer=tf.zeros_initializer)

I will check if it actually works with more code added later.


问:
Executing a jar file in bash script
i want to write a bash script to execute a jar file.

The thing is i can't just write java -jar filename.jar cause it's gonna have several versions like :

filename-v1.0.jar

filename-v1.5.jar

filename-v2.0.jar

but i dont wanna have to chance the script. Is there a way to just write something like java -jar filename$.jar or something ??

答:
First of all see if your IDE options can help you.

One option can be to have a version file in same directory. This file will include the version number and you can change it when you want. Then your command will be the next :

```<code>java -jar filename`cat version`.jar
</code>```

This is an easy option. Then you can control your execution version only changing the content from this file.

If you looks for a pattern do something like :

```<code>java -jar `ls | grep "pattern"`
</code>```

All your files reported by this command will be executed by java.

Title: Executing a jar file in bash script

Body:
First of all see if your IDE options can help you.

One option can be to have a version file in same directory. This file will include the version number and you can change it when you want. Then your command will be the next :

java -jar filename`cat version`.jar

This is an easy option. Then you can control your execution version only changing the content from this file.

If you looks for a pattern do something like :

java -jar `ls | grep "pattern"`

All your files reported by this command will be executed by java.


答:
inside bash script  use $1

java -jar $1

and then pass the jar name as argument to your script.

sh runjar.sh filename.jar
~

Title: Executing a jar file in bash script

Body:
i want to write a bash script to execute a jar file.

The thing is i can't just write java -jar filename.jar cause it's gonna have several versions like :

filename-v1.0.jar

filename-v1.5.jar

filename-v2.0.jar

but i dont wanna have to chance the script. Is there a way to just write something like java -jar filename$.jar or something ??


答:
You can do  </p>

```<code>#!/bin/bash
java -jar $1 // or filename-$1.jar or $1.jar
</code>```

<p>and then give it as argument like </p>

```<code>myscript.sh filename-v1.0.jar // or v1.0 or filename-v1.0
</code>```

Title: Executing a jar file in bash script

Body:
You can do

#!/bin/bash
java -jar $1 // or filename-$1.jar or $1.jar

and then give it as argument like

myscript.sh filename-v1.0.jar // or v1.0 or filename-v1.0