问:
Oracle UTL_FILE read CSV file lines
i'm using UTL_FILE package to read a csv file , then insert values in table, but my issue is how to read values separated by Commas.. , this is my code :

```<code>     declare
         file1 UTL_FILE.FILE_TYPE;
         str varchar2(200 CHAR);
        begin
         file1 := UTL_FILE.FOPEN('DRCT1','test_file.csv','R');

         loop
          UTL_FILE.GET_LINE(file1,str);
-- here i want to read each value before the Commas then insert them in my table
-- insert statement..
          dbms_output.put_line(str);
         end loop;

        exception
        when no_data_found then
        UTL_FILE.FCLOSE(file1);

        end;
        /
</code>```

this is my csv file :

```<code>100,Steven,King
101,Neena,Kochha
102,Lex,De Haan
103,Alexander
104,Bruce,Ernst
</code>```

please do you have any suggestion to my issue ?

Regards .

答:
As an alternative you can use "external tables" to read the CVS file.
So you can "query" the file as a table.

1-If your Oracle database is on:

a-Windows, then use "delimited by '\r\n'"

b-Linux/unix, then use "delimited by '\n'"

2-First row of file no have column names.

3-Delimiter is comma, ascii 44, ",".

4-Fields can have data enclosed between quotes, ascii 34.

So values can have spaces, comma, and double quotes as one quote.

```<code>  create table test_file_ext
  (id      number,
   fname   varchar2(200),
   lname   varchar2(200)
  )
  organization external
  (type oracle_loader
   default directory DRCT1
   access parameters (records      delimited by '\r\n'
                      badfile     'test_file_ext.bad'
                      discardfile 'test_file_ext.dis'
                      logfile     'test_file_ext.log'
                      fields terminated by ','
                             optionally enclosed by '"'
                             missing field values are null
                             reject rows with all null fields
                     )
   location ('test_file.csv')
  )
  reject limit UNLIMITED;
</code>```

Title: Oracle UTL_FILE read CSV file lines

Body:
i'm using UTL_FILE package to read a csv file , then insert values in table, but my issue is how to read values separated by Commas.. , this is my code :

     declare
         file1 UTL_FILE.FILE_TYPE;
         str varchar2(200 CHAR);
        begin
         file1 := UTL_FILE.FOPEN('DRCT1','test_file.csv','R');

         loop
          UTL_FILE.GET_LINE(file1,str);
-- here i want to read each value before the Commas then insert them in my table
-- insert statement..
          dbms_output.put_line(str);
         end loop;

        exception
        when no_data_found then
        UTL_FILE.FCLOSE(file1);

        end;
        /

this is my csv file :

100,Steven,King
101,Neena,Kochha
102,Lex,De Haan
103,Alexander
104,Bruce,Ernst

please do you have any suggestion to my issue ?

Regards .

Body:
As an alternative you can use "external tables" to read the CVS file.
So you can "query" the file as a table.

1-If your Oracle database is on:

a-Windows, then use "delimited by '\r\n'"

b-Linux/unix, then use "delimited by '\n'"

2-First row of file no have column names.

3-Delimiter is comma, ascii 44, ",".

4-Fields can have data enclosed between quotes, ascii 34.

So values can have spaces, comma, and double quotes as one quote.

  create table test_file_ext
  (id      number,
   fname   varchar2(200),
   lname   varchar2(200)
  )
  organization external
  (type oracle_loader
   default directory DRCT1
   access parameters (records      delimited by '\r\n'
                      badfile     'test_file_ext.bad'
                      discardfile 'test_file_ext.dis'
                      logfile     'test_file_ext.log'
                      fields terminated by ','
                             optionally enclosed by '"'
                             missing field values are null
                             reject rows with all null fields
                     )
   location ('test_file.csv')
  )
  reject limit UNLIMITED;


来源: stackexchange

问:
Testing if something is a class in javascript
Hey all, I am trying to test if the argument passed into my function is a class name so that I may compare it to other classes using instanceof.

For example:

```<code>function foo(class1, class2) {
  // Test to see if the parameter is a class.
  if(class1 is a class)
  {
    //do some kind of class comparison.
    if(class2 is a class)
    {
       if(class1 instanceof class2)
       {
          //...
       }
    }
    else
    {
       //...
    }
  }
  else
    //...
}
</code>```

Is this possible? I am having trouble googleing an answer.

答:
I haven't found any 100% certain way to figure out
if something is a class and not a function. The
accepted answer above works in most cases but if
someone redefines the method toString() of their
class it may break in that case. Why would they
ever redefine toString()? I don't know, ask them
if they are still around :-)

So instead I took the approach of defining this
function:

```<code>function isClass(v)
{ if (typeof v !== "function")
  { return false;
  }
  if ( typeof v.isClass === "function" &&
       v.isClass()
     )
  { return true;
  }
}
</code>```

This means I can mark my own classes as
being classes I recognize as classes by
giving them the static method isClass()
which returns true. If such classes have
subclasses the subclasses inherit the
method and are thus automatically recognized
as "classes" as well.

If I need to work with someone else's
classes which does not have this method
I might first subclass their class so
that my subclass is like their class
except it also has the isClass() -method.

I hope the next version of EcmaScript will
remedy this lack of standardized solution
but for now this is the best I can do.

It has the additional benefit that I might
in fact give the method isClass() to some
of my non-class-functions as well, which are
not classes proper, and then be able to
treat such functions as if they were classes,
for whatever reason I might want to.

OwnerDisplayName: kgrad

ContentLicense: CC BY-SA 2.5

Body:
Hey all, I am trying to test if the argument passed into my function is a class name so that I may compare it to other classes using instanceof.

For example:

function foo(class1, class2) {
  // Test to see if the parameter is a class.
  if(class1 is a class)
  {
    //do some kind of class comparison.
    if(class2 is a class)
    {
       if(class1 instanceof class2)
       {
          //...
       }
    }
    else
    {
       //...
    }
  }
  else
    //...
}

Is this possible? I am having trouble googleing an answer.

LastEditorDisplayName: EndangeredMassa

Body:
I haven't found any 100% certain way to figure out
if something is a class and not a function. The
accepted answer above works in most cases but if
someone redefines the method toString() of their
class it may break in that case. Why would they
ever redefine toString()? I don't know, ask them
if they are still around :-)

So instead I took the approach of defining this
function:

function isClass(v)
{ if (typeof v !== "function")
  { return false;
  }
  if ( typeof v.isClass === "function" &&
       v.isClass()
     )
  { return true;
  }
}

This means I can mark my own classes as
being classes I recognize as classes by
giving them the static method isClass()
which returns true. If such classes have
subclasses the subclasses inherit the
method and are thus automatically recognized
as "classes" as well.

If I need to work with someone else's
classes which does not have this method
I might first subclass their class so
that my subclass is like their class
except it also has the isClass() -method.

I hope the next version of EcmaScript will
remedy this lack of standardized solution
but for now this is the best I can do.

It has the additional benefit that I might
in fact give the method isClass() to some
of my non-class-functions as well, which are
not classes proper, and then be able to
treat such functions as if they were classes,
for whatever reason I might want to.

ContentLicense: CC BY-SA 4.0


问:
How can I create a simple assignment statement in codemodel?
I want to create a simple statement using codemodel like :-

```<code>String text = element.getText();
</code>```

I don't want to assign it to any block for now, rather just return it because I would be needing the name of the variable to refer later. How can I create such a statement and in which type of variable to store it? Would it be a JStatement? If yes then how?

答: It looks like the codemodel api doesn't allow you to create an assigment without a Block.  The JAssignment object is created via the JBlock .assign() method, and the constructor for JAssignment is package private.  That being said, you can always make an object of your own to hold the various parts of the assignment and defer the building of the assignment until you have a block to add it to.

Body:
I want to create a simple statement using codemodel like :-

String text = element.getText();

I don't want to assign it to any block for now, rather just return it because I would be needing the name of the variable to refer later. How can I create such a statement and in which type of variable to store it? Would it be a JStatement? If yes then how?


问:
selection based on percentage weighting
I have a set of values, and an associated percentage for each:

a: 70% chance

b: 20% chance

c: 10% chance

I want to select a value (a, b, c) based on the percentage chance given.

how do I approach this?

my attempt so far looks like this:

```<code>r = random.random()
if r <= .7:
    return a
elif r <= .9:
    return b
else:
    return c
</code>```

I'm stuck coming up with an algorithm to handle this.  How should I approach this so it can handle larger sets of values without just chaining together if-else flows.

