问:
Programmatically resize a view in Eclipse
I'm testing an non-e4 RCP application using SWTBot and I need to change the size of my view. (Move the sash-bar)

I unsuccessfully tried

Resize my view using SWTBot (no such api)

Resize my view using Eclipse 3 API (no supported)

Resize my view using underlying e4 model (resizing not working)

e4 model seams to be promising, but I'm missing something, so it doesn't work.

I can

Get MPart of my view: view = ePartService.findPart(ID)

Get MTrimmedWindow: window = (view as EObject).eContainer as MTrimmedWindow

I can't

locale correct MPartSashContainer

move sash-bar with setContainerData()

I would like to know

How can I move from MPart to its direct parent (e.g. MPartStack)

Why common EObject methods like eContainer() are not present on M... objects?

答:
Ok, I found a solution myself.

The thing is, that the view is not a part of the e4 UI-Tree. view.eContainer is directly the MWindow. To be placed at the right spot the view is connected to the MPlaceholder, that is a part of the e4 UI-Tree and has getParent() != null.

In order to resize a view the steps are:

Show view

Find MPlaceholder of the view

Find MPartStack and `MPartSashContainer´ object

Set containerData

Redraw widget (yes, auto-update seam not to work in this case)

Example:

```<code>EModelService modelService = PlatformUI.getWorkbench().getService(EModelService.class);
EPartService  partService  = PlatformUI.getWorkbench().getService(EPartService.class);

// Show view
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
page.showView(MyView.ID, null, IWorkbenchPage.VIEW_ACTIVATE);

MPart view = partService.findPart(MyView.ID);
// view.getParent() => null, because 'view' is not a part of the e4 UI-model!
// It is connected to the Model using MPlaceholder

// Let's find the placeholder
MWindow window = (MWindow)(((EObject)eView).eContainer);
MPlaceholder placeholder = modelService.findPlaceholderFor(window, view);

MUIElement element = placeholder;
MPartStack partStack = null;
while (element != null) {
    // This may not suite your configuration of views/stacks/sashes
    if (element instanceof MPartStack && ((Object)element.parent) instanceof MPartSashContainer) {
            partStack = (MPartStack)element;
            break;
        }
        element = element.parent;
    }
}
if (partStack == null) { /* handle error */ }

// Now let's change the width weights
for (MUIElement element : partStack.getParent().getChildren()) {
    if (element == partStack) {
        element.setContainerData("50"); // Width for my view
    } else {
        element.setContainerData("25"); // Widths for other views & editors
    }
}

// Surprisingly I had to redraw tho UI manually
// There is for sure a better way to do it. Here is my (quick & very dirty):
partStack.toBeRendered = false
partStack.toBeRendered = true
</code>```

Body:
Ok, I found a solution myself.

The thing is, that the view is not a part of the e4 UI-Tree. view.eContainer is directly the MWindow. To be placed at the right spot the view is connected to the MPlaceholder, that is a part of the e4 UI-Tree and has getParent() != null.

In order to resize a view the steps are:

Show view

Find MPlaceholder of the view

Find MPartStack and `MPartSashContainer´ object

Set containerData

Redraw widget (yes, auto-update seam not to work in this case)

Example:

EModelService modelService = PlatformUI.getWorkbench().getService(EModelService.class);
EPartService  partService  = PlatformUI.getWorkbench().getService(EPartService.class);

// Show view
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
page.showView(MyView.ID, null, IWorkbenchPage.VIEW_ACTIVATE);

MPart view = partService.findPart(MyView.ID);
// view.getParent() => null, because 'view' is not a part of the e4 UI-model!
// It is connected to the Model using MPlaceholder

// Let's find the placeholder
MWindow window = (MWindow)(((EObject)eView).eContainer);
MPlaceholder placeholder = modelService.findPlaceholderFor(window, view);

MUIElement element = placeholder;
MPartStack partStack = null;
while (element != null) {
    // This may not suite your configuration of views/stacks/sashes
    if (element instanceof MPartStack && ((Object)element.parent) instanceof MPartSashContainer) {
            partStack = (MPartStack)element;
            break;
        }
        element = element.parent;
    }
}
if (partStack == null) { /* handle error */ }

// Now let's change the width weights
for (MUIElement element : partStack.getParent().getChildren()) {
    if (element == partStack) {
        element.setContainerData("50"); // Width for my view
    } else {
        element.setContainerData("25"); // Widths for other views & editors
    }
}

// Surprisingly I had to redraw tho UI manually
// There is for sure a better way to do it. Here is my (quick & very dirty):
partStack.toBeRendered = false
partStack.toBeRendered = true


来源: stackexchange

问:
like operater not working on hive,what to do?
select * from cancel where deduction_percentage like '%100% cancellation charge%';

SemanticException [Error 10014]: Line 1:27 Wrong arguments ''%100% cancellation charge%'': No matching method for class org.apache.hadoop.hive.ql.udf.UDFLike with (array, string). Possible choices: FUNC(string, string)

答:
Your deduction_percentage seems like array datatype. The query you written will work for string datatype fields only.</p>

```<code>select * from cancel where concat_ws(',',deduction_percentage) like '%100% cancellation charge%';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Your deduction_percentage seems like array datatype. The query you written will work for string datatype fields only.

select * from cancel where concat_ws(',',deduction_percentage) like '%100% cancellation charge%';


问:
Java: Mixin implementation classes
I've seen in several code libraries classes named Mixin with comments like:

```<code>//Mixin style implementation
public class DetachableMixin implements Detachable {}
</code>```

Which is the concept under this style of implementations?

答:
Here is a qoute from Joshua Bloch "Efective Java" (I don't think, I could explain it better myself):

Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type
  that a class can implement in addition to its “primary type” to declare that it provides
  some optional behavior. For example, Comparable is a mixin interface that
  allows a class to declare that its instances are ordered with respect to other mutually
  comparable objects. Such an interface is called a mixin because it allows the
  optional functionality to be “mixed in” to the type’s primary functionality.
  Abstract classes can’t be used to define mixins for the same reason that they can’t
  be retrofitted onto existing classes: a class cannot have more than one parent, and
  there is no reasonable place in the class hierarchy to insert a mixin.

Title: Java: Mixin implementation classes

Body:
I've seen in several code libraries classes named Mixin with comments like:

//Mixin style implementation
public class DetachableMixin implements Detachable {}

Which is the concept under this style of implementations?


问:
Showing data from pickerview
I have designed a tableview cell with a textfield for pickerview. AndI have loaded 2 of those cells in my tableview. In order to show data from the pickerview this is what I did in cellForRowAt...

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
        cell.delegate = self

        let pickerView = UIPickerView()
        pickerView.delegate = self
        cell.pickerField.inputView = pickerView
        cell.pickerField.text = myData[0]//myData is an array with values from 1-10

        myCell = cell //The issue seems to be here.

        return cell
    }
</code>```

And the picker view methods I have given like this...

```<code>func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return myData.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return myData[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    myCell.pickerField.text = myData[row]
}
</code>```

The issue is if I click on the 2nd pickerview the value I select is assigned to the textfield. But when I select a value from the 1st field that value is shown in the 2nd field instead of 1st.

EDIT: This is my code in cellForRowAt...

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
    cell.delegate = self

    let pickerView = MyPickerView()
    pickerView.cell = cell
    pickerView.delegate = self
    cell.qtyPickerField.inputView = pickerView

    return cell
}
</code>```

This is the picker view methods...

```<code>        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }

        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return myData.count
        }

        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return myData[row]
        }

        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

            if pickerView is MyPickerView {

                if let cell = (pickerView as! MyPickerView).cell {
                    let indexpath = self.tableview.indexPath(for: cell)
                    if let index = indexpath {
                        (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]

    }
    }
    }

}
</code>```

EDIT 2 . code of pickerview didSelectRow

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

if pickerView is MyPickerView {

        if let cell = (pickerView as! MyPickerView).cell {

            cell.qtyPickerField.text = myData[row]
            let indexPath = self.tableview.indexPath(for: cell)
            if let index = indexPath {
                (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]
            }
        }

    }
}
</code>```

答:
Problem starts with

```<code>myCell = cell;
</code>```

You will always have instance of latest cell here. So assigning value in delegate will update textField in latest call.

what you can do in pickerView delegate is (Noob way though :p)

```<code>if let cell = tableView.cellForRow(at: INDEXPATH_OF_RESPECTIVE_ROW) {
    "get text field instance and assign value."
}
</code>```

Title: Showing data from pickerview

Body:
I have designed a tableview cell with a textfield for pickerview. AndI have loaded 2 of those cells in my tableview. In order to show data from the pickerview this is what I did in cellForRowAt...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
        cell.delegate = self

        let pickerView = UIPickerView()
        pickerView.delegate = self
        cell.pickerField.inputView = pickerView
        cell.pickerField.text = myData[0]//myData is an array with values from 1-10

        myCell = cell //The issue seems to be here.

        return cell
    }

And the picker view methods I have given like this...

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return myData.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return myData[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    myCell.pickerField.text = myData[row]
}

The issue is if I click on the 2nd pickerview the value I select is assigned to the textfield. But when I select a value from the 1st field that value is shown in the 2nd field instead of 1st.

EDIT: This is my code in cellForRowAt...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
    cell.delegate = self

    let pickerView = MyPickerView()
    pickerView.cell = cell
    pickerView.delegate = self
    cell.qtyPickerField.inputView = pickerView

    return cell
}

This is the picker view methods...

        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }

        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return myData.count
        }

        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return myData[row]
        }

        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

            if pickerView is MyPickerView {

                if let cell = (pickerView as! MyPickerView).cell {
                    let indexpath = self.tableview.indexPath(for: cell)
                    if let index = indexpath {
                        (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]

    }
    }
    }

}