(any explanation or answers in pseudo-code are fine.  a python or C# implementation would be especially helpful)

答:
Based loosely on python's numpy.random.choice(a=items, p=probs), which takes an array and a probability array of the same size.

```<code>    public T RandomChoice<T>(IEnumerable<T> a, IEnumerable<double> p)
    {
        IEnumerator<T> ae = a.GetEnumerator();
        Random random = new Random();
        double target = random.NextDouble();
        double accumulator = 0;
        foreach (var prob in p)
        {
            ae.MoveNext();
            accumulator += prob;
            if (accumulator > target)
            {
                break;
            }
        }
        return ae.Current;
    }
</code>```

The probability array p must sum to (approx.) 1.  This is to keep it consistent with the numpy interface (and mathematics), but you could easily change that if you wanted.

Title: selection based on percentage weighting

Body:
I have a set of values, and an associated percentage for each:

a: 70% chance

b: 20% chance

c: 10% chance

I want to select a value (a, b, c) based on the percentage chance given.

how do I approach this?

my attempt so far looks like this:

r = random.random()
if r <= .7:
    return a
elif r <= .9:
    return b
else:
    return c

I'm stuck coming up with an algorithm to handle this.  How should I approach this so it can handle larger sets of values without just chaining together if-else flows.

(any explanation or answers in pseudo-code are fine.  a python or C# implementation would be especially helpful)

Body:
Based loosely on python's numpy.random.choice(a=items, p=probs), which takes an array and a probability array of the same size.

    public T RandomChoice<T>(IEnumerable<T> a, IEnumerable<double> p)
    {
        IEnumerator<T> ae = a.GetEnumerator();
        Random random = new Random();
        double target = random.NextDouble();
        double accumulator = 0;
        foreach (var prob in p)
        {
            ae.MoveNext();
            accumulator += prob;
            if (accumulator > target)
            {
                break;
            }
        }
        return ae.Current;
    }

The probability array p must sum to (approx.) 1.  This is to keep it consistent with the numpy interface (and mathematics), but you could easily change that if you wanted.


问:
Python delete dictionary items with same values
How would I remove dictionary items that have different keys but identical values? I am sure there a better way than my novice algorithm...?

Example: (abends with error "dictionary changed size during iteration")

The goal of this example is to remove either 'car_id' or 'truck_id' from dict.

```<code>key_fields_obj = {}
key_fields_obj['car_id'] = 'bob'
key_fields_obj['bike_id'] = 'sam'
key_fields_obj['truck_id'] = 'bob' #goal: remove this one, so left with only car_id and bike_id

for item in key_fields_obj:
    tst = key_fields_obj[item]
    for comp in key_fields_obj:
        if item == comp:
            continue
        cmp = key_fields_obj[comp]
        if cmp == tst:
            del key_fields_obj[comp]

print(key_fields_obj)
</code>```

答:
Create a new dict with values as key and key as values, then perform the same again on new dict.</p>

```<code>>>> key_fields_obj = {key_fields_obj[key]: key for key in key_fields_obj}
>>> key_fields_obj
{'bob': 'truck_id', 'sam': 'bike_id'}
>>>
>>> key_fields_obj = {key_fields_obj[key]: key for key in key_fields_obj}
>>> key_fields_obj
{'truck_id': 'bob', 'bike_id': 'sam'}
</code>```

Body:
How would I remove dictionary items that have different keys but identical values? I am sure there a better way than my novice algorithm...?

Example: (abends with error "dictionary changed size during iteration")

The goal of this example is to remove either 'car_id' or 'truck_id' from dict.

key_fields_obj = {}
key_fields_obj['car_id'] = 'bob'
key_fields_obj['bike_id'] = 'sam'
key_fields_obj['truck_id'] = 'bob' #goal: remove this one, so left with only car_id and bike_id

for item in key_fields_obj:
    tst = key_fields_obj[item]
    for comp in key_fields_obj:
        if item == comp:
            continue
        cmp = key_fields_obj[comp]
        if cmp == tst:
            del key_fields_obj[comp]

print(key_fields_obj)

Body:
Create a new dict with values as key and key as values, then perform the same again on new dict.

>>> key_fields_obj = {key_fields_obj[key]: key for key in key_fields_obj}
>>> key_fields_obj
{'bob': 'truck_id', 'sam': 'bike_id'}
>>>
>>> key_fields_obj = {key_fields_obj[key]: key for key in key_fields_obj}
>>> key_fields_obj
{'truck_id': 'bob', 'bike_id': 'sam'}


问:
Python convert byte string to list of dictionaries based on newline
I have a string byte

```<code>data = b'ra1,rb1,rc1\nra2,rb2,rc2\nra3,rb3,rc3\nra4,rb4,rc4' # No \n at the end
</code>```

The result should be like

```<code>result = [
{"field1": "ra1", "field2": "rb1", "field3": "rc1"},
{"field1": "ra2", "field2": "rb2", "field3": "rc2"},
{"field1": "ra3", "field2": "rb3", "field3": "rc3"},
{"field1": "ra4", "field2": "rb4", "field3": "rc4"}
]
</code>```

I tried

```<code>result = csv.DictReader(data, fieldnames=('field1', 'field2', 'field3'))
</code>```

Please note that I'm not dealing with any CSV files here.

I know we need to pass file object as the first parameter to the above DictReader method to get the above result.

Is there any similar in-built method in python 3.6 to achieve my result?

Here I don't want to use loop since my data will be very huge.

答:
```<code>import pandas as pd, io
data = b'ra1,rb1,rc1\nra2,rb2,rc2\nra3,rb3,rc3\nra4,rb4,rc4'
names = {0:'fields1',1:'fields2',2:'fields3'}

pd.read_csv(io.StringIO(data.decode('utf8')),header=None).rename(names,axis=1).to_dict('records')

[{'fields1': 'ra1', 'fields2': 'rb1', 'fields3': 'rc1'},
 {'fields1': 'ra2', 'fields2': 'rb2', 'fields3': 'rc2'},
 {'fields1': 'ra3', 'fields2': 'rb3', 'fields3': 'rc3'},
 {'fields1': 'ra4', 'fields2': 'rb4', 'fields3': 'rc4'}]
</code>```

Body:
I have a string byte

data = b'ra1,rb1,rc1\nra2,rb2,rc2\nra3,rb3,rc3\nra4,rb4,rc4' # No \n at the end

The result should be like

result = [
{"field1": "ra1", "field2": "rb1", "field3": "rc1"},
{"field1": "ra2", "field2": "rb2", "field3": "rc2"},
{"field1": "ra3", "field2": "rb3", "field3": "rc3"},
{"field1": "ra4", "field2": "rb4", "field3": "rc4"}
]

I tried

result = csv.DictReader(data, fieldnames=('field1', 'field2', 'field3'))

Please note that I'm not dealing with any CSV files here.

I know we need to pass file object as the first parameter to the above DictReader method to get the above result.

Is there any similar in-built method in python 3.6 to achieve my result?

Here I don't want to use loop since my data will be very huge.


问:
Read list from a file
I want to read a simple list from a file. But can't separate list elements from one another.

Here's my file:

```<code>"11","Arial","red","white","black","200x200","My Project"
</code>```

Here's my read function:

def fread(file_name):
    user_file=open('{}'.format(file_name),"r")
    file_content=user_file.read()
    user_file.close()
    return str(file_content)
```

<p>Here's the part that does not work:</p>

<pre class="lang-py prettyprint-override"><code>conf_file=fread("settings")
conf_file.split(",")
print(conf_file[2])
</code>```

This returns 1 instead of red

答:
You need to split on the "commas", and remove the enclosing double-quotes -

Also, no need for a four line function to read the file contents:

```<code>conf_file = [part.strip('"') for part in open(filename).read().split(",")]
</code>```

Title: Read list from a file

Body:
I want to read a simple list from a file. But can't separate list elements from one another.

Here's my file:

"11","Arial","red","white","black","200x200","My Project"

Here's my read function:

def fread(file_name):
    user_file=open('{}'.format(file_name),"r")
    file_content=user_file.read()
    user_file.close()
    return str(file_content)

Here's the part that does not work:

conf_file=fread("settings")
conf_file.split(",")
print(conf_file[2])

This returns 1 instead of red

Body:
You need to split on the "commas", and remove the enclosing double-quotes -

Also, no need for a four line function to read the file contents:

conf_file = [part.strip('"') for part in open(filename).read().split(",")]


问:
How to replace the Segoe UI Emoji font in an UWP app?
I'd like to replace the Segoe UI Emoji font with a newer version for all text controls in my app on older Windows 10 devices, so all devices support all the new Unicode 11 Emoji.
Is there a way to do this in an UWP C# Windows 10 app?

I tried declaring my own FontFamily and replacing ContentControlThemeFontFamily but it does not work. It only updates the actual font characters like ABCD....

Example:

```<code>TextBlock FontFamily="Assets/Fonts/seguiemj.ttf#Segoe UI Emoji" Text=""/>
</code>```

The  Emoji is part of Unicode 11 and shows up on all updated W10 devices, but like mentioned above not on older devices (only shows as empty square).
All of this even through I set my own font that should support it (copied from an updated W10 PC).

答:
I added the following into the App.xaml which fixed my problem:

```<code><FontFamily x:Key="ContentControlThemeFontFamily">ms-appx:///Assets/Fonts/seguiemj.ttf#Segoe UI Emoji,XamlAutoFontFamily</FontFamily>
</code>```

Body:
I'd like to replace the Segoe UI Emoji font with a newer version for all text controls in my app on older Windows 10 devices, so all devices support all the new Unicode 11 Emoji.
Is there a way to do this in an UWP C# Windows 10 app?

I tried declaring my own FontFamily and replacing ContentControlThemeFontFamily but it does not work. It only updates the actual font characters like ABCD....

Example:

TextBlock FontFamily="Assets/Fonts/seguiemj.ttf#Segoe UI Emoji" Text=""/>

The  Emoji is part of Unicode 11 and shows up on all updated W10 devices, but like mentioned above not on older devices (only shows as empty square).
All of this even through I set my own font that should support it (copied from an updated W10 PC).

Body:
I added the following into the App.xaml which fixed my problem:

<FontFamily x:Key="ContentControlThemeFontFamily">ms-appx:///Assets/Fonts/seguiemj.ttf#Segoe UI Emoji,XamlAutoFontFamily</FontFamily>


问:
Reversing a linked list in a specific manner through PHP
Given a Singly Linked List $link, with elements (a->b->c->d->e->f->g->h->i->j), we need to reverse the linked list provided that the reversing will be done in a manner like -

Reverse 1st element (a)

Reverse next 2 elements (a->c->b)

Reverse next 3 elements (a->c->b->f->e->d)

Reverse next 4 elements (a->c->b->f->e->d->j->i->h->g)

....

....

I am looking for a PHP function code which takes the linked list $link and reverse it in above manner with least time complexity.

For help, I am adding my code below for linked list. The function reverseLinkedList has to be completed to perform this specific reverse operation -

```<code>class ListNode
{
    public $data;
    public $next;

    function __construct($data)
    {
        $this->data = $data;
        $this->next = NULL;
    }

    function read_node()
    {
        return $this->data;
    }
}

class LinkList
{
    private $first_node;
    private $last_node;
    private $count;

    function __construct()
    {
        $this->first_node = NULL;
        $this->last_node = NULL;
        $this->count = 0;
    }

    function size()
    {
        return $this->count;
    }

    public function read_list()
    {
        $listData = array();
        $current = $this->first_node;
        while($current != NULL)
        {
            echo $current->read_node().' ';
            $current = $current->next;
        }
    }

    public function reverse_list()
    {
        if(($this->first_node != NULL)&&($this->first_node->next != NULL))
        {
            $current = $this->first_node;
            $new = NULL;

            while ($current != NULL)
            {
                $temp = $current->next;
                $current->next = $new;
                $new = $current;
                $current = $temp;
            }
            $this->first_node = $new;
        }
    }

    public function read_node($position)
    {
        if($position <= $this->count)
        {
            $current = $this->first_node;
            $pos = 1;
            while($pos != $position)
            {
                if($current->next == NULL)
                    return null;
                else
                    $current = $current->next;

                $pos++;
            }
            return $current->data;
        }
        else
            return NULL;
    }

    public function insert($data)
    {
        $new_node = new ListNode($data);

        if($this->first_node != NULL)
        {
            $this->last_node->next = $new_node;
            $new_node->next = NULL;
            $this->last_node = &$new_node;
            $this->count++;
        }
        else
        {
            $new_node->next = $this->first_node;
            $this->first_node = &$new_node;

            if($this->last_node == NULL)
                $this->last_node = &$new_node;

            $this->count++;
        }
    }
}

//Create linked list
$link1 = new LinkList();

//Insert elements
$link1->insert('a');
$link1->insert('b');
$link1->insert('c');
$link1->insert('d');
$link1->insert('e');
$link1->insert('f');
$link1->insert('g');
$link1->insert('h');
$link1->insert('i');
$link1->insert('j');

echo "<b>Input :</b><br>";
$link1->read_list();

//function to reverse linked list in specified manner
function reverseLinkedList(&$link1)
{
  //Logic to reverse the linked list $link1
}
///function to reverse linked list in specified manner

//Reverse current linked list $link1
reverseLinkedList($link1);

echo "<br><br><b>Output :</b><br>";
$link1->read_list();
</code>```

答:
For example You have linked objects:

```<code>class obj {
    public $next;
}

$a = new obj();
$b = new obj();
$c = new obj();
$d = new obj();

$a->next = $b;
$b->next = $c;
$c->next = $d;
$d->next = null;

$obj = $a;
</code>```

Your task is to make sure that the result is returned in the reverse sequence:

```<code>$d->next->$c->next->$b->next->$a = null;
</code>```

Try to use the following code for yourself and fix it for your task

```<code>$new = null;

function recursive(&$new, &$obj) {

    if(is_object($new) && (spl_object_id($new)-1) === 0) {
        return null;
    }

    $getLast = function (&$obj) use(&$getLast) {
        if($obj->next === null) {
            return $obj;
        }

        return $getLast($obj->next);
    };

    $dropLast = function (&$obj) use(&$dropLast) {

        if(!isset($obj->next)) {
            return null;
        }

        if($obj->next->next === null) {
            $obj->next = null;
            return null;
        }

        return $dropLast($obj->next);
    };

    if($new === null) {
        $new = $getLast($obj);
        $dropLast($obj);
        $new->next = $getLast($obj);
    } else {
        $new->next = $getLast($obj);
    }

    $dropLast($obj);

    return recursive($new->next, $obj);
}

recursive($new, $obj);

echo '```';
var_dump($new);
exit;
```

ContentLicense: CC BY-SA 3.0

Body:
Given a Singly Linked List $link, with elements (a->b->c->d->e->f->g->h->i->j), we need to reverse the linked list provided that the reversing will be done in a manner like -

Reverse 1st element (a)

Reverse next 2 elements (a->c->b)

Reverse next 3 elements (a->c->b->f->e->d)

Reverse next 4 elements (a->c->b->f->e->d->j->i->h->g)

....

....

I am looking for a PHP function code which takes the linked list $link and reverse it in above manner with least time complexity.

For help, I am adding my code below for linked list. The function reverseLinkedList has to be completed to perform this specific reverse operation -

class ListNode
{
    public $data;
    public $next;

    function __construct($data)
    {
        $this->data = $data;
        $this->next = NULL;
    }

    function read_node()
    {
        return $this->data;
    }
}

class LinkList
{
    private $first_node;
    private $last_node;
    private $count;

    function __construct()
    {
        $this->first_node = NULL;
        $this->last_node = NULL;
        $this->count = 0;
    }

    function size()
    {
        return $this->count;
    }

    public function read_list()
    {
        $listData = array();
        $current = $this->first_node;
        while($current != NULL)
        {
            echo $current->read_node().' ';
            $current = $current->next;
        }
    }

    public function reverse_list()
    {
        if(($this->first_node != NULL)&&($this->first_node->next != NULL))
        {
            $current = $this->first_node;
            $new = NULL;

            while ($current != NULL)
            {
                $temp = $current->next;
                $current->next = $new;
                $new = $current;
                $current = $temp;
            }
            $this->first_node = $new;
        }
    }

    public function read_node($position)
    {
        if($position <= $this->count)
        {
            $current = $this->first_node;
            $pos = 1;
            while($pos != $position)
            {
                if($current->next == NULL)
                    return null;
                else
                    $current = $current->next;

                $pos++;
            }
            return $current->data;
        }
        else
            return NULL;
    }

    public function insert($data)
    {
        $new_node = new ListNode($data);

        if($this->first_node != NULL)
        {
            $this->last_node->next = $new_node;
            $new_node->next = NULL;
            $this->last_node = &$new_node;
            $this->count++;
        }
        else
        {
            $new_node->next = $this->first_node;
            $this->first_node = &$new_node;

            if($this->last_node == NULL)
                $this->last_node = &$new_node;

            $this->count++;
        }
    }
}

//Create linked list
$link1 = new LinkList();

//Insert elements
$link1->insert('a');
$link1->insert('b');
$link1->insert('c');
$link1->insert('d');
$link1->insert('e');
$link1->insert('f');
$link1->insert('g');
$link1->insert('h');
$link1->insert('i');
$link1->insert('j');

echo "Input :
";
$link1->read_list();

//function to reverse linked list in specified manner
function reverseLinkedList(&$link1)
{
  //Logic to reverse the linked list $link1
}
///function to reverse linked list in specified manner

//Reverse current linked list $link1
reverseLinkedList($link1);

echo "

Output :
";
$link1->read_list();

Body:
For example You have linked objects:

class obj {
    public $next;
}

$a = new obj();
$b = new obj();
$c = new obj();
$d = new obj();

$a->next = $b;
$b->next = $c;
$c->next = $d;
$d->next = null;

$obj = $a;

Your task is to make sure that the result is returned in the reverse sequence:

$d->next->$c->next->$b->next->$a = null;

Try to use the following code for yourself and fix it for your task

$new = null;

function recursive(&$new, &$obj) {

    if(is_object($new) && (spl_object_id($new)-1) === 0) {
        return null;
    }

    $getLast = function (&$obj) use(&$getLast) {
        if($obj->next === null) {
            return $obj;
        }

        return $getLast($obj->next);
    };

    $dropLast = function (&$obj) use(&$dropLast) {

        if(!isset($obj->next)) {
            return null;
        }

        if($obj->next->next === null) {
            $obj->next = null;
            return null;
        }

        return $dropLast($obj->next);
    };

    if($new === null) {
        $new = $getLast($obj);
        $dropLast($obj);
        $new->next = $getLast($obj);
    } else {
        $new->next = $getLast($obj);
    }

    $dropLast($obj);

    return recursive($new->next, $obj);
}

recursive($new, $obj);

echo '<pre>';
var_dump($new);
exit;


问:
How do I prevent deletion if related data still exists?
I need to make sure that my users can only delete their "question" if all "answers" to that question have already been deleted.

Questions and answers are stored in different collections. Here is some invalid code that explains what I'm looking for:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /questions/{question_id} {
      allow delete: if !exists(/databases/$(database)/documents/answers/{answer}).where(answer.question_id == question_id);
    }
  }
}
</code>```

I can't seem to figure out how to restrict the "exists" call to only those that are answers to the question.

I am open to all suggestions, even those that involve restructuring my data if necessary.

Thank you very much.

答:
You can't perform queries against collection using Firebase security rules.  You can only get() and check exists() of single documents when you know the full ID of that document.  So, what you're trying to do right now isn't possible.

What you can do instead is maintain a count or boolean flag in some other known document, and allow deletion when that count is the value indicates the condition by which the user is allowed to delete the document.

Body:
I need to make sure that my users can only delete their "question" if all "answers" to that question have already been deleted.

Questions and answers are stored in different collections. Here is some invalid code that explains what I'm looking for:

service cloud.firestore {
  match /databases/{database}/documents {
    match /questions/{question_id} {
      allow delete: if !exists(/databases/$(database)/documents/answers/{answer}).where(answer.question_id == question_id);
    }
  }
}

I can't seem to figure out how to restrict the "exists" call to only those that are answers to the question.

I am open to all suggestions, even those that involve restructuring my data if necessary.

Thank you very much.


问:
Ajax is not redirecting to the given URL
I'm having a hard time finding the error of why my ajax is not performing or possibly not redirecting to the given URL on my ajax code.

I've tried troubleshooting by putting an alert message inside my php code just to make sure if it's redirecting, but it's not showing anything.

```<code> $('#insert_form').on("submit", function(event) {
     event.preventDefault();
     alert("hi");
     $.ajax({

         url: "unit_update.php",
         method: "POST",
         data: $('#insert_form').serialize(),

         beforeSend: function() {
             $('#insert').val("Updating");
         },
         success: function(data) {
             alert("SUCCESSFULLY UPDATED");
             $('#insert_form')[0].reset();
             $('#edit_data_Modal').modal('hide');
             $('#unit').php(data);

             setTimeout(function() {
                 location.reload();
             }, 100);
         },
         error: function(data) {
             $('#ErrorDiv').show();
             $("#ERRMessage").text("ERROR UPDATING");
         }

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

I'm getting the "hi" and the "SUCCESSFULLY UPDATED" message coming from my ajax code after pressing the UPDATE button but I'm not getting the Updated result on my database.

答:
http://api.jquery.com/jquery.ajax/</p>

```<code>$('#insert_form').on("submit", function(event){
    event.preventDefault();
    alert("hi");
    $.ajax({
        type: "POST",
        url: "unit_update.php",
        data: $('#insert_form').serialize(),
        beforeSend: function() {
            $('#insert').val("Updating");
        }
    }).done(function(data) {
        alert("SUCCESSFULLY UPDATED");
        $('#insert_form')[0].reset();
        $('#edit_data_Modal').modal('hide');
        $('#unit').php(data);
        setTimeout(function() {
            location.reload();
        }, 100);
    }).fail(function() {
        $('#ErrorDiv').show();
        $("#ERRMessage").text("ERROR UPDATING");
    });
});
</code>```

Body:
I'm having a hard time finding the error of why my ajax is not performing or possibly not redirecting to the given URL on my ajax code.

I've tried troubleshooting by putting an alert message inside my php code just to make sure if it's redirecting, but it's not showing anything.

 $('#insert_form').on("submit", function(event) {
     event.preventDefault();
     alert("hi");
     $.ajax({

         url: "unit_update.php",
         method: "POST",
         data: $('#insert_form').serialize(),

         beforeSend: function() {
             $('#insert').val("Updating");
         },
         success: function(data) {
             alert("SUCCESSFULLY UPDATED");
             $('#insert_form')[0].reset();
             $('#edit_data_Modal').modal('hide');
             $('#unit').php(data);

             setTimeout(function() {
                 location.reload();
             }, 100);
         },
         error: function(data) {
             $('#ErrorDiv').show();
             $("#ERRMessage").text("ERROR UPDATING");
         }

     });
 });

I'm getting the "hi" and the "SUCCESSFULLY UPDATED" message coming from my ajax code after pressing the UPDATE button but I'm not getting the Updated result on my database.

Body:
http://api.jquery.com/jquery.ajax/

$('#insert_form').on("submit", function(event){
    event.preventDefault();
    alert("hi");
    $.ajax({
        type: "POST",
        url: "unit_update.php",
        data: $('#insert_form').serialize(),
        beforeSend: function() {
            $('#insert').val("Updating");
        }
    }).done(function(data) {
        alert("SUCCESSFULLY UPDATED");
        $('#insert_form')[0].reset();
        $('#edit_data_Modal').modal('hide');
        $('#unit').php(data);
        setTimeout(function() {
            location.reload();
        }, 100);
    }).fail(function() {
        $('#ErrorDiv').show();
        $("#ERRMessage").text("ERROR UPDATING");
    });
});


问:
Tkinter insert json data inside Text
I have a json file with names, email adress, surname etc..
I'm trying to put the data inside a Text box in tkinter.

I tried using Label like this:

```<code>with open('file.json','r') as inside:
    data = json.load(inside)

Label(Interface, text=data).place(x=100,y=100)
</code>```

What happened now is that there was only 1 line with all the information and it was not readable so I decided to go with the Text box

```<code>Text(Interface, state='normal',height = 20, width = 60).place(x=10,y=350)
Text.insert(INSERT,data)
</code>```

I get now the error:

```<code>TypeError: insert() missing 1 required positional argument: 'chars'
</code>```

I read that it only takes 2 arguments, but I tried with 3:

```<code>Text.insert(INSERT,data,"test")
</code>```

I get the error:

```<code>AttributeError: 'str' object has no attribute 'tk'
</code>```

I don't know what I am doing wrong in this case..

答:
I can't reproduce the problem you say you're having. The following runnable example seems to work with respect to displaying the JSON data in the file:</p>

```<code>import json
from tkinter import *

json_filename = 'inside.json'

Interface = Tk()

with open(json_filename, 'r') as inside:
    data = json.load(inside)

text = Text(Interface, state='normal', height=20, width=60)
text.place(x=10, y=50)
text.insert('1.0', str(data))

Interface.mainloop()
</code>```

Title: Tkinter insert json data inside Text

Body:
I have a json file with names, email adress, surname etc..
I'm trying to put the data inside a Text box in tkinter.

I tried using Label like this:

with open('file.json','r') as inside:
    data = json.load(inside)

Label(Interface, text=data).place(x=100,y=100)

What happened now is that there was only 1 line with all the information and it was not readable so I decided to go with the Text box

Text(Interface, state='normal',height = 20, width = 60).place(x=10,y=350)
Text.insert(INSERT,data)

I get now the error:

TypeError: insert() missing 1 required positional argument: 'chars'

I read that it only takes 2 arguments, but I tried with 3:

Text.insert(INSERT,data,"test")

I get the error:

AttributeError: 'str' object has no attribute 'tk'

I don't know what I am doing wrong in this case..

Body:
I can't reproduce the problem you say you're having. The following runnable example seems to work with respect to displaying the JSON data in the file:

import json
from tkinter import *

json_filename = 'inside.json'

Interface = Tk()

with open(json_filename, 'r') as inside:
    data = json.load(inside)

text = Text(Interface, state='normal', height=20, width=60)
text.place(x=10, y=50)
text.insert('1.0', str(data))

Interface.mainloop()


问:
ASP.NET Razor Pages dropdown list from DB
I'm writing Application on ASP.NET Razor Pages(It's my homerwork).
Topic of this app is "Library" I have adding,deleting,modifying etc.
What i'm trying to do is. When i'm adding a new book, when it's genre of book i want to use dropdown list from database. I have been searching for this but i didn't find working solution for me.

So my Book class is:
Book.cs

```<code>public class Book
{
    [Key]
    public int Id { get; set; }

    [Required]
    [Display(Name = "Tytuł")]

    public string Title { get; set; }
    [Required]
    [Display(Name = "Autor")]
    public string Author { get; set; }
    [Required]
    [Display(Name = "Gatunek")]
    public string Genre { get; set; }
    [Required]
    [Display(Name = "Rok Wydania")]
    public int ReleaseYear { get; set; }
    [Required]
    [Display(Name = "Okładka")]
    public string Cover { get; set; }
    [Required]
    [Display(Name = "Liczba Stron")]
    public int NumberOfPages { get; set; }
    [Required]
    [Display(Name = "Opis")]
    public string Description { get; set; }
}
</code>```

Next i have Genre class

Genre.cs

```<code>[Key]
    public int Id { get; set; }

    [Required]
    [Display(Name = "Gatunek")]
    public string Name { get; set; }
</code>```

I'm adding this to my ApplicationDbContext

ApplicationDbContext.cs

```<code>public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {

    }

    public DbSet<Book> Book { get; set; }
    public DbSet<Genre> Genre { get; set; }
</code>```

AddBook.cshtml.cs

```<code>[Authorize(Roles = SD.AdminEndUser)]
public class AddBookModel : PageModel
{
    private readonly ApplicationDbContext _db;

    [BindProperty]
    public Book Book { get; set; }

    public AddBookModel(ApplicationDbContext db)
    {
        _db = db;
    }

    public IActionResult OnGet()
    {
        return Page();
    }

    public async Task <IActionResult> OnPostAsync(ServiceType ServiceType)
    {
        if(!ModelState.IsValid)
        {
            return Page();
        }

        _db.Book.Add(Book);
        await _db.SaveChangesAsync();

        return RedirectToPage("Index");

    }
</code>```

And
AddBook.cs

```<code><form method="post">
<div class="border backgroundWhite">
    <div class="form-group row">
        <div class="col-2">
            <label asp-for="Book.Title"></label>
        </div>
        <div class="col-5">
            <input asp-for="Book.Title" class="form-control" />
        </div>
        <span asp-validation-for="Book.Title" class="text-danger"></span>
    </div>
    <div class="form-group row">
        <div class="col-2">
            <label asp-for="Book.Author"></label>
        </div>
        <div class="col-5">
            <input asp-for="Book.Author" class="form-control" />
        </div>
        <span asp-validation-for="Book.Author" class="text-danger"></span>
    </div>
    <div class="form-group row">
        <div class="col-2">
            <label asp-for="Book.Genre"></label>
        </div>
        <div class="col-5">
            <input asp-for="Book.Genre" class="form-control" />
        </div>
        <span asp-validation-for="Book.Genre" class="text-danger"></span>
    </div>
    <div class="form-group row">
        <div class="col-2">
            <label asp-for="Book.ReleaseYear"></label>
        </div>
        <div class="col-5">
            <input asp-for="Book.ReleaseYear" class="form-control" />
        </div>
        <span asp-validation-for="Book.ReleaseYear" class="text-danger"></span>
    </div>
    <div class="form-group row">
        <div class="col-2">
            <label asp-for="Book.NumberOfPages"></label>
        </div>
        <div class="col-5">
            <input asp-for="Book.NumberOfPages" class="form-control" />
        </div>
        <span asp-validation-for="Book.NumberOfPages" class="text-danger"></span>
    </div>
    <div class="form-group row">
        <div class="col-2">
            <label asp-for="Book.Cover"></label>
        </div>
        <div class="col-5">
            <input asp-for="Book.Cover" class="form-control" />
        </div>
        <span asp-validation-for="Book.Cover" class="text-danger"></span>
    </div>
    <div class="form-group row">
        <div class="col-2">
            <label asp-for="Book.Description"></label>
        </div>
        <div class="col-5">
            <input asp-for="Book.Description" class="form-control" />
        </div>
        <span asp-validation-for="Book.Description" class="text-danger"></span>
    </div>
    <div class="form-group row">
        <div class="col-5 offset-2">
           <partial name="_AddAndBackToListButton" />
        </div>
    </div>
</div>
</code>```

I have working connection with Db. I just don't know what i should do next to make dropdownlist. I'm not interested in solution with controllers!

Any ideas ?

Thank you for assistance!

答:
This is a possible repeat of:

How to write a simple Html.DropDownListFor()? (Answered Jun 16 '10 )

But anyway, I'll try and answer:

If you're writing it in Razor syntax, you can just use the same solution as the link above. Create an HtmlDropdownFor, and as the argument perform a LINQ query on your List<Genre> (list of of genres, or dictionary of genres, whichever iterable you might need)

Otherwise, you can just manually write a <select></select> input inside each of the HTML form that requires it. Obviously this is more time-consuming, but you can find more info  on how to do that, at w3 schools: HTML Form Elements, specifically the section about <select>

Body:
I'm writing Application on ASP.NET Razor Pages(It's my homerwork).
Topic of this app is "Library" I have adding,deleting,modifying etc.
What i'm trying to do is. When i'm adding a new book, when it's genre of book i want to use dropdown list from database. I have been searching for this but i didn't find working solution for me.

So my Book class is:
Book.cs

public class Book
{
    [Key]
    public int Id { get; set; }

    [Required]
    [Display(Name = "Tytuł")]

    public string Title { get; set; }
    [Required]
    [Display(Name = "Autor")]
    public string Author { get; set; }
    [Required]
    [Display(Name = "Gatunek")]
    public string Genre { get; set; }
    [Required]
    [Display(Name = "Rok Wydania")]
    public int ReleaseYear { get; set; }
    [Required]
    [Display(Name = "Okładka")]
    public string Cover { get; set; }
    [Required]
    [Display(Name = "Liczba Stron")]
    public int NumberOfPages { get; set; }
    [Required]
    [Display(Name = "Opis")]
    public string Description { get; set; }
}

Next i have Genre class

Genre.cs

[Key]
    public int Id { get; set; }

    [Required]
    [Display(Name = "Gatunek")]
    public string Name { get; set; }

I'm adding this to my ApplicationDbContext

ApplicationDbContext.cs

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {

    }

    public DbSet<Book> Book { get; set; }
    public DbSet<Genre> Genre { get; set; }

AddBook.cshtml.cs

[Authorize(Roles = SD.AdminEndUser)]
public class AddBookModel : PageModel
{
    private readonly ApplicationDbContext _db;

    [BindProperty]
    public Book Book { get; set; }

    public AddBookModel(ApplicationDbContext db)
    {
        _db = db;
    }

    public IActionResult OnGet()
    {
        return Page();
    }

    public async Task <IActionResult> OnPostAsync(ServiceType ServiceType)
    {
        if(!ModelState.IsValid)
        {
            return Page();
        }

        _db.Book.Add(Book);
        await _db.SaveChangesAsync();

        return RedirectToPage("Index");

    }

And
AddBook.cs

<form method="post">

            <input asp-for="Book.Title" class="form-control" />

            <input asp-for="Book.Author" class="form-control" />

            <input asp-for="Book.Genre" class="form-control" />

            <input asp-for="Book.ReleaseYear" class="form-control" />

            <input asp-for="Book.NumberOfPages" class="form-control" />

            <input asp-for="Book.Cover" class="form-control" />

            <input asp-for="Book.Description" class="form-control" />

           <partial name="_AddAndBackToListButton" />

I have working connection with Db. I just don't know what i should do next to make dropdownlist. I'm not interested in solution with controllers!

Any ideas ?

Thank you for assistance!


问:
Kafka Stream Exception: GroupAuthorizationException
I'm developing a Kafka-Stream application, which will read the message from input Kafka topic and filter unwanted data and push to output Kafka topic.

Kafka Stream Configuration:

```<code>@Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
public KafkaStreamsConfiguration kStreamsConfigs() {

    Map<String, Object> streamsConfiguration = new HashMap<>();
    streamsConfiguration.put(ConsumerConfig.GROUP_ID_CONFIG, "abcd");
    streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "QC-NormalizedEventProcessor-v1.0.0");
    streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "test:9072");
    streamsConfiguration.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    streamsConfiguration.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    streamsConfiguration.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE);
    streamsConfiguration.put(StreamsConfig.producerPrefix(ProducerConfig.ACKS_CONFIG), -1);
    streamsConfiguration.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 3);
    streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
    streamsConfiguration.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, kafkaConsumerProperties.getConsumerJKSFileLocation());
    streamsConfiguration.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, kafkaConsumerProperties.getConsumerJKSPwd());
    streamsConfiguration.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_SSL");
    streamsConfiguration.put(SASL_MECHANISM, "PLAIN");

    return new KafkaStreamsConfiguration(streamsConfiguration);
}
</code>```

KStream Filter Logic:

```<code>@Bean
public KStream<String, String> kStreamJson(StreamsBuilder builder) {

    KStream<String, String> stream = builder.stream(kafkaConsumerProperties.getConsumerTopic(), Consumed.with(Serdes.String(), Serdes.String()));
    /** Printing the source message */
    stream.foreach((key, value) -> LOGGER.info(THREAD_NO + Thread.currentThread().getId() + " *****Message From Input Topic: " + key + ": " + value));
    KStream<String, String> filteredDocument = stream.filter((k, v) -> filterCondition.test(k, v));

    filteredDocument.to(kafkaConsumerProperties.getProducerTopic(), Produced.with(Serdes.String(), Serdes.String()));
    /** After filtering printing the same message */
    filteredDocument.foreach((key, value) -> LOGGER.info(THREAD_NO + Thread.currentThread().getId() + " #####Filtered Document: " + key + ": " + value));
    return stream;
}
</code>```

While starting above spring based Kafka Stream application, i was getting below exception.

```<code>2019-05-27T07:58:36.018-0500 ERROR stream-thread [QC-NormalizedEventProcessor-v1.0.0-e9cb1bed-3d90-41f1-957a-4fc7efc12a02-StreamThread-1] Encountered the following unexpected Kafka exception during processing, this usually indicate Streams internal errors:
org.apache.kafka.common.errors.GroupAuthorizationException: Not authorized to access group: QC-NormalizedEventProcessor-v1.0.0
</code>```

Our Kafka Infra team given necessary permission to "group.id", using this same "group id" i can consume the message using other Kafka Consumer applications and I was using name as per my wish in "application.id". We are not adding/updating "application.id" in Kafka Access Control List.

Am really not sure we need to give any permission for "application.id" or am missing something in the Kafka Stream Configuration. Please advice.

Please Note: I have tried with using with "group.id" and without "group.id" in Kafka Stream Configuration, all the time i am getting same exception.

Thanks!
Bharathiraja Shanmugam

答: I am not at my desk but I think Streams sets the group.id to application.id.</p>

Body:
I'm developing a Kafka-Stream application, which will read the message from input Kafka topic and filter unwanted data and push to output Kafka topic.

Kafka Stream Configuration:

@Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
public KafkaStreamsConfiguration kStreamsConfigs() {

    Map<String, Object> streamsConfiguration = new HashMap<>();
    streamsConfiguration.put(ConsumerConfig.GROUP_ID_CONFIG, "abcd");
    streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "QC-NormalizedEventProcessor-v1.0.0");
    streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "test:9072");
    streamsConfiguration.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    streamsConfiguration.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    streamsConfiguration.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE);
    streamsConfiguration.put(StreamsConfig.producerPrefix(ProducerConfig.ACKS_CONFIG), -1);
    streamsConfiguration.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 3);
    streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
    streamsConfiguration.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, kafkaConsumerProperties.getConsumerJKSFileLocation());
    streamsConfiguration.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, kafkaConsumerProperties.getConsumerJKSPwd());
    streamsConfiguration.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_SSL");
    streamsConfiguration.put(SASL_MECHANISM, "PLAIN");

    return new KafkaStreamsConfiguration(streamsConfiguration);
}

KStream Filter Logic:

@Bean
public KStream<String, String> kStreamJson(StreamsBuilder builder) {

    KStream<String, String> stream = builder.stream(kafkaConsumerProperties.getConsumerTopic(), Consumed.with(Serdes.String(), Serdes.String()));
    /** Printing the source message */
    stream.foreach((key, value) -> LOGGER.info(THREAD_NO + Thread.currentThread().getId() + " *****Message From Input Topic: " + key + ": " + value));
    KStream<String, String> filteredDocument = stream.filter((k, v) -> filterCondition.test(k, v));

    filteredDocument.to(kafkaConsumerProperties.getProducerTopic(), Produced.with(Serdes.String(), Serdes.String()));
    /** After filtering printing the same message */
    filteredDocument.foreach((key, value) -> LOGGER.info(THREAD_NO + Thread.currentThread().getId() + " #####Filtered Document: " + key + ": " + value));
    return stream;
}

While starting above spring based Kafka Stream application, i was getting below exception.

2019-05-27T07:58:36.018-0500 ERROR stream-thread [QC-NormalizedEventProcessor-v1.0.0-e9cb1bed-3d90-41f1-957a-4fc7efc12a02-StreamThread-1] Encountered the following unexpected Kafka exception during processing, this usually indicate Streams internal errors:
org.apache.kafka.common.errors.GroupAuthorizationException: Not authorized to access group: QC-NormalizedEventProcessor-v1.0.0

Our Kafka Infra team given necessary permission to "group.id", using this same "group id" i can consume the message using other Kafka Consumer applications and I was using name as per my wish in "application.id". We are not adding/updating "application.id" in Kafka Access Control List.

Am really not sure we need to give any permission for "application.id" or am missing something in the Kafka Stream Configuration. Please advice.

Please Note: I have tried with using with "group.id" and without "group.id" in Kafka Stream Configuration, all the time i am getting same exception.

Thanks!
Bharathiraja Shanmugam


问:
Problem with connect to postgresql with java and intellij
I have problem with my project. I'm trying start my application with postgresql and I have error. I can not call build gradle, always finish BUILD FAILED. I show you the code.
I do not understand why this error because I threw in a week without a problem and gradle build was also successful. I just changed the application properties file back to MySQL. When I again wanted to use postgresql, these errors pop up. I am asking for help and thank you for every answer

My application properties

```<code>spring.jpa.hibernate.ddl-auto=update
spring.jpa.database=postgresql
spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.username=${JDBC_DATABASE_USERNAME}
spring.datasource.password=${JDBC_DATABASE_PASSWORD}
</code>```

my build.gradle

```<code>plugins {
    id 'org.springframework.boot' version '2.1.3.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'
</code>```

//apply plugin: 'war'

```<code>group = 'com.crud'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    compileOnly 'org.projectlombok:lombok:1.18.8'
    annotationProcessor 'org.projectlombok:lombok:1.18.8'
    implementation 'org.springframework.boot:spring-boot-starter-data-
   jpa'
    //runtimeOnly 'mysql:mysql-connector-java'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'io.springfox:springfox-swagger2:2.7.0'
    implementation 'io.springfox:springfox-swagger-ui:2.7.0'
    testImplementation 'org.springframework.boot:spring-boot-starter-
   test'
    runtimeOnly 'org.postgresql:postgresql'
    implementation 'org.springframework.boot:spring-boot-starter-
   mail:2.1.5.RELEASE'
    //providedRuntime 'org.springframework.boot:spring-boot-starter-
    tomcat'
}
</code>```

When I run application...

```<code>2019-05-26 19:19:36.139  INFO 14288 --- [           main]
o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-05-26 19:19:36.152  INFO 14288 --- [           main]
ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-
run your application with 'debug' enabled.
2019-05-26 19:19:36.162 ERROR 14288 --- [           main]
o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name
'org.springframework.boot.autoconfigure.
orm.jpa.HibernateJpaConfiguration':
Unsatisfied dependency expressed through constructor parameter 0; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSource' defined in class path resource

 [org/springframework/boot/autoconfigure
/jdbc/DataSourceConfiguration$Hikari.c
lass]: Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
 java.lang.IllegalArgumentException: URL must start with 'jdbc'
at

org.springframework.beans.factory.
support.ConstructorResolver.createArgumentA
rray(ConstructorResolver.java:769) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.autowireConstru
ctor(ConstructorResolver.java:218) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
autowireConstructor(AbstractAutowireCapableBeanFactory.java:1325) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1171) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
 support.AbstractAutowireCapableBeanFactory.
 createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
 5.1.5.RELEASE.jar:5.1.5.RELEASE]
 at

org.springframework.beans.factory.
support.AbstractBeanFactory.lambda$doGetBea
n$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.getSin
gleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.doGetBean(Abstr
actBeanFactory.java:318) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.getBean(Abstrac
tBeanFactory.java:199) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.ConstructorResolver.instantiateUsin
gFactoryMethod(ConstructorResolver.java:392) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.

instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.
java:1305)
 ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.
getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractBeanFactory.
doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.context.support
.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105)
~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.context.support
.AbstractApplicationContext.
finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~
[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
 org.springframework.context.support
.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.boot.web.servlet.
context.ServletWebServerApplicationContext.
refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.SpringApplication
.refresh(SpringApplication.java:775) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
 org.springframework.boot.SpringApplication
.refreshContext(SpringApplication.java:397) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.SpringApplication
.run(SpringApplication.java:316) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.SpringApplication
.run(SpringApplication.java:1260) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
 org.springframework.boot.SpringApplication
.run(SpringApplication.java:1248) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
com.crud.tasks.TasksApplication.
main(TasksApplication.java:11) ~[classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dataSource' defined in class path resource

[org/springframework/boot/autoconfigure
/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
java.lang.IllegalArgumentException: URL must start with 'jdbc'
at
org.springframework.beans.factory.
support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.ConstructorResolver.
instantiateUsingFactoryMethod(ConstructorResolver.java:607) ~[spring-
beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
instantiateUsingFactoryMethod
(AbstractAutowireCapableBeanFactory.java:1305) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractBeanFactory.
lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.
getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
getBean(AbstractBeanFactory.java:199) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.config
.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultListableBeanFactory.
doResolveDependency(DefaultListableBeanFactory.java:1247) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
 support.DefaultListableBeanFactory.
 resolveDependency(DefaultListableBeanFactory.java:1167) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.support.
ConstructorResolver.
resolveAutowiredArgument(ConstructorResolver.java:857) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.
createArgumentArray(ConstructorResolver.java:760) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 28 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed
to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
java.lang.IllegalArgumentException: URL must start with 'jdbc'
at

org.springframework.beans.factory.
support.SimpleInstantiationStrategy.
instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 42 common frames omitted
Caused by: java.lang.IllegalArgumentException: URL must start with 'jdbc'
at org.springframework.util.Assert.isTrue(Assert.java:118) ~[spring-core-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.boot.jdbc.DatabaseDriver.
fromJdbcUrl(DatabaseDriver.java:280) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceProperties.
determineDriverClassName(DataSourceProperties.java:230) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.autoconfigure
.jdbc.DataSourceProperties.
initializeDataSourceBuilder(DataSourceProperties.java:176) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceConfiguration.
createDataSource(DataSourceConfiguration.java:43) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceConfiguration$Hikari.
dataSource(DataSourceConfiguration.java:83) ~[spring-boot-autoconfigure-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) ~[na:na]
at
java.base/jdk.internal.reflect.
NativeMethodAccessorImpl.
invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at
java.base/jdk.internal.reflect.
DelegatingMethodAccessorImpl.
invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at
org.springframework.beans.
factory.support.SimpleInstantiationStrategy.
instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 43 common frames omitted
</code>```

and when I run gradle build...

```<code>Task :test

com.crud.tasks.TasksApplicationTests > contextLoads FAILED
java.lang.IllegalStateException
    Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException
        Caused by:
org.springframework.beans.factory.BeanCreationException
            Caused by:
org.springframework.beans.BeanInstantiationException
                Caused by: java.lang.IllegalArgumentException

7 tests completed, 1 failed
</code>```

答:
I do not need it locally, the problem is that when I send to the heroku repository such application.properties, my application does not work. Today I used the friend's lower prompts and set JDBC_DATABASE_URL alone, then the terminal shows me this error

```<code>Field repository in com.crud.tasks.com.crud.tasks.service.DbService required a bean
of type 'com.crud.tasks.com.crud.tasks.repository.TaskRepository' that could not be
found.

The injection point has the following annotations:
- @ org.springframework.beans.factory.annotation.Autowired (required = true)

Action:

Consider defining a bean of type
'com.crud.tasks.com.crud.tasks.repository.TaskRepository' in your configuration.
</code>```

but I did not change anything in the code and everything was fine with the last
successful deployment plan

Body:
I have problem with my project. I'm trying start my application with postgresql and I have error. I can not call build gradle, always finish BUILD FAILED. I show you the code.
I do not understand why this error because I threw in a week without a problem and gradle build was also successful. I just changed the application properties file back to MySQL. When I again wanted to use postgresql, these errors pop up. I am asking for help and thank you for every answer

My application properties

spring.jpa.hibernate.ddl-auto=update
spring.jpa.database=postgresql
spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.username=${JDBC_DATABASE_USERNAME}
spring.datasource.password=${JDBC_DATABASE_PASSWORD}

my build.gradle

plugins {
    id 'org.springframework.boot' version '2.1.3.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

//apply plugin: 'war'

group = 'com.crud'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    compileOnly 'org.projectlombok:lombok:1.18.8'
    annotationProcessor 'org.projectlombok:lombok:1.18.8'
    implementation 'org.springframework.boot:spring-boot-starter-data-
   jpa'
    //runtimeOnly 'mysql:mysql-connector-java'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'io.springfox:springfox-swagger2:2.7.0'
    implementation 'io.springfox:springfox-swagger-ui:2.7.0'
    testImplementation 'org.springframework.boot:spring-boot-starter-
   test'
    runtimeOnly 'org.postgresql:postgresql'
    implementation 'org.springframework.boot:spring-boot-starter-
   mail:2.1.5.RELEASE'
    //providedRuntime 'org.springframework.boot:spring-boot-starter-
    tomcat'
}

When I run application...

2019-05-26 19:19:36.139  INFO 14288 --- [           main]
o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-05-26 19:19:36.152  INFO 14288 --- [           main]
ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-
run your application with 'debug' enabled.
2019-05-26 19:19:36.162 ERROR 14288 --- [           main]
o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name
'org.springframework.boot.autoconfigure.
orm.jpa.HibernateJpaConfiguration':
Unsatisfied dependency expressed through constructor parameter 0; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSource' defined in class path resource

 [org/springframework/boot/autoconfigure
/jdbc/DataSourceConfiguration$Hikari.c
lass]: Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
 java.lang.IllegalArgumentException: URL must start with 'jdbc'
at

org.springframework.beans.factory.
support.ConstructorResolver.createArgumentA
rray(ConstructorResolver.java:769) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.autowireConstru
ctor(ConstructorResolver.java:218) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
autowireConstructor(AbstractAutowireCapableBeanFactory.java:1325) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1171) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
 support.AbstractAutowireCapableBeanFactory.
 createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
 5.1.5.RELEASE.jar:5.1.5.RELEASE]
 at

org.springframework.beans.factory.
support.AbstractBeanFactory.lambda$doGetBea
n$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.getSin
gleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.doGetBean(Abstr
actBeanFactory.java:318) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.getBean(Abstrac
tBeanFactory.java:199) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.ConstructorResolver.instantiateUsin
gFactoryMethod(ConstructorResolver.java:392) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.

instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.
java:1305)
 ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.
getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractBeanFactory.
doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.context.support
.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105)
~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.context.support
.AbstractApplicationContext.
finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~
[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
 org.springframework.context.support
.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.boot.web.servlet.
context.ServletWebServerApplicationContext.
refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.SpringApplication
.refresh(SpringApplication.java:775) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
 org.springframework.boot.SpringApplication
.refreshContext(SpringApplication.java:397) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.SpringApplication
.run(SpringApplication.java:316) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.SpringApplication
.run(SpringApplication.java:1260) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
 org.springframework.boot.SpringApplication
.run(SpringApplication.java:1248) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
com.crud.tasks.TasksApplication.
main(TasksApplication.java:11) ~[classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dataSource' defined in class path resource

[org/springframework/boot/autoconfigure
/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
java.lang.IllegalArgumentException: URL must start with 'jdbc'
at
org.springframework.beans.factory.
support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.ConstructorResolver.
instantiateUsingFactoryMethod(ConstructorResolver.java:607) ~[spring-
beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
instantiateUsingFactoryMethod
(AbstractAutowireCapableBeanFactory.java:1305) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractBeanFactory.
lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.
getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
getBean(AbstractBeanFactory.java:199) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.config
.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultListableBeanFactory.
doResolveDependency(DefaultListableBeanFactory.java:1247) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
 support.DefaultListableBeanFactory.
 resolveDependency(DefaultListableBeanFactory.java:1167) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.support.
ConstructorResolver.
resolveAutowiredArgument(ConstructorResolver.java:857) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.
createArgumentArray(ConstructorResolver.java:760) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 28 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed
to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
java.lang.IllegalArgumentException: URL must start with 'jdbc'
at

org.springframework.beans.factory.
support.SimpleInstantiationStrategy.
instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 42 common frames omitted
Caused by: java.lang.IllegalArgumentException: URL must start with 'jdbc'
at org.springframework.util.Assert.isTrue(Assert.java:118) ~[spring-core-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.boot.jdbc.DatabaseDriver.
fromJdbcUrl(DatabaseDriver.java:280) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceProperties.
determineDriverClassName(DataSourceProperties.java:230) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.autoconfigure
.jdbc.DataSourceProperties.
initializeDataSourceBuilder(DataSourceProperties.java:176) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceConfiguration.
createDataSource(DataSourceConfiguration.java:43) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceConfiguration$Hikari.
dataSource(DataSourceConfiguration.java:83) ~[spring-boot-autoconfigure-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) ~[na:na]
at
java.base/jdk.internal.reflect.
NativeMethodAccessorImpl.
invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at
java.base/jdk.internal.reflect.
DelegatingMethodAccessorImpl.
invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at
org.springframework.beans.
factory.support.SimpleInstantiationStrategy.
instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 43 common frames omitted

and when I run gradle build...

Task :test

com.crud.tasks.TasksApplicationTests > contextLoads FAILED
java.lang.IllegalStateException
    Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException
        Caused by:
org.springframework.beans.factory.BeanCreationException
            Caused by:
org.springframework.beans.BeanInstantiationException
                Caused by: java.lang.IllegalArgumentException

7 tests completed, 1 failed

Body:
I do not need it locally, the problem is that when I send to the heroku repository such application.properties, my application does not work. Today I used the friend's lower prompts and set JDBC_DATABASE_URL alone, then the terminal shows me this error

Field repository in com.crud.tasks.com.crud.tasks.service.DbService required a bean
of type 'com.crud.tasks.com.crud.tasks.repository.TaskRepository' that could not be
found.

The injection point has the following annotations:
- @ org.springframework.beans.factory.annotation.Autowired (required = true)

Action:

Consider defining a bean of type
'com.crud.tasks.com.crud.tasks.repository.TaskRepository' in your configuration.

but I did not change anything in the code and everything was fine with the last
successful deployment plan


问:
JSDOM's querySelectorAll returned too many XML elements
Node.js version: 10.15.3
jsdom version: 15.1.0

const fs = require('fs');
const jsdom = require("jsdom");
const { JSDOM } = jsdom;

const xmlFile = fs.readFileSync("question.xml", "utf8");
const dom = new JSDOM(xmlFile);
const all = dom.window.document.querySelectorAll("S");
console.log(all);
```

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
    <Foo>
        <FooBar>
            <S a="string1" b="string2" c="string3"/>
        </FooBar>
    </Foo>
    <Foo>
        <FooBar>
            <S a="string1" b="string2"/>
            <S a="string1"/>
        </FooBar>
    </Foo>
</code>```

querySelectorAll("S") returns 7 HTML elements when there are clearly only 3. What makes it even stranger is if I rename the xml elements from S to F, it works correctly and querySelectorAll("F") finds only 3 elements. What is the cause of this inconsistency?

答:
By default, JSDOM interprets the markup you give to it as HTML. So it interprets your XML as HTML, and you get funky results. Remember that the HTML specification provides rules about how to make sense of broken HTML so when JSDOM reads your XML, it applies the rules and tries to get some sensible document out of it. If I take your XML and your code but I add

```<code>console.log(dom.window.document.documentElement.innerHTML);
</code>```

just after the line that assigns dom, I get this serialized HTML:

```<code><head></head><body><foo>
        <foobar>
            <s a="string1" b="string2" c="string3">
        </s></foobar><s a="string1" b="string2" c="string3">
    </s></foo><s a="string1" b="string2" c="string3">
    <foo>
        <foobar>
            <s a="string1" b="string2">
            <s a="string1">
        </s></s></foobar><s a="string1" b="string2"><s a="string1">
    </s></s></foo><s a="string1" b="string2"><s a="string1">
</s></s></s></body>
</code>```

Look at what happens to s. (Reminder: HTML element names are case-insensitive so S and s are the same HTML element.)

By the way, the reason you get different behavior with S by opposition to F is because S is an actual HTML element, whereas F is not. So JSDOM applies different rules to S than F when it tries to make sense of your document as HTML.

In order for JSDOM to interpret your document as XML, you can do this:

```<code>const dom = new JSDOM(xmlFile, { contentType: "text/xml" });
</code>```

But note that your document is not well-formed XML because it has more than one root element. The XML specification does not provide any rule for making sense of documents that are not well-formed. A document which is not well-formed is essentially not XML. So JSDOM will just reject your document. You need to edit it so that it has only one root element. For instance, this would work:

```<code><?xml version="1.0" encoding="utf-8"?>
<doc>
   <Foo>
        <FooBar>
            <S a="string1" b="string2" c="string3"/>
        </FooBar>
    </Foo>
    <Foo>
        <FooBar>
            <S a="string1" b="string2"/>
            <S a="string1"/>
        </FooBar>
    </Foo>
</doc>
</code>```

I've just wrapped the two Foo elements in a doc element which forms the single root required by XML.

Body:
Node.js version: 10.15.3
jsdom version: 15.1.0

const fs = require('fs');
const jsdom = require("jsdom");
const { JSDOM } = jsdom;

const xmlFile = fs.readFileSync("question.xml", "utf8");
const dom = new JSDOM(xmlFile);
const all = dom.window.document.querySelectorAll("S");
console.log(all);

<?xml version="1.0" encoding="utf-8"?>
    <Foo>
        <FooBar>
            <S a="string1" b="string2" c="string3"/>
        </FooBar>
    </Foo>
    <Foo>
        <FooBar>
            <S a="string1" b="string2"/>
            <S a="string1"/>
        </FooBar>
    </Foo>

querySelectorAll("S") returns 7 HTML elements when there are clearly only 3. What makes it even stranger is if I rename the xml elements from S to F, it works correctly and querySelectorAll("F") finds only 3 elements. What is the cause of this inconsistency?

Body:
By default, JSDOM interprets the markup you give to it as HTML. So it interprets your XML as HTML, and you get funky results. Remember that the HTML specification provides rules about how to make sense of broken HTML so when JSDOM reads your XML, it applies the rules and tries to get some sensible document out of it. If I take your XML and your code but I add

console.log(dom.window.document.documentElement.innerHTML);

just after the line that assigns dom, I get this serialized HTML:

<head></head><body><foo>
        <foobar>
            <s a="string1" b="string2" c="string3">
        </s></foobar><s a="string1" b="string2" c="string3">
    </s></foo><s a="string1" b="string2" c="string3">
    <foo>
        <foobar>
            <s a="string1" b="string2">
            <s a="string1">
        </s></s></foobar><s a="string1" b="string2"><s a="string1">
    </s></s></foo><s a="string1" b="string2"><s a="string1">
</s></s></s></body>

Look at what happens to s. (Reminder: HTML element names are case-insensitive so S and s are the same HTML element.)

By the way, the reason you get different behavior with S by opposition to F is because S is an actual HTML element, whereas F is not. So JSDOM applies different rules to S than F when it tries to make sense of your document as HTML.

In order for JSDOM to interpret your document as XML, you can do this:

const dom = new JSDOM(xmlFile, { contentType: "text/xml" });

But note that your document is not well-formed XML because it has more than one root element. The XML specification does not provide any rule for making sense of documents that are not well-formed. A document which is not well-formed is essentially not XML. So JSDOM will just reject your document. You need to edit it so that it has only one root element. For instance, this would work:

<?xml version="1.0" encoding="utf-8"?>
<doc>
   <Foo>
        <FooBar>
            <S a="string1" b="string2" c="string3"/>
        </FooBar>
    </Foo>
    <Foo>
        <FooBar>
            <S a="string1" b="string2"/>
            <S a="string1"/>
        </FooBar>
    </Foo>
</doc>

I've just wrapped the two Foo elements in a doc element which forms the single root required by XML.


问:
Default value for user ForeignKey with Django admin
```<code>author = models.ForeignKey(User)
</code>```

Is there any way I can set the default value of this field to automatically select the logged in user? I know you can do this in the save method but my client has requested that it automatically defaults to the logged in user at edit time to avoid confusion.

This article goes into how to update it during save, just not at edit time.

答:
You could override the Admin part of your model to not display the author if the object that you are editing is new because it should be set to the current user and only if you are editing an object does the field show?

You would do this by overriding the get_form method of ModelAdmin.

Body:
author = models.ForeignKey(User)

Is there any way I can set the default value of this field to automatically select the logged in user? I know you can do this in the save method but my client has requested that it automatically defaults to the logged in user at edit time to avoid confusion.

This article goes into how to update it during save, just not at edit time.


问:
A result was returned when none was expected. SpringBoot/Postgresql
I want to select only last row in my table and return this int in my variable.
This is my method in my Repository :

```<code>@Transactional
@Modifying
@Query(value="SELECT category_id FROM category ORDER BY category_id DESC LIMIT 1\r\n", nativeQuery = true)
int  selectLastRecord();
</code>```

And when I call method with this code:

```<code>int categoryId = this.categoryRepository.selectLastRecord();
</code>```

I have the error:

```<code>org.postgresql.util.PSQLException: A result was returned when none was expected.
</code>```

答:
Queries that require a @Modifying annotation include INSERT, UPDATE, DELETE, and DDL statements.

Adding @Modifying annotation indicates the query is not for a SELECT query.

So remove @Modifying.

Reference Modifying

Body:
I want to select only last row in my table and return this int in my variable.
This is my method in my Repository :

@Transactional
@Modifying
@Query(value="SELECT category_id FROM category ORDER BY category_id DESC LIMIT 1\r\n", nativeQuery = true)
int  selectLastRecord();

And when I call method with this code:

int categoryId = this.categoryRepository.selectLastRecord();

I have the error:

org.postgresql.util.PSQLException: A result was returned when none was expected.


问:
How to stop AppBarLayout minimizing on scroll up?
Im trying to stop the navbar which contains search and menu from minimizing when i scroll up. I have attached images of before and after user scrolls up.

I cannot find relevant element. Im not sure what its called.

答:
I needed to add the following code</p>

```<code><android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbarEvents"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="enterAlways" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:tag="tab_indicator_accent_color,bg_primary_color" />

    </android.support.design.widget.AppBarLayout>
</code>```

Body:
I needed to add the following code

<android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbarEvents"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="enterAlways" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:tag="tab_indicator_accent_color,bg_primary_color" />

    </android.support.design.widget.AppBarLayout>


问:
How to generate Documents on-fly using PHP for microsoft and openoffice together?
I want to generate doc (or odt) and xls document files using PHP, The problems is that both Microsoft office and open office should be able to open the files without warning, nicely and similar using any document reader.

Also there are images inside the documents that should be saved as embedded file, does anybody know any component, class or way that can help me?

答:
OpenTBS is a PHP tool that can read an modify the contents of any OpenDocument files (ODT, ODS, ODG, ODF, ODM, ODP, OTT, OTS, OTG, OTP). But also OpenXML files (DOCX, XLSX, PPTX).

No temporary files needed, no command lines, all in PHP.