EDIT 2 . code of pickerview didSelectRow

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

if pickerView is MyPickerView {

        if let cell = (pickerView as! MyPickerView).cell {

            cell.qtyPickerField.text = myData[row]
            let indexPath = self.tableview.indexPath(for: cell)
            if let index = indexPath {
                (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]
            }
        }

    }
}

Body:
Problem starts with

myCell = cell;

You will always have instance of latest cell here. So assigning value in delegate will update textField in latest call.

what you can do in pickerView delegate is (Noob way though :p)

if let cell = tableView.cellForRow(at: INDEXPATH_OF_RESPECTIVE_ROW) {
    "get text field instance and assign value."
}


问:
Kernel trace Windows 7 WinDbg
I'm getting no debug information when debugging en_windows_7_checked_build_dvd_x86_398742.
I can't see even my own trace info (ATLTRACE).
In opposite, Windows XP Checked works like a charm.
I get "Bad QueryIdType:5" msg on debug session start with Windows 7.
Kernel debug is set up properly obviously.
Please help...</p>

答:
OK, i found the solution here. It may help people:

The problem: Your DbgPrint or KdPrint messages don't appear in WinDbg (or KD) when you run your driver on Windows Vista.

The reason?  Vista automatically maps DbgPrint and friends to DbgPrintEx.  Now, you may recall that DbgPrintEx allows you to control the conditions under which messages will be sent to the kernel debugger by filtering messages via a component name and level in the function call and an associated filter mask in either the registry or in memory.

In Vista, DbgPrint and KdPrint are mapped to component "DPFLTR_DEFAULT_ID" and level "DPFLTR_INFO_LEVEL".  Of course, in Vista, xxx_INFO_LEVEL output is disabled by default.  So, by default, your DbgPrint/KdPrint doesn't get sent to the kernel debugger.

How to fix it? Two choices:

Enable output of DbgPrint/KdPrint messages by default --Open the key HKLM\SYSTEM\CurrentControlSet\Session Manager\Debug Print Filter.  Under this key, create a  value with the name DEFAULT  Set the value of this key equal to the DWORD value 8 to enable xxx_INFO_LEVEL output as well as xxx_ERROR_LEVEL output.  Or try setting the mask to 0xF so you get all output.  You must reboot for these changes to take effect.

Specifically change the component filter mast for DPFLTR.  In early releases of Vista/LH you changed the default printout mask by specifying a mask value for the DWORD at Kd_DPFLTR_MASK ("ed Kd_DPFLTR_MASK").  In build 5308 (the February CTP of Vista), it seems that the mask variable has changed and you need to set the mask value for the DWORD at Kd_DEFAULT_MASK ("ed Kd_DEFAULT_MASK).  In either case, specify 8 to enable DPFLTR_INFO_LEVEL output in addition to DPFLTR_ERROR_LEVEL output, or 0xF to get all levels of output.

See the WDK documentation for Reading and Filtering Debugging Messages (follow the path: Driver Development Tools\Tools for Debugging Drivers\Using Debugging Code in a Driver\Debugging Code Overview) for the complete details on the use of DbgPrintEx/KdPrintEx.  Or look at the Debugging Tools For Windows documentation (Appendix A) on DbgPrintEx.

ContentLicense: CC BY-SA 2.5

Title: Kernel trace Windows 7 WinDbg


问:
array in array in array and also one
I need to write a factorial using an array but the problem is only Show 120 five times and what i want is  1, 2, 6, 24, 120 showing in the textBox

```<code>int factProg = 1;
public void factArray(int[] arr)
{
    for (int i = 0; i < arr.Length; i++)
    {
        factProg = factProg * arr[i];
    }
}

int[] arr = {1,2,3,4,5};

for (int i = 0; i < arr.Length; i++)
{
    factArray(arr);
    textBox1.Text += Convert.ToString(factProg);
    textBox1.Text += Environment.NewLine;
}
</code>```

答:
Simply put - your factArray method always calculates the factorial for the length of the whole array which is a fixed size. You need to pass an extra parameter - being the position in the array you want to stop calculating

Try this if you want to calculate using your array :

```<code>int factProg;
public void factArray(int[] arr, int len)
{
  factProg = arr[0];
  for (int i = 1; i <= len; i++)
  {
    factProg = factProg * arr[i];
  }
}

int[] arr = {1,2,3,4,5};

for (int i = 0; i < arr.Length; i++)
{
  factArray(arr, i);
  textBox1.Text += Convert.ToString(factProg);
  textBox1.Text += Environment.NewLine;
}
</code>```

You would need to add a check in the method that you are not exceeding the array length.

Title: array in array in array and also one

Body:
I need to write a factorial using an array but the problem is only Show 120 five times and what i want is  1, 2, 6, 24, 120 showing in the textBox

int factProg = 1;
public void factArray(int[] arr)
{
    for (int i = 0; i < arr.Length; i++)
    {
        factProg = factProg * arr[i];
    }
}

int[] arr = {1,2,3,4,5};

for (int i = 0; i < arr.Length; i++)
{
    factArray(arr);
    textBox1.Text += Convert.ToString(factProg);
    textBox1.Text += Environment.NewLine;
}

Body:
Simply put - your factArray method always calculates the factorial for the length of the whole array which is a fixed size. You need to pass an extra parameter - being the position in the array you want to stop calculating

Try this if you want to calculate using your array :

int factProg;
public void factArray(int[] arr, int len)
{
  factProg = arr[0];
  for (int i = 1; i <= len; i++)
  {
    factProg = factProg * arr[i];
  }
}

int[] arr = {1,2,3,4,5};

for (int i = 0; i < arr.Length; i++)
{
  factArray(arr, i);
  textBox1.Text += Convert.ToString(factProg);
  textBox1.Text += Environment.NewLine;
}

You would need to add a check in the method that you are not exceeding the array length.


问:
elasticsearch_dsl: Generate multiple buckets in aggregation
I want to generate this:

```<code>GET /packets-2017-09-25/_search
{
  "size": 0,
  "query": {
        "match": {
            "transport_protocol": "tcp"
        }
  },
  "aggs": {
    "clients": {
      "terms": {
        "field": "layers.ip.src.keyword",
        "size": 1000,
        "order":{ "num_servers.value":"desc" }
      },
      "aggs": {
        "num_servers": {
          "cardinality": {
            "field": "layers.ip.dst.keyword",
            "precision_threshold" : 40000
          }
        },
        "server_list": {
          "terms": {
            "field": "layers.ip.dst.keyword"
          }
        }
      }
    }
  }
}
</code>```

i.e I want two buckets (num_servers) and (server_list) under clients.

I am trying the below piece of code, which errors out:

```<code>def get_streams_per_client(proto='tcp', max=40000):
    s = Search(using=client, index="packets-2017-09-25") \
               .query("match", transport_protocol=proto)
    s.aggs.bucket('clients', 'terms', field='layers.ip.src.keyword', size=max, order={"num_servers.value":"desc"})\
    .bucket('num_servers', 'cardinality', field='layers.ip.dst.keyword', precision_threshold=40000)\
    .bucket('server_list', 'terms', field='layers.ip.dst.keyword')
    s = s.execute()
    <snip>
</code>```

I think I am missing on the right syntax. Appreciate some guidance.

答:
You can always reach existing aggregation using the ["name"] notation if you want to define other sub-aggregations:

```<code>s = Search().query('match', transport_protocol='tcp')
s.aggs.bucket('clients', 'terms', field='layers.ip.src.keyword', size=max, order={"num_servers.value":"desc"})
s.aggs['clients'].metric('num_servers', 'cardinality', field=..., precision_threshold=...)
s.aggs['clients'].bucket('server_list', 'terms', ...)
</code>```

Hope this helps!

Body:
I want to generate this:

GET /packets-2017-09-25/_search
{
  "size": 0,
  "query": {
        "match": {
            "transport_protocol": "tcp"
        }
  },
  "aggs": {
    "clients": {
      "terms": {
        "field": "layers.ip.src.keyword",
        "size": 1000,
        "order":{ "num_servers.value":"desc" }
      },
      "aggs": {
        "num_servers": {
          "cardinality": {
            "field": "layers.ip.dst.keyword",
            "precision_threshold" : 40000
          }
        },
        "server_list": {
          "terms": {
            "field": "layers.ip.dst.keyword"
          }
        }
      }
    }
  }
}

i.e I want two buckets (num_servers) and (server_list) under clients.

I am trying the below piece of code, which errors out:

def get_streams_per_client(proto='tcp', max=40000):
    s = Search(using=client, index="packets-2017-09-25") \
               .query("match", transport_protocol=proto)
    s.aggs.bucket('clients', 'terms', field='layers.ip.src.keyword', size=max, order={"num_servers.value":"desc"})\
    .bucket('num_servers', 'cardinality', field='layers.ip.dst.keyword', precision_threshold=40000)\
    .bucket('server_list', 'terms', field='layers.ip.dst.keyword')
    s = s.execute()
    <snip>

I think I am missing on the right syntax. Appreciate some guidance.

Body:
You can always reach existing aggregation using the ["name"] notation if you want to define other sub-aggregations:

s = Search().query('match', transport_protocol='tcp')
s.aggs.bucket('clients', 'terms', field='layers.ip.src.keyword', size=max, order={"num_servers.value":"desc"})
s.aggs['clients'].metric('num_servers', 'cardinality', field=..., precision_threshold=...)
s.aggs['clients'].bucket('server_list', 'terms', ...)

Hope this helps!


问:
combine three tables with keyword with in laravel
I want to join three tables. Here is the DB model in server:

```<code>lecturers
    id - integer (PK)
    ......

examination
    id - integer (PK)
   .....

exam_supervision
    lecturer_id - integer (FK)
    exam_id- integer (FK)
</code>```

Model relation as I implemented in laravel.

```</p>

```<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examsupervision extends Model {

    public $timestamps = false;

    protected $table = 'exam_supervision';

    protected $fillable = ['lecturer_id', 'exam_id'];
}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examination extends Model {

    public $timestamps = false;

    protected $table = 'examination';

    protected $fillable = ['name', 'module_id', 'startdate', 'enddate', 'duration', 'type', 'code', 'status'];

}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Lecturers extends Model {

    public $timestamps = false;

    protected $table = 'lecturers';

    protected $fillable = ['user_id', 'address', 'phone'];

}
```

<p>```

lecturers, examinations and exam_supervision which is M:M. What I want is find all the examinations of a lecturer.

My code

```<code> public function lecturerViewExaminations($id)
  {

what code to get all exam for a lecturer..say ID 129

  }
</code>```

Returning me empty set. WHat am I doing wrong? It is easy in SQL syntax but in laravel I am finding it very confusing

答:
Model::with() is for relation, Use just ->get()

```<code>$examinations=Examsupervision::with('lecturers', 'examinations')->get();
</code>```

You already have relation for lecturers and examinations.

If not worked, share Model Examsupervision

Body:
I want to join three tables. Here is the DB model in server:

lecturers
    id - integer (PK)
    ......

examination
    id - integer (PK)
   .....

exam_supervision
    lecturer_id - integer (FK)
    exam_id- integer (FK)

Model relation as I implemented in laravel.

```</p>

<pre><code><?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examsupervision extends Model {

    public $timestamps = false;

    protected $table = 'exam_supervision';

    protected $fillable = ['lecturer_id', 'exam_id'];
}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examination extends Model {

    public $timestamps = false;

    protected $table = 'examination';

    protected $fillable = ['name', 'module_id', 'startdate', 'enddate', 'duration', 'type', 'code', 'status'];

}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Lecturers extends Model {

    public $timestamps = false;

    protected $table = 'lecturers';

    protected $fillable = ['user_id', 'address', 'phone'];

}
</code></pre>

<p>```

lecturers, examinations and exam_supervision which is M:M. What I want is find all the examinations of a lecturer.

My code

 public function lecturerViewExaminations($id)
  {

what code to get all exam for a lecturer..say ID 129

  }

Returning me empty set. WHat am I doing wrong? It is easy in SQL syntax but in laravel I am finding it very confusing

Body:
Model::with() is for relation, Use just ->get()

$examinations=Examsupervision::with('lecturers', 'examinations')->get();

You already have relation for lecturers and examinations.

If not worked, share Model Examsupervision


问:
Storing and processing a lot of tiny files
There are a lot of files with size from 1Kb to 5Mb on our servers. Total size of those files is about 7Tb.  Process algorithm - read and make some decisions about this file. Files may have several formats: doc, txt, png, bmp and etc. Therefore I can't merge those files to get bigger files.
How I can effectively store and process those files? What technology fits well to this task?</p>

答:
Start by segregating files into Different directories based on types. You can even have partition withing the individual directories. Example /data/images/YYYY-MM-DD , /data/text/YYYY-MM-DD

Use multipleInputs with appropriate InputFormat for each Path.

Normalize the data into a generic format before sending it to the reducer if needed.

There are ways to ingest data for your need .

Use Kafka to store data under different topics based on type(image , text ) and then copy to hdfs from kafka

Use Flume

As you have huge amount of data ,

please rollup the data in HDFS on a weekly basis . You can use oozie or falcon to automate the weekly rollup process

Use CombinedInPutFormat in your Spark or MR code.

Last but not the least map the data as table using Hive to expose it to external clients.


问:
Nested JSON Object not showing up when printing it
Not able to show deeply nested JSON Objects to show up.Have been looking at all kinds of stackoverflow posts for this. Appreciate any help on this newbie question. I want it to show details of the athlete JSONObject within the athletes array.
It shows up like [Object].

```<code>eventUnitResults: [ { is_team: true, athletes: [ [Object], [Object] ] },
  { is_team: true, athletes: [ [Object], [Object] ] } ]
</code>```

const result = {}
let eventUnitResults = [];
let athletes = [];

for (i=0; i < 2; i++) {
  const athlete = {};
  athlete.athlete_name = 'Ram' + i;
  athlete.athlete_gender = 'M'
  athletes.push(athlete);
}
for (j=0;j < 2;j++) {
  const nestedResult = {};
  nestedResult.is_team = true;
  if (athletes) {
    nestedResult.athletes = athletes;
  }
  console.log('nestedResult:', nestedResult);
  if (nestedResult) {
    eventUnitResults.push(nestedResult);//TODO:
    //eventUnitResults.push(JSON.stringify(nestedResult));//TODO:
  }
}
console.log('eventUnitResults:', eventUnitResults);//<==== how can I get deeply nested values of athletes showing up properly here

if (eventUnitResults) {
  result.event_unit_results = eventUnitResults;
}
console.log('result:', result)```

TIA

答:
If you log your objects, you might want to convert the actual object to a string.

Background

If you compare this to java (or most languages):

```<code>System.out.println(object);
</code>```

prints your object.toString(). Unless you override it, that's the memory address.

Problem

In JavaScript:

```<code>console.log(object);
</code>```

[object, object]

would print [object, object] because it prints WHAT you are printing. In this case, it does not know that you expect a String containing JSON.

Note this does not apply to all browsers. Chrome, for example, wants to help you out and prints the JSON value interactively; you can collapse and uncollapse it.

Solution

The solution to this problem, is telling the console explicitly to print a json string. You can do this by calling the build-in json object's function to stringify an object.

```<code>JSON.stringify(object);
</code>```

{ "content": "json" }

For completeness, print the object pretty by setting the print output to 4 spaces indentation:

```<code>JSON.stringify(object, null, 4);
</code>```

prints:

```<code>{
    "content": "json"
}
</code>```

Body:
Not able to show deeply nested JSON Objects to show up.Have been looking at all kinds of stackoverflow posts for this. Appreciate any help on this newbie question. I want it to show details of the athlete JSONObject within the athletes array.
It shows up like [Object].

eventUnitResults: [ { is_team: true, athletes: [ [Object], [Object] ] },
  { is_team: true, athletes: [ [Object], [Object] ] } ]

const result = {}
let eventUnitResults = [];
let athletes = [];

for (i=0; i < 2; i++) {
  const athlete = {};
  athlete.athlete_name = 'Ram' + i;
  athlete.athlete_gender = 'M'
  athletes.push(athlete);
}
for (j=0;j < 2;j++) {
  const nestedResult = {};
  nestedResult.is_team = true;
  if (athletes) {
    nestedResult.athletes = athletes;
  }
  console.log('nestedResult:', nestedResult);
  if (nestedResult) {
    eventUnitResults.push(nestedResult);//TODO:
    //eventUnitResults.push(JSON.stringify(nestedResult));//TODO:
  }
}
console.log('eventUnitResults:', eventUnitResults);//<==== how can I get deeply nested values of athletes showing up properly here

if (eventUnitResults) {
  result.event_unit_results = eventUnitResults;
}
console.log('result:', result)

TIA

Body:
If you log your objects, you might want to convert the actual object to a string.

Background

If you compare this to java (or most languages):

System.out.println(object);

prints your object.toString(). Unless you override it, that's the memory address.

Problem

In JavaScript:

console.log(object);

[object, object]

would print [object, object] because it prints WHAT you are printing. In this case, it does not know that you expect a String containing JSON.

Note this does not apply to all browsers. Chrome, for example, wants to help you out and prints the JSON value interactively; you can collapse and uncollapse it.

Solution

The solution to this problem, is telling the console explicitly to print a json string. You can do this by calling the build-in json object's function to stringify an object.

JSON.stringify(object);

{ "content": "json" }

For completeness, print the object pretty by setting the print output to 4 spaces indentation:

JSON.stringify(object, null, 4);

prints:

{
    "content": "json"
}


问:
Toolbar doesn't hide on Scrolling recyclerview in DrawerLayout
hello I'm trying to hide toolbar when i scroll recyclerview which is in fragment, my layout also has an drawerlayout and tablayout. I'm trying just to hide toolbar and move tab bar up.

this is my activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fitsSystemWindows="true"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#e9e7e7"
    tools:context=".MainActivity">

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

        <android.support.v4.view.ViewPager
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:id="@+id/viewPager"
            >

        </android.support.v4.view.ViewPager>

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

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/ctb_dashboard"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="@color/white"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <android.support.v7.widget.Toolbar
                    xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:layout_width="match_parent"
                    android:background="@color/colorPrimary"
                    android:minHeight="?attr/actionBarSize"
                    android:id="@+id/toolBar"
                    app:layout_scrollFlags="scroll|enterAlways"
                    android:layout_height="wrap_content"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                    app:theme="@style/ThemeOverlay.AppCompat.Dark"
                    app:layout_collapseMode="pin">

                </android.support.v7.widget.Toolbar>

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

            <android.support.design.widget.TabLayout
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:id="@+id/tabLayout"
                app:tabMode="fixed"
                app:tabSelectedTextColor="@color/white"
                app:tabTextColor="@color/colorTab"
                app:tabTextAppearance="@style/MyTabStyle"
                app:tabIndicatorColor="@android:color/white"
                app:tabIndicatorHeight="3dp"
                app:tabGravity="fill">
            </android.support.design.widget.TabLayout>

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

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

    <android.support.design.widget.NavigationView
        app:headerLayout="@layout/header"
        app:itemTextAppearance="@style/NavDrawerTextStyle"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/nav_view"
        android:background="#d2d2d2"
        app:itemTextColor="#6c6c6c"
        app:itemIconTint="#6c6c6c"
        app:menu="@menu/drawermenu"
        android:layout_gravity="start">
    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>
</code>```

fragment_home.xml

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_marginTop="100dp"
        android:id="@+id/blog_listt2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

    </android.support.v7.widget.RecyclerView>

    <ProgressBar
        android:id="@+id/progressBar2"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:indeterminateTint="@color/colorPrimaryDark"
        android:visibility="visible"/>

</FrameLayout>
</code>```

I have tried most of the answers which i have found in Stack overflow still i was unable to get it done. Am I doing something wrong? will someone please help me out with this trying to get this done sense 1 week.

答:
acitivity_main.xml</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fitsSystemWindows="true"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#e9e7e7"
    tools:context=".MainActivity">

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

        <android.support.v4.view.ViewPager
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:id="@+id/viewPager"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            >

        </android.support.v4.view.ViewPager>

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

                <android.support.v7.widget.Toolbar
                    xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:layout_width="match_parent"
                    android:background="@color/colorPrimary"
                    android:minHeight="?attr/actionBarSize"
                    android:id="@+id/toolBar"
                    app:layout_scrollFlags="scroll|enterAlways"
                    android:layout_height="wrap_content"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                    app:theme="@style/ThemeOverlay.AppCompat.Dark"
                    app:layout_collapseMode="pin">

                </android.support.v7.widget.Toolbar>

            <android.support.design.widget.TabLayout
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:id="@+id/tabLayout"
                app:tabSelectedTextColor="@color/white"
                app:tabTextColor="@color/colorTab"
                app:tabTextAppearance="@style/MyTabStyle"
                app:tabIndicatorColor="@android:color/white"
                app:tabIndicatorHeight="3dp"
                app:tabMode="fixed"
                app:tabGravity="fill">
            </android.support.design.widget.TabLayout>

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

    <android.support.design.widget.NavigationView
        app:headerLayout="@layout/header"
        app:itemTextAppearance="@style/NavDrawerTextStyle"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/nav_view"
        android:background="#d2d2d2"
        app:itemTextColor="#6c6c6c"
        app:itemIconTint="#6c6c6c"
        app:menu="@menu/drawermenu"
        android:layout_gravity="start">
    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>
</code>```

Body:
hello I'm trying to hide toolbar when i scroll recyclerview which is in fragment, my layout also has an drawerlayout and tablayout. I'm trying just to hide toolbar and move tab bar up.

this is my activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fitsSystemWindows="true"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#e9e7e7"
    tools:context=".MainActivity">

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

        <android.support.v4.view.ViewPager
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:id="@+id/viewPager"
            >

        </android.support.v4.view.ViewPager>

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

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/ctb_dashboard"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="@color/white"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <android.support.v7.widget.Toolbar
                    xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:layout_width="match_parent"
                    android:background="@color/colorPrimary"
                    android:minHeight="?attr/actionBarSize"
                    android:id="@+id/toolBar"
                    app:layout_scrollFlags="scroll|enterAlways"
                    android:layout_height="wrap_content"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                    app:theme="@style/ThemeOverlay.AppCompat.Dark"
                    app:layout_collapseMode="pin">

                </android.support.v7.widget.Toolbar>

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

            <android.support.design.widget.TabLayout
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:id="@+id/tabLayout"
                app:tabMode="fixed"
                app:tabSelectedTextColor="@color/white"
                app:tabTextColor="@color/colorTab"
                app:tabTextAppearance="@style/MyTabStyle"
                app:tabIndicatorColor="@android:color/white"
                app:tabIndicatorHeight="3dp"
                app:tabGravity="fill">
            </android.support.design.widget.TabLayout>

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

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

    <android.support.design.widget.NavigationView
        app:headerLayout="@layout/header"
        app:itemTextAppearance="@style/NavDrawerTextStyle"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/nav_view"
        android:background="#d2d2d2"
        app:itemTextColor="#6c6c6c"
        app:itemIconTint="#6c6c6c"
        app:menu="@menu/drawermenu"
        android:layout_gravity="start">
    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

fragment_home.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_marginTop="100dp"
        android:id="@+id/blog_listt2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

    </android.support.v7.widget.RecyclerView>

    <ProgressBar
        android:id="@+id/progressBar2"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:indeterminateTint="@color/colorPrimaryDark"
        android:visibility="visible"/>

</FrameLayout>

I have tried most of the answers which i have found in Stack overflow still i was unable to get it done. Am I doing something wrong? will someone please help me out with this trying to get this done sense 1 week.

Body:
acitivity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fitsSystemWindows="true"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#e9e7e7"
    tools:context=".MainActivity">

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

        <android.support.v4.view.ViewPager
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:id="@+id/viewPager"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            >

        </android.support.v4.view.ViewPager>

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

                <android.support.v7.widget.Toolbar
                    xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:layout_width="match_parent"
                    android:background="@color/colorPrimary"
                    android:minHeight="?attr/actionBarSize"
                    android:id="@+id/toolBar"
                    app:layout_scrollFlags="scroll|enterAlways"
                    android:layout_height="wrap_content"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                    app:theme="@style/ThemeOverlay.AppCompat.Dark"
                    app:layout_collapseMode="pin">

                </android.support.v7.widget.Toolbar>

            <android.support.design.widget.TabLayout
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:id="@+id/tabLayout"
                app:tabSelectedTextColor="@color/white"
                app:tabTextColor="@color/colorTab"
                app:tabTextAppearance="@style/MyTabStyle"
                app:tabIndicatorColor="@android:color/white"
                app:tabIndicatorHeight="3dp"
                app:tabMode="fixed"
                app:tabGravity="fill">
            </android.support.design.widget.TabLayout>

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

    <android.support.design.widget.NavigationView
        app:headerLayout="@layout/header"
        app:itemTextAppearance="@style/NavDrawerTextStyle"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/nav_view"
        android:background="#d2d2d2"
        app:itemTextColor="#6c6c6c"
        app:itemIconTint="#6c6c6c"
        app:menu="@menu/drawermenu"
        android:layout_gravity="start">
    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>


问:
stop background to be draggable on a button click
I have some code that when I press button the background in the div start to be draggable. I would like to do something like when I click on some else button  the background stop to be draggable and when again I press button the bg start to be draggable again.</p>

```<code><html>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
<script src="draggable_background.js"></script>

<style>
div { width: 320px; height: 240px; display: inline-block; font-family:
sans-serif; border: 2px solid #aaa;}
</style>

<body>
<div id="default" style="background:url('aaa.jpg')">default</div>

<br><br>
<button id="first"></button>

<script>
$(document).ready(function(){
$('#first').click(function() {
  $('#default').backgroundDraggable();
  $('div').each(function() {
    var $this = $(this),
        html = $this.html();
    $this.empty().append($('<p>').html(html))
  });
  });
});

</body>
</html>
</code>```

答:
I belive you are using this library https://github.com/kentor/jquery-draggable-background

To disable the draggable you can call

```<code>$('div').backgroundDraggable('disable');
</code>```

to make the button toggle isDraggable, you can use variable isDraggable, and check whether to toggle drag or disable drag

here's the full example

```<code><html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="draggable_background.js"></script>
</head>

<style>
div { width: 320px; height: 240px; display: inline-block; font-family:
sans-serif; border: 2px solid #aaa;}
</style>

<body>
    <div id="default" style="background:url('bg.jpg')">default</div>

    <br><br>
    <button id="first">DRAG</button>

    <script>
    //While in global context declare variable
    var isDraggable = false;

    $(document).ready(function(){
        $('#first').click(function() {

            if (!isDraggable)
            {
                //Not Draggable, then make it draggable
                $('#default').backgroundDraggable();
                $('div').each(function() {
                    var $this = $(this);
                    var html = $this.html();
                    $this.empty().append($('<p>').html($this.html()));
                });
                isDraggable = true;
            } else
            {
                //Already draggable, then disable it
                $('#default').backgroundDraggable('disable');
                isDraggable = false;
            }

        });
    });
    </script>
</body>
</html>
</code>```

Body:
I have some code that when I press button the background in the div start to be draggable. I would like to do something like when I click on some else button  the background stop to be draggable and when again I press button the bg start to be draggable again.

default

<button id="first"></button>

Body:
I belive you are using this library https://github.com/kentor/jquery-draggable-background

To disable the draggable you can call

$('div').backgroundDraggable('disable');

to make the button toggle isDraggable, you can use variable isDraggable, and check whether to toggle drag or disable drag

here's the full example

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="draggable_background.js"></script>
</head>

<style>
div { width: 320px; height: 240px; display: inline-block; font-family:
sans-serif; border: 2px solid #aaa;}
</style>

<body>
    <div id="default" style="background:url('bg.jpg')">default</div>

    <br><br>
    <button id="first">DRAG</button>

    <script>
    //While in global context declare variable
    var isDraggable = false;

    $(document).ready(function(){
        $('#first').click(function() {

            if (!isDraggable)
            {
                //Not Draggable, then make it draggable
                $('#default').backgroundDraggable();
                $('div').each(function() {
                    var $this = $(this);
                    var html = $this.html();
                    $this.empty().append($('<p>').html($this.html()));
                });
                isDraggable = true;
            } else
            {
                //Already draggable, then disable it
                $('#default').backgroundDraggable('disable');
                isDraggable = false;
            }

        });
    });
    </script>
</body>
</html>


问:
Perl user input into SQL Like statement
Im trying to get user input and send it through to the SQL Like statement. But Im getting error: Can't call method "bind_param" on an undefined.
My Original code :

```<code>#!/usr/bin/perl
use DBI;
#use DBD::Oracle;
use strict;
use warnings;
use CGI;

print "Enter INCD number : ";

my $input = <>;
chomp $input;

my $DSN = 'driver={SQL Server};Server=ddsfs1; database=sdfds;TrustedConnection=Yes';
my $dbh = DBI->connect("dbi:ODBC:$DSN")
    #print "connected.."
    or die "$DBI::errstr\n";

my $query = $dbh->prepare("SELECT TOP 20 Id
      ,Created
      ,Updated
      ,Message
      FROM FrameworkDEV3.Log.Entry
     where Message  like ?
     and Created >= DATEADD(day, -10, GETDATE())
        order by Created desc");
$sth->bind_param(1, '%$input%');

print $sth;
$sth->execute;
#DBI::dump_results($sth);

while( my @data = $query->fetchrow_array())
{
    foreach(@data) {
    print "[$_]";
    }
    print "\n\n";
}

$sth->finish;
$dbh->disconnect;
#print "Connected..";
print "\n";
</code>```

Following code is fixed as per comments from Dave and Jim :

```<code>my $sth = $dbh->prepare("SELECT TOP 20 Id
      ,Created
      ,Updated
      ,Message
      FROM FrDEVsd.Log.Entry
     where Message  like ?
     and Created >= DATEADD(day, -10, GETDATE())
        order by Created desc");
  $sth->bind_param(1, "%$input%");
print $sth;
$sth->execute;
#DBI::dump_results($sth);
while( my @data = $sth->fetchrow_array())
{
    foreach(@data) {
    print "[$_]";
    }
    print "\n\n";
}

$sth->finish;
$dbh->disconnect;
</code>```

print "\n";

The error im getting now is

DBI::st=HASH(0x2a9a480)

答:
You've already been given a fish. Perhaps we can show you how to catch your own in the future.

This is your error:

Can't call method "bind_param" on an undefined

You call bind_param() on this line:

```<code>my $sth->bind_param(1, "%$input%");
</code>```

So you're defining a variable (called $sth) and immediately expecting that variable to be an object that you can call a method on. When you define a variable with my the variable is initialised to undef unless you assign something to it like this:

```<code>my $var = 'something';
</code>```

Your code is the equivalent of this.

```<code>my $sth = undef;
$sth->my $sth->bind_param(1, "%$input%");
</code>```

Do you see the problem now?

In DBI code you'll often see the the variable $sth used to store the statement handle that we use to execute a statement. I suspect you've copied this from some example DBI code and taken the variable name from there. If $sth was a statement handle then you could certainly call the bind_param() method on it.

So $sth needs to be a statement handle. And we create one of those by calling the prepare() method on a database handle.

```<code>my $sth = $dbh->prepare($some_sql);
</code>```

Oh, but wait.... you already have a line that looks a lot like that:

```<code>my $query = $dbh->prepare("SELECT ...");
</code>```

So it looks to me like you started writing your own code, using $query as the variable to hold the statement handle. You then copied the bind_param() line from some sample code. That didn't compile, because it used $sth, which you hadn't declared, so you just stuck a my in front of it to get around that problem? Does that sound at all accurate?

What you really wanted was to call bind_param() on the statement handle that you had already created.

```<code>$query->bind_param(1, "%$input%");
</code>```

But, to be honest, I think it's a good idea to stick with the "standard" names for DBi-related variables. It's what your maintenance programmer (which might well be you in six months time!) will expect to see.

So I'd change the prepare() line to:

```<code>my $sth = $dbh->prepare("SELECT ...");
</code>```

And leave the bind_param() call as it is. You'll need to change the fetchrow_array() to be called on $sth as well.

Title: Perl user input into SQL Like statement

Body:
Im trying to get user input and send it through to the SQL Like statement. But Im getting error: Can't call method "bind_param" on an undefined.
My Original code :

#!/usr/bin/perl
use DBI;
#use DBD::Oracle;
use strict;
use warnings;
use CGI;

print "Enter INCD number : ";

my $input = <>;
chomp $input;

my $DSN = 'driver={SQL Server};Server=ddsfs1; database=sdfds;TrustedConnection=Yes';
my $dbh = DBI->connect("dbi:ODBC:$DSN")
    #print "connected.."
    or die "$DBI::errstr\n";

my $query = $dbh->prepare("SELECT TOP 20 Id
      ,Created
      ,Updated
      ,Message
      FROM FrameworkDEV3.Log.Entry
     where Message  like ?
     and Created >= DATEADD(day, -10, GETDATE())
        order by Created desc");
$sth->bind_param(1, '%$input%');

print $sth;
$sth->execute;
#DBI::dump_results($sth);

while( my @data = $query->fetchrow_array())
{
    foreach(@data) {
    print "[$_]";
    }
    print "\n\n";
}

$sth->finish;
$dbh->disconnect;
#print "Connected..";
print "\n";

Following code is fixed as per comments from Dave and Jim :

my $sth = $dbh->prepare("SELECT TOP 20 Id
      ,Created
      ,Updated
      ,Message
      FROM FrDEVsd.Log.Entry
     where Message  like ?
     and Created >= DATEADD(day, -10, GETDATE())
        order by Created desc");
  $sth->bind_param(1, "%$input%");
print $sth;
$sth->execute;
#DBI::dump_results($sth);
while( my @data = $sth->fetchrow_array())
{
    foreach(@data) {
    print "[$_]";
    }
    print "\n\n";
}

$sth->finish;
$dbh->disconnect;

print "\n";

The error im getting now is

DBI::st=HASH(0x2a9a480)

Body:
You've already been given a fish. Perhaps we can show you how to catch your own in the future.

This is your error:

Can't call method "bind_param" on an undefined

You call bind_param() on this line:

my $sth->bind_param(1, "%$input%");

So you're defining a variable (called $sth) and immediately expecting that variable to be an object that you can call a method on. When you define a variable with my the variable is initialised to undef unless you assign something to it like this:

my $var = 'something';

Your code is the equivalent of this.

my $sth = undef;
$sth->my $sth->bind_param(1, "%$input%");

Do you see the problem now?

In DBI code you'll often see the the variable $sth used to store the statement handle that we use to execute a statement. I suspect you've copied this from some example DBI code and taken the variable name from there. If $sth was a statement handle then you could certainly call the bind_param() method on it.

So $sth needs to be a statement handle. And we create one of those by calling the prepare() method on a database handle.

my $sth = $dbh->prepare($some_sql);

Oh, but wait.... you already have a line that looks a lot like that:

my $query = $dbh->prepare("SELECT ...");

So it looks to me like you started writing your own code, using $query as the variable to hold the statement handle. You then copied the bind_param() line from some sample code. That didn't compile, because it used $sth, which you hadn't declared, so you just stuck a my in front of it to get around that problem? Does that sound at all accurate?

What you really wanted was to call bind_param() on the statement handle that you had already created.

$query->bind_param(1, "%$input%");

But, to be honest, I think it's a good idea to stick with the "standard" names for DBi-related variables. It's what your maintenance programmer (which might well be you in six months time!) will expect to see.

So I'd change the prepare() line to:

my $sth = $dbh->prepare("SELECT ...");

And leave the bind_param() call as it is. You'll need to change the fetchrow_array() to be called on $sth as well.


问:
AD group and permissions SQL server
Our production server has group @supporttechnician and that is active directory(AD) group, we have 10 people in that group and I want to give 6 people more privileges than other 4, how can I go for this, I am Software Engineer, not a professional DBA.

your help is much appreciated.

Thank you

答:
Unless you create additional groups this will more than likely cause issues in the future (essentially it'll be an additional step for starters and leavers of your organisation).
Create two additional AD groups one called something like "DBReadOnly" and another called "DBManagers". Then add the @supporttechnician group to the "DBReadOnly" group and only the 6 higher privileged staff to the "DBManagers" group. You then need to add the groups to the SQL instance security.
Easiest way to do this is launch SQL Server Management Studio (SSMS) and login with a user with security rights ('sa' account for example). Then select the 'Security' folder in Object Explorer, expand 'Logins' and check that the members of staff you are adding don't already have permissions (if they do, you need to sort this first). To add the AD groups, right click 'logins' > 'New login' and enter the domain group information in the panel, then from the 'User Mappings' page section grant the permissions to each database as required.</p>

Title: AD group and permissions SQL server


问:
Angular 2 - Expression has changed after it was checked
When passing an object through multiple directives of childcomponents I get the following error message:

Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.

template:

```<code><form *ngIf="deliveryrequest" [formGroup]="deliveryRequestForm" (ngSubmit)="onSubmit(deliveryRequestForm)">
    <h4>Detail: {{deliveryrequest.nr}}</h4>
    <div class="row">
        <div class="col-lg-6 col-xs-12 col-md-6 col-sm-6">
            <drr-request [request]="deliveryrequest" [group]="deliveryRequestForm"></drr-request>
            <drr-received [received]="deliveryrequest" [group]="deliveryRequestForm"></drr-received>
        </div>
        <div class="col-lg-6 col-xs-12 col-md-6 col-sm-6">
            <drr-requester [requester]="deliveryrequest" [group]="deliveryRequestForm"></drr-requester>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12 col-xs-12">
            <button type="submit" class="btn btn-primary" [disabled]="!deliveryRequestForm.valid">Bewaren</button>
        </div>
    </div>
</form>
</code>```

requester component template:

```<code><div [formGroup]="requesterForm">
    <div class="row">
        <div class="col-lg-12 col-xs-12 col-md-12 col-sm-12">
            <div class="panel panel-default">
                <div class="panel-heading">Aanvrager</div>
                <div class="control-group">
                    <drr-person [required]="true" (isMinorEmittor)="setPersonIsMinor($event)" [group]="requesterForm"></drr-person>
                </div>
            </div>
        </div>
    </div>
    <div class="row" formArrayName="responsiblePersonsNationalNumbers">
        <div class="col-lg-6 col-xs-12 col-md-6 col-sm-6"
             *ngFor="let responsible of requesterForm.controls.responsiblePersonsNationalNumbers.controls; let i=index; trackBy:i">
            <div class="panel panel-default">
                <div class="panel-heading">Verantwoordelijke {{i + 1}}</div>
                <div class="control-group" [formGroupName]="i">
                    <drr-person [required]="i === 0" [group]="requesterForm.controls.responsiblePersonsNationalNumbers.controls[i]"></drr-person>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

person component template:

```<code><p-growl [value]="msgs"></p-growl>
<div [formGroup]="personForm">
    <div class="row">
        <div class="col-lg-5">
            <label>Rijksregisternummer</label>
        </div>
        <div class="col-lg-7">

            <div [ngClass]="{ 'has-error': personForm.controls.nationalnumber.invalid, 'has-success': personForm.controls.nationalnumber.valid, 'has-feedback': true }">
                <input type="text"
                       class="form-control"
                       data-mask="99.99.99-999.99"
                       placeholder="99.99.99-999.99"
                       (keyup)="lookupPerson($event)"
                       aria-describedby="inputSuccess2Status">
                <span class="glyphicon form-control-feedback" [ngClass]="{ 'glyphicon-ok' : personForm.controls.nationalnumber.valid, 'glyphicon-remove' : personForm.controls.nationalnumber.invalid }" aria-hidden="true"></span>
                <div id="inputSuccess2Status" class="sr-only">
                    <span *ngIf="personForm.controls.nationalnumber.valid">(success)</span>
                    <span *ngIf="personForm.controls.nationalnumber.invalid">(error)</span>
                </div>
            </div>
            <div *ngIf="personForm.controls.nationalnumber.dirty && !personForm.controls.nationalnumber.valid">
                <p *ngIf="personForm.controls.nationalnumber.errors" class="text-danger">
                    {{formErrors.nationalnumber}}
                </p>
            </div>
            <!--due to data-mask not passing value-->
            <input type="hidden" formControlName="nationalnumber" />
        </div>
    </div>
    <div *ngIf="person">
        <div class="row">
            <div class="col-lg-5">
                <label>Naam</label>
            </div>
            <div class="col-lg-7">{{person.familyName}}</div>
        </div>
        <div class="row">
            <div class="col-lg-5">
                <label>Voornaam</label>
            </div>
            <div class="col-lg-7">{{person.givenName}}</div>
        </div>
        <div class="row">
            <div class="col-lg-5">
                <label>Geboortedatum</label>
            </div>
            <div class="col-lg-7">{{person.birthDate | stringformat : 'xxxx-xx-xx' }}</div>
        </div>
        <div class="row">
            <div class="col-lg-5">
                <label>Adres</label>
            </div>
            <div class="col-lg-7" *ngIf="person.streetName">
                {{person.streetName}} {{person.houseNumber}} {{person.houseNumberExtension}}, {{person.postalCode}} {{person.municipalityName}}
            </div>
        </div>
        <div class="row" *ngIf="person.isMinor">
            <div class="col-lg-5">
                <label>Aanvraag minderjarige</label>
            </div>
            <div class="col-lg-7">
                <span>{{person.isMinor ? "Ja" : "Nee" }}</span>
            </div>
        </div>
    </div>
</div>
</code>```

答:
It is very strangely, because the solution is simple. I had this error in the same place. I read an interesting article about the error.
But i solved this otherwise.

From

```<code><div class="row">
    <div class="col-lg-12 col-xs-12">
        <button type="submit" class="btn btn-primary" [disabled]="!deliveryRequestForm.valid">Bewaren</button>
    </div>
</div>
</code>```

To

```<code><div class="row">
    <div class="col-lg-12 col-xs-12">
        <button type="submit" class="btn btn-primary" [attr.disabled]="!deliveryRequestForm.valid">Bewaren</button>
    </div>
</div>
</code>```

Body:
When passing an object through multiple directives of childcomponents I get the following error message:

Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.

template:

<form *ngIf="deliveryrequest" [formGroup]="deliveryRequestForm" (ngSubmit)="onSubmit(deliveryRequestForm)">

Detail: {{deliveryrequest.nr}}

            <drr-request [request]="deliveryrequest" [group]="deliveryRequestForm"></drr-request>
            <drr-received [received]="deliveryrequest" [group]="deliveryRequestForm"></drr-received>

            <drr-requester [requester]="deliveryrequest" [group]="deliveryRequestForm"></drr-requester>

            <button type="submit" class="btn btn-primary" [disabled]="!deliveryRequestForm.valid">Bewaren</button>

</form>

requester component template:

Aanvrager

                    <drr-person [required]="true" (isMinorEmittor)="setPersonIsMinor($event)" [group]="requesterForm"></drr-person>

Verantwoordelijke {{i + 1}}

                    <drr-person [required]="i === 0" [group]="requesterForm.controls.responsiblePersonsNationalNumbers.controls[i]"></drr-person>

person component template:

            Rijksregisternummer

                <input type="text"
                       class="form-control"
                       data-mask="99.99.99-999.99"
                       placeholder="99.99.99-999.99"
                       (keyup)="lookupPerson($event)"
                       aria-describedby="inputSuccess2Status">

                    (success)
                    (error)

                    {{formErrors.nationalnumber}}

            <input type="hidden" formControlName="nationalnumber" />

                Naam

{{person.familyName}}

                Voornaam

{{person.givenName}}

                Geboortedatum

{{person.birthDate | stringformat : 'xxxx-xx-xx' }}

                Adres

                {{person.streetName}} {{person.houseNumber}} {{person.houseNumberExtension}}, {{person.postalCode}} {{person.municipalityName}}

                Aanvraag minderjarige

                {{person.isMinor ? "Ja" : "Nee" }}

Body:
It is very strangely, because the solution is simple. I had this error in the same place. I read an interesting article about the error.
But i solved this otherwise.

From

<div class="row">
    <div class="col-lg-12 col-xs-12">
        <button type="submit" class="btn btn-primary" [disabled]="!deliveryRequestForm.valid">Bewaren</button>
    </div>
</div>

To

<div class="row">
    <div class="col-lg-12 col-xs-12">
        <button type="submit" class="btn btn-primary" [attr.disabled]="!deliveryRequestForm.valid">Bewaren</button>
    </div>
</div>


问:
how to get Activity's windowToken without view?
Now, I try to hide the softkeyboard when user touch outside the keyboard:

```<code>((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(editView.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
</code>```

I want put the logic in my base activity class, so if it is possible to getWindowToken without View?

答:
You can try this on your manifest file activity tag to hide keyboard.</p>

```<code> android:windowSoftInputMode="stateHidden"
</code>```

Body:
Now, I try to hide the softkeyboard when user touch outside the keyboard:

((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(editView.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);

I want put the logic in my base activity class, so if it is possible to getWindowToken without View?

Body:
You can try this on your manifest file activity tag to hide keyboard.

 android:windowSoftInputMode="stateHidden"


问:
Xamarin forms BottomNavigationBarXF displayed on top of page
I've started a Xamarin.Forms project. In need to display a TappedBage, but with the tab bar at the bottom of the page on Android and not at the top. The following lib https://github.com/thrive-now/BottomNavigationBarXF is exactly what i'm looking for.

I've added the reference to my Portable project. I can see the page, but the bar is still displayed at the top of the page.

There is no compilation error, but the behavior is the one of a standard TabbedPage.

Am I missing something?

```<code><xf:BottomBarPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:TestApp"
         xmlns:xf="clr-namespace:BottomBar.XamarinForms;assembly=BottomBar.XamarinForms"
         x:Class="TestApp.MainPageBottomTab">
<xf:BottomBarPage.Children>
    <local:Page1 />
    <local:Page2 />
    <local:Page3 />
</xf:BottomBarPage.Children>
</code>```

Thanks

答: I was missing the dependency "BottomNavigationBar" in my Nugget packages.</p>

Body:
I've started a Xamarin.Forms project. In need to display a TappedBage, but with the tab bar at the bottom of the page on Android and not at the top. The following lib https://github.com/thrive-now/BottomNavigationBarXF is exactly what i'm looking for.

I've added the reference to my Portable project. I can see the page, but the bar is still displayed at the top of the page.

There is no compilation error, but the behavior is the one of a standard TabbedPage.

Am I missing something?

<xf:BottomBarPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:TestApp"
         xmlns:xf="clr-namespace:BottomBar.XamarinForms;assembly=BottomBar.XamarinForms"
         x:Class="TestApp.MainPageBottomTab">
<xf:BottomBarPage.Children>
    <local:Page1 />
    <local:Page2 />
    <local:Page3 />
</xf:BottomBarPage.Children>

Thanks


问:
replace url using preg_replace php
Hi all i know preg_replace can be used for formatting string but
i need help in that concerned area
my url will be like this

```<code>www.example.com/en/index.php
</code>```

or

```<code>www.example.com/fr/index.php
</code>```

what i want is to get

result as

```<code>www.example.com/index.php
</code>```

i need it in php code so as to set in a session

can anyone please explain how ?

答:
This is one way to do it:-

```<code>$newurl = preg_replace('/\/[a-z][a-z]\//', '/', $url);
</code>```

Note that the search string appears with quotes and forward slashes ('/.../') and that the forward slashes in the URL then have to be escaped (\/).  The language code is then matched with '[a-z][a-z]', but there are several other ways to do this and you may want something more liberal in case there are ever 3 letter codes, or caps.  Equally you may need to do something tighter depending on what other URL schemes might appear.

Title: replace url using preg_replace php

Body:
Hi all i know preg_replace can be used for formatting string but
i need help in that concerned area
my url will be like this

www.example.com/en/index.php

or

www.example.com/fr/index.php

what i want is to get

result as

www.example.com/index.php

i need it in php code so as to set in a session

can anyone please explain how ?

Body:
This is one way to do it:-

$newurl = preg_replace('/\/[a-z][a-z]\//', '/', $url);

Note that the search string appears with quotes and forward slashes ('/.../') and that the forward slashes in the URL then have to be escaped (\/).  The language code is then matched with '[a-z][a-z]', but there are several other ways to do this and you may want something more liberal in case there are ever 3 letter codes, or caps.  Equally you may need to do something tighter depending on what other URL schemes might appear.


问:
PhpStorm not recognizing return type as extension of another
Scenario

I'm using PHP7 type hinting to say that my function has return type City.

```<code>public function getCityById(int $city_id) : City { ... }
</code>```

In this function, I return the outcome of running a finder.

```<code>return $this->city_finder->findById($city_id);
</code>```

But PhpStorm complains here, because the findById() function returns AbstractModel.

But I have class City extends AbstractModel, so this isn't a problem. PhpStorm doesn't seem to recognize this, however, and highlights the return statement with a warning.

I don't want to mute this type of warning (disable inspection), because it is an important warning to have.

Question

Can I make PhpStorm recognize that this return statement will satisfy the return type?

Additional info

One workaround is to extract a variable, and annotate it, like so:

```<code>/** @var City $city */
$city = $this->city_finder->findById($city_id);
return $city;
</code>```

At this point, it stops warning me about it, but it seems like the extra line should be avoidable since it only exists to mute a warning in the IDE.

The findById() function is protected against returning the wrong type, because a Finder class is generated on a per-model basis.

```<code>$this->city_finder = $this->orm->getFinder(City::class);
//...
$city = $city_finder->findById(...);
</code>```

答:
PHPStorm is technically right here: according to the contracts of your functions, the statement might return the wrong value.

```<code>$result = $this->city_finder->findById($city_id);
</code>```

The only thing we can know about $result here is what findById promises us, and that's that it's an AbstractModel. It might be a City, but it might equally be a User, or a Widget, or an anonymous object defined as class extends AbstractModel {}.

The underlying problem is that $this->city_finder is an instance of some abstract repository; while you know that it will always handle City objects, that's not actually built into your type system. If it was a more specific class, it could declare that it returned City objects from its findById method, and the code would be type safe.

Based on your comment that your ORM takes in the class name as a parameter ($finder = $orm->getFinder(City::class);), if PHP supported "generics" or "template meta-programming", you might write something like this:

```<code>class ORM {
    public function getFinder<T>(): Finder<T> { ... }
}
class Finder<T> {
     public function findById(int $id): T { ...}
}
$finder = $orm->getFinder<City>();
$city = $finder->findById($city_id);
</code>```

The analyser would know that $finder was an instance of Finder<City>, and therefore that findById would return a City.

Without generics, though, there is no way to tell the analyser that if given City::class in its constructor, the Finder class will always return instances of that class.

Body:
Scenario

I'm using PHP7 type hinting to say that my function has return type City.

public function getCityById(int $city_id) : City { ... }

In this function, I return the outcome of running a finder.

return $this->city_finder->findById($city_id);

But PhpStorm complains here, because the findById() function returns AbstractModel.

But I have class City extends AbstractModel, so this isn't a problem. PhpStorm doesn't seem to recognize this, however, and highlights the return statement with a warning.

I don't want to mute this type of warning (disable inspection), because it is an important warning to have.

Question

Can I make PhpStorm recognize that this return statement will satisfy the return type?

Additional info

One workaround is to extract a variable, and annotate it, like so:

/** @var City $city */
$city = $this->city_finder->findById($city_id);
return $city;

At this point, it stops warning me about it, but it seems like the extra line should be avoidable since it only exists to mute a warning in the IDE.

The findById() function is protected against returning the wrong type, because a Finder class is generated on a per-model basis.

$this->city_finder = $this->orm->getFinder(City::class);
//...
$city = $city_finder->findById(...);

Body:
PHPStorm is technically right here: according to the contracts of your functions, the statement might return the wrong value.

$result = $this->city_finder->findById($city_id);

The only thing we can know about $result here is what findById promises us, and that's that it's an AbstractModel. It might be a City, but it might equally be a User, or a Widget, or an anonymous object defined as class extends AbstractModel {}.

The underlying problem is that $this->city_finder is an instance of some abstract repository; while you know that it will always handle City objects, that's not actually built into your type system. If it was a more specific class, it could declare that it returned City objects from its findById method, and the code would be type safe.

Based on your comment that your ORM takes in the class name as a parameter ($finder = $orm->getFinder(City::class);), if PHP supported "generics" or "template meta-programming", you might write something like this:

class ORM {
    public function getFinder<T>(): Finder<T> { ... }
}
class Finder<T> {
     public function findById(int $id): T { ...}
}
$finder = $orm->getFinder<City>();
$city = $finder->findById($city_id);

The analyser would know that $finder was an instance of Finder<City>, and therefore that findById would return a City.

Without generics, though, there is no way to tell the analyser that if given City::class in its constructor, the Finder class will always return instances of that class.


问:
Neo4j OGM & Multiple similar classes
I'm using Neo4j ogm to map many (over 20) similar classes into neo4j db which are different in just
relationship name, name and direction.
Each class implements the "Classification" interface with just one method which is the same
in every class (consist on adding relation into collection of node)

Example node:

```<code>@NodeEntity
public class ExampleClass implements Classification {
    @GraphId
    private Long id;
    private String name;

    @Relationship(type = "EXAMPLE_1", direction = "OUTGOING")
    private Set<Species> classification = new HashSet<>();

    public ExampleClass (){}
    public ExampleClass (String name) {
        this.name = name;
    }

    public Set<Species> getClassification(){
        return classification;
    }
    @Override
    public void specifiedAs(Species species){
        classification.add(species);
    }
</code>```

and analogously:

```<code>@NodeEntity
public class ExampleClass2 implements Classification {
    @GraphId
    private Long id;

    private String name;

    @Relationship(type = "EXAMPLE_2", direction = "OUTGOING")
    private Set<Species> classification = new HashSet<>();

    public ExampleClass2 (){}
    public ExampleClass2 (String name) {
        this.name = name;
    }

    public Set<Species> getClassification(){
        return classification;
    }
    @Override
    public void specifiedAs(Species species){
        classification.add(species);
    }
}
</code>```

I'm looking for possibility to reduce count of those similar classes
and create... maybe one generic class in which I can define label,property name and realtionship type also.
I prefer still using spring-data and Neo4j OGM.

答:
You could improve this by introducing an super class containing all the common properties, and just have the specific relationships in your ExampleClassXXX classes.

Note that the relationship types cannot be dynamic, so you cannot have just a generic class by itself.

Title: Neo4j OGM & Multiple similar classes

Body:
I'm using Neo4j ogm to map many (over 20) similar classes into neo4j db which are different in just
relationship name, name and direction.
Each class implements the "Classification" interface with just one method which is the same
in every class (consist on adding relation into collection of node)

Example node:

@NodeEntity
public class ExampleClass implements Classification {
    @GraphId
    private Long id;
    private String name;

    @Relationship(type = "EXAMPLE_1", direction = "OUTGOING")
    private Set<Species> classification = new HashSet<>();

    public ExampleClass (){}
    public ExampleClass (String name) {
        this.name = name;
    }

    public Set<Species> getClassification(){
        return classification;
    }
    @Override
    public void specifiedAs(Species species){
        classification.add(species);
    }

and analogously:

@NodeEntity
public class ExampleClass2 implements Classification {
    @GraphId
    private Long id;

    private String name;

    @Relationship(type = "EXAMPLE_2", direction = "OUTGOING")
    private Set<Species> classification = new HashSet<>();

    public ExampleClass2 (){}
    public ExampleClass2 (String name) {
        this.name = name;
    }

    public Set<Species> getClassification(){
        return classification;
    }
    @Override
    public void specifiedAs(Species species){
        classification.add(species);
    }
}

I'm looking for possibility to reduce count of those similar classes
and create... maybe one generic class in which I can define label,property name and realtionship type also.
I prefer still using spring-data and Neo4j OGM.


问:
Webdriver: ExpectedConditions.invisibilityOf is not working. Always throws an exception
I'm using ExpectedConditions.invisibilityOf to check the invisibility of one of the element, but every time it throws the timeout exception for :

```<code>wait.until(ExpectedConditions.invisibilityOf(elementTobeInvisible));
</code>```

Error Message:

```<code>org.openqa.selenium.TimeoutException: Expected condition failed: waiting for invisibility of Proxy element for: DefaultElementLocator 'By.xpath: //button[text()='button text']' (tried for 30 second(s) with 500 MILLISECONDS interval)
</code>```

I've checked visibility of same element using element.isDisplayed() it returns 'false' correctly.

Recently I upgraded selenium from 2.53.0

Webdriver: 3.7.1 or 3.6.0

Chrome:  62.0.3202.94 (Official Build) (64-bit)

OS: Windows 7

答:
Investigated the issue, looks like wrong implementation:

For version 2.53.0 and 3.7.0, there is implementation difference for invisibility method.

2.53 Implementation:

```<code>public static ExpectedCondition<Boolean> invisibilityOfAllElements(final List<WebElement> elements) {
    return new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver webDriver) {
            Iterator var2 = elements.iterator();

            while(var2.hasNext()) {
                WebElement element = (WebElement)var2.next();

                try {
                    if (element.isDisplayed()) {
                        return false;
                    }
                } catch (Exception var5) {
                    ;
                }
            }

            return true;
        }

        public String toString() {
            return "invisibility of all elements " + elements;
        }
    };
}
</code>```

Observation: Look at line "catch (Exception var5) ". Here we are catching everything as an Exception

for 3.7.1 implementation

```<code>public static ExpectedCondition<Boolean> invisibilityOfAllElements(final List<WebElement> elements) {
    return new ExpectedCondition() {
        public Boolean apply(WebDriver webDriver) {
            return Boolean.valueOf(elements.stream().allMatch((x$0) -> {
                return ExpectedConditions.isInvisible(x$0);
            }));
        }

        public String toString() {
            return "invisibility of all elements " + elements;
        }
    };
}

private static boolean isInvisible(WebElement element) {
    try {
        return !element.isDisplayed();
    } catch (StaleElementReferenceException var2) {
        return true;
    }
}
</code>```

Observation: We are only catching StaleElementReferenceException, hence while using the method throws TimeoutException which is not catched

ContentLicense: CC BY-SA 4.0

Body:
I'm using ExpectedConditions.invisibilityOf to check the invisibility of one of the element, but every time it throws the timeout exception for :

wait.until(ExpectedConditions.invisibilityOf(elementTobeInvisible));

Error Message:

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for invisibility of Proxy element for: DefaultElementLocator 'By.xpath: //button[text()='button text']' (tried for 30 second(s) with 500 MILLISECONDS interval)

I've checked visibility of same element using element.isDisplayed() it returns 'false' correctly.

Recently I upgraded selenium from 2.53.0

Webdriver: 3.7.1 or 3.6.0

Chrome:  62.0.3202.94 (Official Build) (64-bit)

OS: Windows 7

Body:
Investigated the issue, looks like wrong implementation:

For version 2.53.0 and 3.7.0, there is implementation difference for invisibility method.

2.53 Implementation:

public static ExpectedCondition<Boolean> invisibilityOfAllElements(final List<WebElement> elements) {
    return new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver webDriver) {
            Iterator var2 = elements.iterator();

            while(var2.hasNext()) {
                WebElement element = (WebElement)var2.next();

                try {
                    if (element.isDisplayed()) {
                        return false;
                    }
                } catch (Exception var5) {
                    ;
                }
            }

            return true;
        }

        public String toString() {
            return "invisibility of all elements " + elements;
        }
    };
}

Observation: Look at line "catch (Exception var5) ". Here we are catching everything as an Exception

for 3.7.1 implementation

public static ExpectedCondition<Boolean> invisibilityOfAllElements(final List<WebElement> elements) {
    return new ExpectedCondition() {
        public Boolean apply(WebDriver webDriver) {
            return Boolean.valueOf(elements.stream().allMatch((x$0) -> {
                return ExpectedConditions.isInvisible(x$0);
            }));
        }

        public String toString() {
            return "invisibility of all elements " + elements;
        }
    };
}

private static boolean isInvisible(WebElement element) {
    try {
        return !element.isDisplayed();
    } catch (StaleElementReferenceException var2) {
        return true;
    }
}

Observation: We are only catching StaleElementReferenceException, hence while using the method throws TimeoutException which is not catched


问:
WebPack require context from list in external json file
I have build_modules.json file, which contains information about modules should be required by WebPack, for example:

```<code>[
    'module.superman',
    'module.superwoman',
    'module.spiderman',
    'module.wolverine'
]
</code>```

So, I need to require all those modules only once to compile everything to single bundle:

```<code>var _modules = require('./build_modules.json');

_modules.forEach(function(_module){
    require('./modules/' + _module);
});
</code>```

Everything works pretty fine, but if I am having some other files in ./modules/ folder than listed in build_modules.json, all of them are included to bundle due to WebPack core mechanism, though, they are not required and will never be used in current build. I need to forcely exclude those excess files from bundle because, in praxis, my ./modules/ folder contains over 200 different modules and only modules that are in build_modules.json should be included to current bundle.

Maybe I can do this with some plugin, or maybe inside of webpack.config.js file to construct a list of needed modules and require them with node.js, then put all that stuff to WebPack as a precompiled context?

答:
In case you need just to execute your modules

You need to set entry property in webpack config. This property accepts array as value of files to include in bundle.

```<code>// webpack.config.js
const fs = require('fs');
const path = require('path');

const getModulePath = module => path.resolve(__dirname, './relative/path/to/modules/directory', module);

const fileContent = fs.readFileSync('./your.json');
const entries = JSON.parse(fileContent).map(getModulePath);

module.exports = {
  // all entries will be built during one build process
  // if you need you can split each entry to separate config file
  entry: {
    bundle1: entries, // build modules from JSON file to single bundle
    bundle2: [ './file1', './file2' ], // build static modules to single bundle
    bundle3: './sindle/file', // "classic" build
    all: [ ...entries, './file1', './file2', './sindle/file' ], // you can combine everything to 1 bundle
  },
};
</code>```

In case you need to export something from your modules

Unfortunately webpack's entry as array won't help you because it will export only last file in array.

I didn't heard something about such plugins that can combine certan files and use it as entry point. But you can create such file by yourself.

```<code>// webpack.config.js
const fs = require('fs');
const path = require('path');

// saving tmp file location
const pathToCreatedFile = path.resolve(__dirname, './path/to/created/file');
// implement fn to get relative path to modules from tmp file
const getModulePath = module => path.relative(pathToCreatedFile, path.resolve(
  __dirname,
  './relative/path/to/modules/directory',
  module,
));

// read json
const fileContent = fs.readFileSync('./path/to/your.json');
// prepare modules for tmp file
const entries = JSON.parse(fileContent)
  .map(item => ({
    name: item.slice(7),
    relpath: getModulePath(item),
  }));

// here generate import directive for each module. I used `import * as modules_name from 'path';` format
// you can choose any
const importsString = entries.map(({ name, relpath }) => `import * as ${name} from '${relpath}';`).join('\n');
// here generate exports from tmp file. It contain of all imports
const exportsString = `export {${entries.map(({name}) => name).join(',\n')}};`;
// and here just concatenate imports ad exports
const content = [
  entries.map(({ name, relpath }) => `import * as ${name} from '${relpath}';`).join('\n'),
  `export {${entries.map(({name}) => name).join(',\n')}};`,
].join('\n');

// and save tmp file content to fs
fs.writeFileSync(pathToCreatedFile, content);

module.exports = {
  // and here use saved tmp file path as entry point
  entry: pathToCreatedFile,
};
</code>```

After you import builded bundle it will return plain object with your modules. You can use Object.values or similar to get your dependencies as array.

And another aproach, you can format exportString to export array of imports.

I used import * as name from ... format to show you more common way to create file. If you don't have any default exports or you have only default export it's better to use export * from ... or export {default as name} from ... formats respectively.

Body:
I have build_modules.json file, which contains information about modules should be required by WebPack, for example:

[
    'module.superman',
    'module.superwoman',
    'module.spiderman',
    'module.wolverine'
]

So, I need to require all those modules only once to compile everything to single bundle:

var _modules = require('./build_modules.json');

_modules.forEach(function(_module){
    require('./modules/' + _module);
});

Everything works pretty fine, but if I am having some other files in ./modules/ folder than listed in build_modules.json, all of them are included to bundle due to WebPack core mechanism, though, they are not required and will never be used in current build. I need to forcely exclude those excess files from bundle because, in praxis, my ./modules/ folder contains over 200 different modules and only modules that are in build_modules.json should be included to current bundle.

Maybe I can do this with some plugin, or maybe inside of webpack.config.js file to construct a list of needed modules and require them with node.js, then put all that stuff to WebPack as a precompiled context?

Body:
In case you need just to execute your modules

You need to set entry property in webpack config. This property accepts array as value of files to include in bundle.

// webpack.config.js
const fs = require('fs');
const path = require('path');

const getModulePath = module => path.resolve(__dirname, './relative/path/to/modules/directory', module);

const fileContent = fs.readFileSync('./your.json');
const entries = JSON.parse(fileContent).map(getModulePath);

module.exports = {
  // all entries will be built during one build process
  // if you need you can split each entry to separate config file
  entry: {
    bundle1: entries, // build modules from JSON file to single bundle
    bundle2: [ './file1', './file2' ], // build static modules to single bundle
    bundle3: './sindle/file', // "classic" build
    all: [ ...entries, './file1', './file2', './sindle/file' ], // you can combine everything to 1 bundle
  },
};

In case you need to export something from your modules

Unfortunately webpack's entry as array won't help you because it will export only last file in array.

I didn't heard something about such plugins that can combine certan files and use it as entry point. But you can create such file by yourself.

// webpack.config.js
const fs = require('fs');
const path = require('path');

// saving tmp file location
const pathToCreatedFile = path.resolve(__dirname, './path/to/created/file');
// implement fn to get relative path to modules from tmp file
const getModulePath = module => path.relative(pathToCreatedFile, path.resolve(
  __dirname,
  './relative/path/to/modules/directory',
  module,
));

// read json
const fileContent = fs.readFileSync('./path/to/your.json');
// prepare modules for tmp file
const entries = JSON.parse(fileContent)
  .map(item => ({
    name: item.slice(7),
    relpath: getModulePath(item),
  }));

// here generate import directive for each module. I used `import * as modules_name from 'path';` format
// you can choose any
const importsString = entries.map(({ name, relpath }) => `import * as ${name} from '${relpath}';`).join('\n');
// here generate exports from tmp file. It contain of all imports
const exportsString = `export {${entries.map(({name}) => name).join(',\n')}};`;
// and here just concatenate imports ad exports
const content = [
  entries.map(({ name, relpath }) => `import * as ${name} from '${relpath}';`).join('\n'),
  `export {${entries.map(({name}) => name).join(',\n')}};`,
].join('\n');

// and save tmp file content to fs
fs.writeFileSync(pathToCreatedFile, content);

module.exports = {
  // and here use saved tmp file path as entry point
  entry: pathToCreatedFile,
};

After you import builded bundle it will return plain object with your modules. You can use Object.values or similar to get your dependencies as array.

And another aproach, you can format exportString to export array of imports.

I used import * as name from ... format to show you more common way to create file. If you don't have any default exports or you have only default export it's better to use export * from ... or export {default as name} from ... formats respectively.