问:
Custom Triggers for Different Sheets
Firstly excuse me for my lack of knowledge.

Let me explain my current situation.

I have 3 Tabs on one Spreadsheet:

A master list

Types of Stock

Stock Requisition sheet

The master list simply gathers the information from the Stock Tab.

The Stock requisition gathers the information from Master list.

I currently have the following simple script that triggers based upon an edit.

```<code>function myFunction() {
  MailApp.sendEmail(
      "excessstock@greenlifepharma.co.uk",
      "Excess Stock - Someone Added Stock ",
      "Please see changes on main list of spreadsheet");
}
</code>```

These are different triggers that i need...

A trigger for my function upon edit of the Stock sheet column C.

A different Trigger for when stock requisition sheet is edited.

Hope i explained well.

答:
Very easy to do what you require. Copy and paste the code below and set an onEdit() trigger.

NOTE: In the IF statment I have 'Stock' and 'Stock Requisition', these must be exact matches to the sheet names i.e. capitalisation and spacing.

```<code>function myFunction(e) {
  var getSheet = e.source.getSheetName();
  var getRange = e.range.getColumn();

     if(getSheet == "Stock" && getRange == 3 || getSheet == "Stock Requisition"){

        var stockEmail = "---------";
        var stockReqEmail = "----------";

         MailApp.sendEmail(
            (getSheet == "Stock") ? stockEmail : stockReqEmail ,
            "Excess Stock - Someone Added Stock ",
            "Please see changes on main list of spreadsheet");
  }
}
</code>```

Title: Custom Triggers for Different Sheets

Body:
Firstly excuse me for my lack of knowledge.

Let me explain my current situation.

I have 3 Tabs on one Spreadsheet:

A master list

Types of Stock

Stock Requisition sheet

The master list simply gathers the information from the Stock Tab.

The Stock requisition gathers the information from Master list.

I currently have the following simple script that triggers based upon an edit.

function myFunction() {
  MailApp.sendEmail(
      "excessstock@greenlifepharma.co.uk",
      "Excess Stock - Someone Added Stock ",
      "Please see changes on main list of spreadsheet");
}

These are different triggers that i need...

A trigger for my function upon edit of the Stock sheet column C.

A different Trigger for when stock requisition sheet is edited.

Hope i explained well.

Body:
Very easy to do what you require. Copy and paste the code below and set an onEdit() trigger.

NOTE: In the IF statment I have 'Stock' and 'Stock Requisition', these must be exact matches to the sheet names i.e. capitalisation and spacing.

function myFunction(e) {
  var getSheet = e.source.getSheetName();
  var getRange = e.range.getColumn();

     if(getSheet == "Stock" && getRange == 3 || getSheet == "Stock Requisition"){

        var stockEmail = "---------";
        var stockReqEmail = "----------";

         MailApp.sendEmail(
            (getSheet == "Stock") ? stockEmail : stockReqEmail ,
            "Excess Stock - Someone Added Stock ",
            "Please see changes on main list of spreadsheet");
  }
}


来源: stackexchange

问:
how to resolve this issue?
```<code>this is my code
package pack;
import java.awt.*;
import javax.swing.*;
public class MySwing
{
MySwing()
{

    JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame("This is my Frame");
JTabbedPane jtb= new JTabbedPane();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();jtb.addTab("employee Info", p1);
jtb.addTab("employee Dept", p2); jtb.addTab("employee Salary", p3);
f.add(jtb);
JLabel l = new JLabel("User Name");
l.setForeground(Color.blue);
JTextField tf = new JTextField(20); tf.setFont(new Font("Coronet",Font.BOLD,20));
tf.setHorizontalAlignment(JTextField.RIGHT); tf.setBackground(Color.black);
tf.setForeground(Color.yellow);
JLabel l1 = new JLabel("Password: ");
JPasswordField pf = new JPasswordField(20);
JTextArea ta = new JTextArea(10,20);
JScrollPane sp = new JScrollPane(ta);
String str[]={"select the city","Noida","Delhi","Faridabad"};
JComboBox c= new JComboBox(str);
JList li = new JList(str);
JCheckBox cb1= new JCheckBox("I.Sc",true);
JCheckBox cb2= new JCheckBox("B.Sc"); JCheckBox cb3= new JCheckBox("M.Sc");

    ButtonGroup cbg = new ButtonGroup(); JRadioButton cb4= new JRadioButton("Male",true);
JRadioButton cb5= new JRadioButton("Female",false);
cbg.add(cb4);cbg.add(cb5);
JButton b = new JButton("save");
p1.add(l);p1.add(tf);p1.add(l1);p1.add(pf);p2.add(sp);p2.add(c);p2.add(li);p2.add(cb1);p2.add(cb2);p2.add(cb3);
p3.add(cb4);p3.add(cb5);p3.add(b);
f.setSize(600,400); f.setLocation(200,100);
f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String arg[])
{

    new MySwing();
}
}
</code>```

here this is the issue
MySwing.java uses unchecked or unsafe operations
recompile with -xlint:unchecked for details
help me to resolve this
this is not a error
but my system doesn't run it
resolve it

答:
For a start you can do

```<code>JComboBox<String> c= new JComboBox<String> (str);
JList<String> li = new JList<String>(str);
</code>```

Learn about generics

ContentLicense: CC BY-SA 3.0

Title: how to resolve this issue?

Body:
this is my code
package pack;
import java.awt.*;
import javax.swing.*;
public class MySwing
{
MySwing()
{

    JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame("This is my Frame");
JTabbedPane jtb= new JTabbedPane();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();jtb.addTab("employee Info", p1);
jtb.addTab("employee Dept", p2); jtb.addTab("employee Salary", p3);
f.add(jtb);
JLabel l = new JLabel("User Name");
l.setForeground(Color.blue);
JTextField tf = new JTextField(20); tf.setFont(new Font("Coronet",Font.BOLD,20));
tf.setHorizontalAlignment(JTextField.RIGHT); tf.setBackground(Color.black);
tf.setForeground(Color.yellow);
JLabel l1 = new JLabel("Password: ");
JPasswordField pf = new JPasswordField(20);
JTextArea ta = new JTextArea(10,20);
JScrollPane sp = new JScrollPane(ta);
String str[]={"select the city","Noida","Delhi","Faridabad"};
JComboBox c= new JComboBox(str);
JList li = new JList(str);
JCheckBox cb1= new JCheckBox("I.Sc",true);
JCheckBox cb2= new JCheckBox("B.Sc"); JCheckBox cb3= new JCheckBox("M.Sc");

    ButtonGroup cbg = new ButtonGroup(); JRadioButton cb4= new JRadioButton("Male",true);
JRadioButton cb5= new JRadioButton("Female",false);
cbg.add(cb4);cbg.add(cb5);
JButton b = new JButton("save");
p1.add(l);p1.add(tf);p1.add(l1);p1.add(pf);p2.add(sp);p2.add(c);p2.add(li);p2.add(cb1);p2.add(cb2);p2.add(cb3);
p3.add(cb4);p3.add(cb5);p3.add(b);
f.setSize(600,400); f.setLocation(200,100);
f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String arg[])
{

    new MySwing();
}
}

here this is the issue
MySwing.java uses unchecked or unsafe operations
recompile with -xlint:unchecked for details
help me to resolve this
this is not a error
but my system doesn't run it
resolve it

Body:
For a start you can do

JComboBox<String> c= new JComboBox<String> (str);
JList<String> li = new JList<String>(str);

Learn about generics


问:
Find key different from given key when iterating list of dictionaries
I have list of dictionaries and in each one of them the key site exists.
So in other words, this code returns True:

```<code>all('site' in site for site in summary)
</code>```

Question is, what will be the pythonic way to iterate over the list of dictionaries and return True if a key different from site exists in any of the dictionaries?

Example: in the following list I would like to return True because of the existence of cost in the last dictionary BUT, I can't tell what will be the other key, it can be cost as in the example and it can be other strings; random keys for that matter.

```<code>[
    {"site": "site_A"},
    {"site": "site_B"},
    {"site": "site_C", "cost": 1000}
]
</code>```

答:
You could just check, for each dictionary dct:

```<code>any(key != "site" for key in dct)
</code>```

If you want to check this for a list of dictionaries dcts, shove another any around that: any(any(key != "site" for key in dct) for dct in dcts)

This also makes it easily extensible to allowing multiple different keys. (E.g. any(key not in ("site", "otherkey") for key in dct)) Because what's a dictionary good for if you can only use one key?

Body:
I have list of dictionaries and in each one of them the key site exists.
So in other words, this code returns True:

all('site' in site for site in summary)

Question is, what will be the pythonic way to iterate over the list of dictionaries and return True if a key different from site exists in any of the dictionaries?

Example: in the following list I would like to return True because of the existence of cost in the last dictionary BUT, I can't tell what will be the other key, it can be cost as in the example and it can be other strings; random keys for that matter.

[
    {"site": "site_A"},
    {"site": "site_B"},
    {"site": "site_C", "cost": 1000}
]

Body:
You could just check, for each dictionary dct:

any(key != "site" for key in dct)

If you want to check this for a list of dictionaries dcts, shove another any around that: any(any(key != "site" for key in dct) for dct in dcts)

This also makes it easily extensible to allowing multiple different keys. (E.g. any(key not in ("site", "otherkey") for key in dct)) Because what's a dictionary good for if you can only use one key?


问:
Rotate object tag (PDF) in Javascript
i'm trying to rotate an object tag that contains a PDF viewed by Acrobat Plugin via AcroPdf.dll.

I already saw this solution but don't rotate the PDF itself on >=IE9 (works on chrome)

I'm using jQuery 1.11.3 and PDFObject 1.2 and i can't change the version of jQuery.

The effect is this:

I want this:

Any help will be appreciated.
Regards

My simple code is this:

```<code><!DOCTYPE html>
<html>
<head>
<style>
.rotate-90 {
  -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.00000000, M12=-1.00000000, M21=1.00000000, M22=0.00000000,sizingMethod='auto expand')";
   filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.00000000, M12=-1.00000000, M21=1.00000000, M22=0.00000000,sizingMethod='auto expand');
  transform: rotate(90deg);
  -o-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
}
</style>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="http://miorepository.altervista.org/pdfobject.js"></script>
</head>

<body>
<button onclick="rotatePdf();">Rotate 90 degree</button>
<div id="boxPdf"></div>

<script type='text/javascript'>
            $(function(){

                var pdfPath = './doc1.pdf';

                var customParameter = {
                    page : '1',
                    view : 'FitH,0',
                    pagemode : 'none',
                    scrollbars : '0',
                    toolbar : '0',
                    statusbar : '0',
                    messages : '0',
                    navpanes : '0'
                };

                var myPDF = new PDFObject({
                                    url : pdfPath,
                                    pdfOpenParams : customParameter,
                                    cid : 'objectBoxPdf'
                                }).embed('boxPdf');
            });

            function rotatePdf(){
                $('#objectBoxPdf').toggleClass('rotate-90');
            }
</script>
</body>
</html>
</code>```

答:
Try this code:

$('#button').click(function() {
  $('#example').addClass('rotate-90');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.rotate-90 {
  transform: rotate(90deg);
  -webkit-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
}

#example {
  width: 400px;
  height: 400px;
  border: 1px solid #000;
}</code>```

  <object width="400px" height="400px" data="pdf.pdf"></object>

<button id="button">Rotate 90 degrees</button>```

Note: replace "pdf.pdf" with the name of your pdf.

Basically what this code is doing is telling the page that when you click the button, it should append the class "rotate-90" to the  element. The CSS tells the page that any element with the class "rotate-90" should be rotated by 90 degrees. When the class is appended, the element is rotated 90 degrees.

Hope this helps!

Title: Rotate object tag (PDF) in Javascript

Body:
i'm trying to rotate an object tag that contains a PDF viewed by Acrobat Plugin via AcroPdf.dll.

I already saw this solution but don't rotate the PDF itself on >=IE9 (works on chrome)

I'm using jQuery 1.11.3 and PDFObject 1.2 and i can't change the version of jQuery.

The effect is this:

I want this:

Any help will be appreciated.
Regards

My simple code is this:

<!DOCTYPE html>

<button onclick="rotatePdf();">Rotate 90 degree</button>

Body:
Try this code:

$('#button').click(function() {
  $('#example').addClass('rotate-90');
});

.rotate-90 {
  transform: rotate(90deg);
  -webkit-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
}

#example {
  width: 400px;
  height: 400px;
  border: 1px solid #000;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="example">
  <object width="400px" height="400px" data="pdf.pdf"></object>
</div>
<button id="button">Rotate 90 degrees</button>

Note: replace "pdf.pdf" with the name of your pdf.

Basically what this code is doing is telling the page that when you click the button, it should append the class "rotate-90" to the  element. The CSS tells the page that any element with the class "rotate-90" should be rotated by 90 degrees. When the class is appended, the element is rotated 90 degrees.

Hope this helps!


问:
Session Variable problems when storing an object in my Session
I have a log in page where I valid my users and based on this validation I store their user info in a session variable so I can access it at any time.  To do this I am trying to store an instance of one of my dbml generated classes "UserInfo".  So I populate the class and then store it in a session variable I call "user"

```<code> UserInfo u = new UserInfo();
    u = dal.RetrieveUser(userID, userPass)
    Session["user"] = u;
</code>```

The issue I am having with this is it seems to mix up these session variables between users.  Or more specifically it always seems to take the information from the first user variable stored for each subsequent user that logs in.  So user 1's info is being pulled in for User 2, User 3, etc...

Is my problem that my class "UserInfo" is somehow static? Or what is causing this to happen?  My UserInfo class looks like this:

```<code>public partial class UserInfo
    {
        ...
</code>```

EDIT:
After further review it seems that my Session variables are in fact working properly but my custom menus are actually the problem.

答: Are you testing this using the web client on the same computer or separate computers? For instance, by default FireFox will run in a single process even if you have multiple windows or tabs open. As silly as it sounds, a colleague of mine had not noticed this phenomena when he had the same issue.</p>

OwnerDisplayName: Collin Estes

ContentLicense: CC BY-SA 2.5

Body:
I have a log in page where I valid my users and based on this validation I store their user info in a session variable so I can access it at any time.  To do this I am trying to store an instance of one of my dbml generated classes "UserInfo".  So I populate the class and then store it in a session variable I call "user"

 UserInfo u = new UserInfo();
    u = dal.RetrieveUser(userID, userPass)
    Session["user"] = u;

The issue I am having with this is it seems to mix up these session variables between users.  Or more specifically it always seems to take the information from the first user variable stored for each subsequent user that logs in.  So user 1's info is being pulled in for User 2, User 3, etc...

Is my problem that my class "UserInfo" is somehow static? Or what is causing this to happen?  My UserInfo class looks like this:

public partial class UserInfo
    {
        ...

EDIT:
After further review it seems that my Session variables are in fact working properly but my custom menus are actually the problem.

LastEditorDisplayName: Collin Estes

OwnerDisplayName: David Thomas Garcia


问:
ASP.NET MVC: Routing needs exact url to work
I have a Products Controller with Details action that has an Id and Slug that works as follows:

```<code>     routes.MapRoute(
            "ProductDetails", // Route name
            "{controller}/{action}/{id}/{title}", // URL with parameters
            new { controller = "Products", action = "Details", id = "", title = UrlParameter.Optional } // Parameter defaults
            );
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
</code>```

The url: localhost/Products/Details/1 and localhost/Products/Details/1/my-slug works.
But putting ProductDetails route at the top breaks my whole application. To get to my home page, my url has to look like: localhost/Home/Index.

localhost/Home or any controller of that matter does not work. It asks for a nullable parameter to be in those actions.

The error:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'MyProject.Controllers.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

答:
Try this:

```<code>routes.MapRoute(
            "ProductDetails", // Route name
            "Products/{action}/{id}/{title}", // URL with parameters
            new { controller = "Products", action = "Details", id = "", title = UrlParameter.Optional } // Parameter defaults
            );
</code>```

The route you defined matches to every URL before the default URL. You have given default values to controller and action fields. When you call http://localhost, it looks for ProductsController's Details method and finds it. Since id has a empty string value, you get the null exception.

The route above has constraint. It matches URLs starting with "Products" literal. So it doesn't break your default route.

Body:
I have a Products Controller with Details action that has an Id and Slug that works as follows:

     routes.MapRoute(
            "ProductDetails", // Route name
            "{controller}/{action}/{id}/{title}", // URL with parameters
            new { controller = "Products", action = "Details", id = "", title = UrlParameter.Optional } // Parameter defaults
            );
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

The url: localhost/Products/Details/1 and localhost/Products/Details/1/my-slug works.
But putting ProductDetails route at the top breaks my whole application. To get to my home page, my url has to look like: localhost/Home/Index.

localhost/Home or any controller of that matter does not work. It asks for a nullable parameter to be in those actions.

The error:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'MyProject.Controllers.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

Body:
Try this:

routes.MapRoute(
            "ProductDetails", // Route name
            "Products/{action}/{id}/{title}", // URL with parameters
            new { controller = "Products", action = "Details", id = "", title = UrlParameter.Optional } // Parameter defaults
            );

The route you defined matches to every URL before the default URL. You have given default values to controller and action fields. When you call http://localhost, it looks for ProductsController's Details method and finds it. Since id has a empty string value, you get the null exception.

The route above has constraint. It matches URLs starting with "Products" literal. So it doesn't break your default route.


问:
How to obtain the absolut path of the copy when copying files?
I'm copying like this:

```<code>cp "$input_file_absolut_path" "$output_directory_absolut_path"
</code>```

Now I want to do something with the copied file, but i CAN'T just:

```<code>copy_absolut_path="$output_directory_absolut_path/$input_file_absolut_path"
</code>```

Any tip to obtain the absolut path of the copied file?

答:
Solution

```<code>copy_absolute_path="$(cd "$output_directory_absolute_path"; pwd)/${input_file_absolute_path##*/}"
</code>```

Explanation

If output_directory_absolute_path ends with a /, then $(cd "$output_directory_absolute_path"; pwd) will return the path without the trailing /.

$(input_file_absolute_path##*/} returns everything after the last /.

Body:
I'm copying like this:

cp "$input_file_absolut_path" "$output_directory_absolut_path"

Now I want to do something with the copied file, but i CAN'T just:

copy_absolut_path="$output_directory_absolut_path/$input_file_absolut_path"

Any tip to obtain the absolut path of the copied file?

Body:
Solution

copy_absolute_path="$(cd "$output_directory_absolute_path"; pwd)/${input_file_absolute_path##*/}"

Explanation

If output_directory_absolute_path ends with a /, then $(cd "$output_directory_absolute_path"; pwd) will return the path without the trailing /.

$(input_file_absolute_path##*/} returns everything after the last /.


问:
Numpy Array Concatenation Multiplies array... why?
I have been desperately trying to figure out why an array concatenation leads to the array being multiplied by 2 on the first iteration...

This is my code:

```<code>def run(filename, max_iter = 1e6):
    data, fm = data_extraction(filename)

    large_output = None

    iteration_count = 0

    while iteration_count < max_iter:
        iteration_count += 1
        print iteration_count
        results = calculations(data, (0.9,1.1))

        if large_output == None:
            large_output = results[:,1] #stores the energy array
            print large_output
        else:
            large_output = np.c_[ large_output, results[:,1]]
            #large_output = np.vstack([large_output, power_and_energy_var[:,1]])
            print large_output
</code>```

and this is the console output for the print statement and 3 iterations only:

```<code>1
[  3.59891391e+01   5.75841568e+00   ]
2
[[  7.22402719e+01   3.62511328e+01]
 [  1.16726670e+01   5.91425129e+00]]
3
[[  7.22402719e+01   3.62511328e+01   3.70141435e+01]
 [  1.16726670e+01   5.91425129e+00   6.02176042e+00]]
</code>```

As you can see 7.22402719e+01 is about twice 3.59891391e+01, yet it doesn't occur for the successive iterations...

I have no idea why this is happening. I have tried everything I could possibly think off:

1) check what exactly was being executed using print statements
2) reloaded the kernel to erase any lingering variables
3) used np.vstack instead of np.c_ (same error)

Any help would be much welcome !!

答:
Despite all the very good comments and suggestions proposed in comments and answers, the answer was much simpler than that (it usually is when I spend a long time banging my head on the computer).

large_output = results[:,1]

should be explicitly expressed as an array:

large_output = np.array(results[:,1])

Body:
I have been desperately trying to figure out why an array concatenation leads to the array being multiplied by 2 on the first iteration...

This is my code:

def run(filename, max_iter = 1e6):
    data, fm = data_extraction(filename)

    large_output = None

    iteration_count = 0

    while iteration_count < max_iter:
        iteration_count += 1
        print iteration_count
        results = calculations(data, (0.9,1.1))

        if large_output == None:
            large_output = results[:,1] #stores the energy array
            print large_output
        else:
            large_output = np.c_[ large_output, results[:,1]]
            #large_output = np.vstack([large_output, power_and_energy_var[:,1]])
            print large_output

and this is the console output for the print statement and 3 iterations only:

1
[  3.59891391e+01   5.75841568e+00   ]
2
[[  7.22402719e+01   3.62511328e+01]
 [  1.16726670e+01   5.91425129e+00]]
3
[[  7.22402719e+01   3.62511328e+01   3.70141435e+01]
 [  1.16726670e+01   5.91425129e+00   6.02176042e+00]]

As you can see 7.22402719e+01 is about twice 3.59891391e+01, yet it doesn't occur for the successive iterations...

I have no idea why this is happening. I have tried everything I could possibly think off:

1) check what exactly was being executed using print statements
2) reloaded the kernel to erase any lingering variables
3) used np.vstack instead of np.c_ (same error)

Any help would be much welcome !!


问:
Eclipse RCP - Programmatically setting a view to not be closeable
I'm trying to create an RCP view that is not closeable.  I need a way to set this property programmatically because I'm creating views with secondary IDs in in the code.  I can't do it through the extension editor dialogs because of this.

Is there a way to remove the x from a view programmatically?

答:
You can do it easily.

Just set the closable property of view to False.

```<code>IViewLayout layout= layout.getViewLayout(View.ID);
layout.setCloseable(false);
</code>```

Body:
You can do it easily.

Just set the closable property of view to False.

IViewLayout layout= layout.getViewLayout(View.ID);
layout.setCloseable(false);


问:
Parent DIV to inherit width (%) from child div
I am currently trying to figure out a way to be able to have a layout that has a bottom-up, content-oriented resizing behavior.

I have the following situation: https://codepen.io/Flash1232/pen/JJYPVQ

What is wrong here is obviously that the wrapper divs do not wrap around the table divs. Now is there any solution for this involving just plain CSS and HTML or do I have to write something in JS like "set wrapper width to the width of its inner div"?

Thanks in advance for any clues!

答:
You should read the definition of the width attribute.

https://developer.mozilla.org/en/docs/Web/CSS/width

Percentages:  refer to the width of the containing block

If you set width to 150%, you explicitly say, that the child should be bigger than the parent. You can not expect, that the parent has the same width like the child, if you force the child to be wider.


问:
How can I cancel NSURLSessionDownloadTask which I resumed to get resumed my download (background) task which I created when last time I launched app
I created a background session and a download task which I wanted to be resumed after lunching app which was killed  by user.I found one way to resume that task, but there is a problem.I created new session and download task with same Url, at first it was good my old download task resumed but the problem was that the new task was created and I have 2 download tasks to download same objet(but I need only the old one). When I'm canceling the new task I'm not getting any notifications from old one.</p>

答: After creating new session and resuming download task with same url you can view the list of tasks on that session and stop the old one</p>

ContentLicense: CC BY-SA 4.0


问:
Launching app in landscape orientation causes rotation on launch
I have implemented shouldAutorotateToInterfaceOrientation and everything works fine in terms or orientation changes in my app once it is running. However I don't like the behavior of my app when it is fist launched.

When I launch my app in portrait orientation, it opens as expected, however when I launch my app in landscape orientation, I see everything load in portrait orientation (including the status bar), then I see an animation of my screen rotating to landscape. That animation is fine, but I don't want it to be displayed at launch.

When I look at most other apps, they seem to detect the orientation as they launch and they do not show the rotation animation on launch (only if the device is rotated after launch time).

How can I make sure my app loads in the proper orientation so the user does not see the rotation animation on launch. I would prefer it if the user only saw the rotation animation if he/she rotates the device after launching.

答:
Okay I think I figured it out. For anybody who created an app from an iPhone tempalte and then modified it for iPad, you need to add a line in your -info.plist file that says "Supported interface orientations" and enter all of the supported orientations as below. Then it seems to work as expected.</p>

```<code>    <key>UISupportedInterfaceOrientations</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationPortraitUpsideDown</string>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>
</code>```

Body:
Okay I think I figured it out. For anybody who created an app from an iPhone tempalte and then modified it for iPad, you need to add a line in your -info.plist file that says "Supported interface orientations" and enter all of the supported orientations as below. Then it seems to work as expected.

    <key>UISupportedInterfaceOrientations</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationPortraitUpsideDown</string>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>


问:
I am not able to figure out a bug that is when I try to click on a link on my website it appears the 404
My website is coded in PHP and hosted in Hostinger. The problem is that when I want to go to another link, for example the contact section or the about section it appears the 404 Not Found Page. However, I have tried the same files on local server and it works fine. Would the problem be with the code or with the host provider.

link of my website: http://tranvio.com

.htaccess:

```<code>RewriteEngine on
RewriteBase /public_html
RewriteRule ^details-(.*)?$ index.php?a=details&id=$1 [L]
RewriteRule ^recovery-(.*)?$ index.php?a=recovery&hash=$1 [L]
RewriteRule ^refid=(.*)?$ index.php?refid=$1 [L]
</code>```

答:
Question solved:

Edit the .htaccess to this:

```<code>RewriteEngine on
RewriteBase /
RewriteRule ^(login|register|forgot-
password|testimonials|logout|submit-testimonial)?$ index.php?a=$1 [L]
RewriteRule ^page/(contact|about|faq|privacy-policy|terms-of-service)?$
index.php?a=page&b=$1 [L] RewriteRule ^account/(exchanges|wallet|wallet_exchange|deposit|referrals|settings|with
drawals|withdrawal)?$ index.php?a=account&b=$1 [L]
RewriteRule ^account/exchanges/(.*)?$ index.php?
a=account&b=exchanges&page=$1 [L]
RewriteRule ^account/exchange/(.*)?$ index.php?
a=account&b=exchange&id=$1 [L]
RewriteRule ^account/referrals/(.*)?$ index.php?
a=account&b=referrals&page=$1 [L]
RewriteRule ^ref/(.*)?$ index.php?refid=$1 [L]
RewriteRule ^password-recovery/(.*)?$ index.php?a=password-
recovery&hash=$1 [L]
RewriteRule ^become_payment/(.*)?$ index.php?a=become_payment&id=$1 [L]`
</code>```

Body:
My website is coded in PHP and hosted in Hostinger. The problem is that when I want to go to another link, for example the contact section or the about section it appears the 404 Not Found Page. However, I have tried the same files on local server and it works fine. Would the problem be with the code or with the host provider.

link of my website: http://tranvio.com

.htaccess:

RewriteEngine on
RewriteBase /public_html
RewriteRule ^details-(.*)?$ index.php?a=details&id=$1 [L]
RewriteRule ^recovery-(.*)?$ index.php?a=recovery&hash=$1 [L]
RewriteRule ^refid=(.*)?$ index.php?refid=$1 [L]

Body:
Question solved:

Edit the .htaccess to this:

RewriteEngine on
RewriteBase /
RewriteRule ^(login|register|forgot-
password|testimonials|logout|submit-testimonial)?$ index.php?a=$1 [L]
RewriteRule ^page/(contact|about|faq|privacy-policy|terms-of-service)?$
index.php?a=page&b=$1 [L] RewriteRule ^account/(exchanges|wallet|wallet_exchange|deposit|referrals|settings|with
drawals|withdrawal)?$ index.php?a=account&b=$1 [L]
RewriteRule ^account/exchanges/(.*)?$ index.php?
a=account&b=exchanges&page=$1 [L]
RewriteRule ^account/exchange/(.*)?$ index.php?
a=account&b=exchange&id=$1 [L]
RewriteRule ^account/referrals/(.*)?$ index.php?
a=account&b=referrals&page=$1 [L]
RewriteRule ^ref/(.*)?$ index.php?refid=$1 [L]
RewriteRule ^password-recovery/(.*)?$ index.php?a=password-
recovery&hash=$1 [L]
RewriteRule ^become_payment/(.*)?$ index.php?a=become_payment&id=$1 [L]`


问:
Why doesn't typescript check an option argument?
Why doesn't typescript show any type errors for the following example?

```<code>function fancyMethod({ option1 = true }: { option1?: boolean } = {}) {
    console.log(option1);
}

fancyMethod("abc");
fancyMethod(false);
fancyMethod(42);
</code>```

Try it yourself using this Playground Link

答:
So the type of the argument to fancyMethod is that is must be an object with optionally a boolean property option1.

All of the parameters you passed in are objects that don't have an option1 property but that's alright as it is optional, so in each case you'll just get the default option1 = true.

A shorter example that shows the same thing:

```<code>let x: { option1?: boolean } = "abc";
x = 42;
</code>```

Both the string and the number are compatible with a type where all of the properties are optional.

However, if you now try:

```<code>x = { foo: 1 };
</code>```

you get an error:

```<code>t.ts(11,7): error TS2322: Type '{ foo: number; }' is not assignable to type '{ option1?: boolean | undefined; }'.
  Object literal may only specify known properties, and 'foo' does not exist in type '{ option1?: boolean | undefined; }'.
</code>```

because there is additional checking if you pass in an object literal with properties that are not part of the type, and the same happens if you try to pass an object literal with additional properties to fancyMethod()

Body:
Why doesn't typescript show any type errors for the following example?

function fancyMethod({ option1 = true }: { option1?: boolean } = {}) {
    console.log(option1);
}

fancyMethod("abc");
fancyMethod(false);
fancyMethod(42);

Try it yourself using this Playground Link

Body:
So the type of the argument to fancyMethod is that is must be an object with optionally a boolean property option1.

All of the parameters you passed in are objects that don't have an option1 property but that's alright as it is optional, so in each case you'll just get the default option1 = true.

A shorter example that shows the same thing:

let x: { option1?: boolean } = "abc";
x = 42;

Both the string and the number are compatible with a type where all of the properties are optional.

However, if you now try:

x = { foo: 1 };

you get an error:

t.ts(11,7): error TS2322: Type '{ foo: number; }' is not assignable to type '{ option1?: boolean | undefined; }'.
  Object literal may only specify known properties, and 'foo' does not exist in type '{ option1?: boolean | undefined; }'.

because there is additional checking if you pass in an object literal with properties that are not part of the type, and the same happens if you try to pass an object literal with additional properties to fancyMethod()


问:
PhantomJS: curl: (22) The requested URL returned error: 404 Not Found
Tried installing phantomjs via brew, receive this error

==> Downloading https://github.com/ariya/phantomjs/archive/2.
      Already downloaded: /Library/Caches/Homebrew/phantomjs-2.0.0.tar.gz
      ==> Downloading https://gist.githubusercontent.com/mikemcquaid/db645f7cbeec4f3b1b2e/raw/e664ecc5c259344d5a73a84b52e472bf8ad3733

```<code>curl: (22) The requested URL returned error: 404 Not Found
Error: Failed to download resource "phantomjs--patch"
Download failed: https://gist.githubusercontent.com/mikemcquaid/db645f7cbeec4f3b1b2e/raw/e664ecc5c259344d5a73a84b52e472bf8ad3733e/phantomjs-yosemite.patch
</code>```

答:
Installing PhantomJS on Ubuntu

First, install or update to the latest system software.

```<code>sudo apt-get update
sudo apt-get install build-essential chrpath libssl-dev libxft-dev
</code>```

Install these packages needed by PhantomJS to work correctly.

```<code>sudo apt-get install libfreetype6 libfreetype6-dev
sudo apt-get install libfontconfig1 libfontconfig1-dev
</code>```

Get it from the PhantomJS website.

```<code>cd ~
export PHANTOM_JS="phantomjs-1.9.8-linux-x86_64"
wget https://bitbucket.org/ariya/phantomjs/downloads/$PHANTOM_JS.tar.bz2
sudo tar xvjf $PHANTOM_JS.tar.bz2
</code>```

Once downloaded, move Phantomjs folder to /usr/local/share/ and create a symlink:

```<code>sudo mv $PHANTOM_JS /usr/local/share
sudo ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin
</code>```

Now, It should have PhantomJS properly on your system.

phantomjs --version

Body:
Tried installing phantomjs via brew, receive this error

==> Downloading https://github.com/ariya/phantomjs/archive/2.
      Already downloaded: /Library/Caches/Homebrew/phantomjs-2.0.0.tar.gz
      ==> Downloading https://gist.githubusercontent.com/mikemcquaid/db645f7cbeec4f3b1b2e/raw/e664ecc5c259344d5a73a84b52e472bf8ad3733

curl: (22) The requested URL returned error: 404 Not Found
Error: Failed to download resource "phantomjs--patch"
Download failed: https://gist.githubusercontent.com/mikemcquaid/db645f7cbeec4f3b1b2e/raw/e664ecc5c259344d5a73a84b52e472bf8ad3733e/phantomjs-yosemite.patch

Body:
Installing PhantomJS on Ubuntu

First, install or update to the latest system software.

sudo apt-get update
sudo apt-get install build-essential chrpath libssl-dev libxft-dev

Install these packages needed by PhantomJS to work correctly.

sudo apt-get install libfreetype6 libfreetype6-dev
sudo apt-get install libfontconfig1 libfontconfig1-dev

Get it from the PhantomJS website.

cd ~
export PHANTOM_JS="phantomjs-1.9.8-linux-x86_64"
wget https://bitbucket.org/ariya/phantomjs/downloads/$PHANTOM_JS.tar.bz2
sudo tar xvjf $PHANTOM_JS.tar.bz2

Once downloaded, move Phantomjs folder to /usr/local/share/ and create a symlink:

sudo mv $PHANTOM_JS /usr/local/share
sudo ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin

Now, It should have PhantomJS properly on your system.

phantomjs --version


问:
Xamarin VS2015 designer not working
I am working with xamarin for visual studio 2015. For 2 days now the designer of the layout stopped working. It is very difficult to identify the problem cause i don't remember doing anything specific during these days.

Here is a screenshot of the error message

I have been trying to follow instructions from all over the web, including the xamarin suggestions, without any success.

Here is the detailed text of the exception:

```<code>java.lang.NoClassDefFoundError: com/android/utils/ILogger
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
    at java.lang.Class.getMethod0(Class.java:3018)
    at java.lang.Class.getMethod(Class.java:1784)
    at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: com.android.utils.ILogger
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more
Error: A JNI error has occurred, please check your installation and try again
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=350m; support was removed in 8.0
Exception in thread "main"
</code>```

What i already did is:
1. Added the enviromental variable MaxPermSize setting it to different sizes without any success.
2. Reinstalled Java runtime and Java SDK both for x86 and x64.
3. I have only in my system JAVA JRE 8 and SDK 1.8.0_102 x64.
4. Reinstalled the Android SDK tools.

So originally i have the question if there is any workaroung cause i really want to use xamarin but not without the designer?

答:
I found a solution, i'm using windows 10 on my machine (64-bit Windows), so instead of downgrading to java JDK 1.7, make sure to install the latest Xamarin updates since updates contains a lot of fixes.

To check for updates follow the link below.
Note: check for update more than once till you receive "Xamarin is up to date!"

Go to: Debug > Options

https://developer.xamarin.com/recipes/cross-platform/ide/change_updates_channel/#Change_the_Updates_Channel_in_Visual_Studio_2015_and_earlier

Title: Xamarin VS2015 designer not working

Body:
I am working with xamarin for visual studio 2015. For 2 days now the designer of the layout stopped working. It is very difficult to identify the problem cause i don't remember doing anything specific during these days.

Here is a screenshot of the error message

I have been trying to follow instructions from all over the web, including the xamarin suggestions, without any success.

Here is the detailed text of the exception:

java.lang.NoClassDefFoundError: com/android/utils/ILogger
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
    at java.lang.Class.getMethod0(Class.java:3018)
    at java.lang.Class.getMethod(Class.java:1784)
    at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: com.android.utils.ILogger
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more
Error: A JNI error has occurred, please check your installation and try again
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=350m; support was removed in 8.0
Exception in thread "main"

What i already did is:
1. Added the enviromental variable MaxPermSize setting it to different sizes without any success.
2. Reinstalled Java runtime and Java SDK both for x86 and x64.
3. I have only in my system JAVA JRE 8 and SDK 1.8.0_102 x64.
4. Reinstalled the Android SDK tools.

So originally i have the question if there is any workaroung cause i really want to use xamarin but not without the designer?


问:
Accessing List<Class> elements in Java
Please ignore any beginner mistakes if I make. Following is my issue:

I have a class Item :

```<code>@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
@Table(name = "item")
public class Item {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
//@ManyToOne
private Long id;
private String stream_item_key;
private String stream_item_date;
private String channel;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "item_workflow", joinColumns = @JoinColumn(name = "item_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "workflow_id", referencedColumnName = "id"))
private List<Workflow> workflow;
</code>```

Workflow is another class and Workflow has the following class members:

```<code>    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String actor;
    private String assignee;
    private String date;
    private String team;
    private String action;
</code>```

I have used JPA to join item and workflow and I am able to see the complete extract of the data. However in a different method I am trying to extract only Item.stream_item_date, Workflow.Actor and Workflow.date

I am able to extract Item.stream_item_date using the getStream_item_date() accessor but I am not sure how to access the List elements. I have researched Stackoverflow and I could not find any answers, all of them led to update index and other things. I am not sure if this is the right way to do it?

Thanks in advance for your answers!

答:
Thanks for the answer @JB Nizet </p>

```<code>Item items = this.getQueryOne();
// getQueryOne() returns the Item object
for (Workflow workflow: items.getWorkflow()) {
   System.out.println(workflow.getActor());
   System.out.println(workflow.getDate());
}
</code>```

Title: Accessing List<Class> elements in Java

Body:
Please ignore any beginner mistakes if I make. Following is my issue:

I have a class Item :

@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
@Table(name = "item")
public class Item {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
//@ManyToOne
private Long id;
private String stream_item_key;
private String stream_item_date;
private String channel;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "item_workflow", joinColumns = @JoinColumn(name = "item_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "workflow_id", referencedColumnName = "id"))
private List<Workflow> workflow;

Workflow is another class and Workflow has the following class members:

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String actor;
    private String assignee;
    private String date;
    private String team;
    private String action;

I have used JPA to join item and workflow and I am able to see the complete extract of the data. However in a different method I am trying to extract only Item.stream_item_date, Workflow.Actor and Workflow.date

I am able to extract Item.stream_item_date using the getStream_item_date() accessor but I am not sure how to access the List elements. I have researched Stackoverflow and I could not find any answers, all of them led to update index and other things. I am not sure if this is the right way to do it?

Thanks in advance for your answers!

Body:
Thanks for the answer @JB Nizet

Item items = this.getQueryOne();
// getQueryOne() returns the Item object
for (Workflow workflow: items.getWorkflow()) {
   System.out.println(workflow.getActor());
   System.out.println(workflow.getDate());
}


问:
Is there a driver for SQLite in Java?
I did some research on their site, and after some Google-ing, it looks like there are only drivers for C & C++. Is there an open driver that I can use with SQLLite, or is there a way I can use it with JDBC?

UPDATE

I'm doing development on Linux, but I would like to keep my options open. Native libraries would work, but wouldn't give the cross-platform freedom that I'm used to with Java.

答:
I have used org:xerial:sqlite-jdbc

Example Groovy script:

```<code>@Grab(group='org.xerial', module='sqlite-jdbc', version='[3.6.4,)')
sql = groovy.sql.Sql.newInstance("jdbc:sqlite:test.db","org.sqlite.JDBC")
sql.execute("create table students(name, age)")
</code>```

(note: 3.6.4 is not the latest version)

Title: Is there a driver for SQLite in Java?

Body:
I have used org:xerial:sqlite-jdbc

Example Groovy script:

@Grab(group='org.xerial', module='sqlite-jdbc', version='[3.6.4,)')
sql = groovy.sql.Sql.newInstance("jdbc:sqlite:test.db","org.sqlite.JDBC")
sql.execute("create table students(name, age)")

(note: 3.6.4 is not the latest version)


问:
Js autoload function is not working on flexigrid
Well... I am using flexigrid and grocery crud and i am trying to autoload table with js function. I have followed these steps to do this but it isn't working. Table should auto refresh each 5 seconds when something new is added. What am i doing wrong?

js file contain

```<code>var interval = null;

window.onload = function() {
    interval = setInterval(callFunc, 5000);
};

function callFunc() {
       $("#ajax_refresh_and_loading").trigger("click");
}
</code>```

js calling on controller

```<code>$jsfile = base_url('index.php/assets/bootstrap/js/refresh.js');
        $crud->set_js($jsfile);
</code>```

Steps i have followed

Mini tutorial

答:
I just changed the route and deleted base_url() because it was useless.</p>

```<code>$jsfile = 'assets/bootstrap/js/refresh.js';

        $crud->set_js($jsfile);
</code>```

Body:
Well... I am using flexigrid and grocery crud and i am trying to autoload table with js function. I have followed these steps to do this but it isn't working. Table should auto refresh each 5 seconds when something new is added. What am i doing wrong?

js file contain

var interval = null;

window.onload = function() {
    interval = setInterval(callFunc, 5000);
};

function callFunc() {
       $("#ajax_refresh_and_loading").trigger("click");
}

js calling on controller

$jsfile = base_url('index.php/assets/bootstrap/js/refresh.js');
        $crud->set_js($jsfile);

Steps i have followed

Mini tutorial

Body:
I just changed the route and deleted base_url() because it was useless.

$jsfile = 'assets/bootstrap/js/refresh.js';

        $crud->set_js($jsfile);


问:
How to check SysML stereotypes with Acceleo?
I'm using Eclipse 4.6.3 (Neon.3) with Acceleo 3.6.6, Paprus 2.0.3 and Papyrus SysML 1.4 0.10.1.
How can I check from an Acceleo MTL script, whether a class of my model has the SysML Block stereotype applied? The method getAppliedStereotypes() only works for my own defined stereotypes but not for SysML 1.4 ones.

In my UML model (Papyrus project) I have created

"Class1" to which I have applied my own stereotype "MyProfile::MyStereotype" created in the "Model Explorer" via "Profile"/"Update Profile" and

"Class2" to which I have applied "SysML::Blocks::Block" under "Properties"/"Profile"/"Applied stereotypes"

In the Acceleo project in generate.mtl, if I'm calling getAppliedStereotypes() on each of these 2 classes, I only get the stereotype of "Class1", but none for "Class2".

model.uml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xmi:XMI xmi:version="20131001" xmlns:xmi="http://www.omg.org/spec/XMI/20131001" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:Blocks="http://www.eclipse.org/papyrus/sysml/1.4/SysML/Blocks" xmlns:MyProfile="http:///schemas/MyProfile/__okhIEO5EeezquIZgVUJBA/0" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" xmlns:uml="http://www.eclipse.org/uml2/5.0.0/UML" xsi:schemaLocation="http://www.eclipse.org/papyrus/sysml/1.4/SysML/Blocks http://www.eclipse.org/papyrus/sysml/1.4/SysML#//blocks http:///schemas/MyProfile/__okhIEO5EeezquIZgVUJBA/0 MyProfile.profile.uml#__olvQUO5EeezquIZgVUJBA">
  <uml:Model xmi:id="_Jl27kEO4EeezquIZgVUJBA" name="RootElement">
    <packagedElement xmi:type="uml:Class" xmi:id="_LpXEYEO4EeezquIZgVUJBA" name="Class1"/>
    <packagedElement xmi:type="uml:Class" xmi:id="_ZFGQwEO4EeezquIZgVUJBA" name="Class2"/>
    <profileApplication xmi:type="uml:ProfileApplication" xmi:id="_SLhJ0EO4EeezquIZgVUJBA">
      <eAnnotations xmi:type="ecore:EAnnotation" xmi:id="_SLi_AEO4EeezquIZgVUJBA" source="http://www.eclipse.org/uml2/2.0.0/UML">
        <references xmi:type="ecore:EPackage" href="http://www.eclipse.org/papyrus/sysml/1.4/SysML#//blocks"/>
      </eAnnotations>
      <appliedProfile xmi:type="uml:Profile" href="pathmap://SysML14_PROFILES/SysML.profile.uml#SysML.package_packagedElement_Blocks"/>
    </profileApplication>
    <profileApplication xmi:type="uml:ProfileApplication" xmi:id="__om9ZkO5EeezquIZgVUJBA">
      <eAnnotations xmi:type="ecore:EAnnotation" xmi:id="__om9Z0O5EeezquIZgVUJBA" source="http://www.eclipse.org/uml2/2.0.0/UML">
        <references xmi:type="ecore:EPackage" href="MyProfile.profile.uml#__olvQUO5EeezquIZgVUJBA"/>
      </eAnnotations>
      <appliedProfile xmi:type="uml:Profile" href="MyProfile.profile.uml#__og2wEO5EeezquIZgVUJBA"/>
    </profileApplication>
  </uml:Model>
  <Blocks:Block xmi:id="_bBkkgEO4EeezquIZgVUJBA" base_Class="_ZFGQwEO4EeezquIZgVUJBA"/>
  <MyProfile:MyStereotype xmi:id="__ooykEO5EeezquIZgVUJBA" base_Class="_LpXEYEO4EeezquIZgVUJBA"/>
</xmi:XMI>
</code>```

MyProfile.profile.uml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<uml:Profile xmi:version="20131001" xmlns:xmi="http://www.omg.org/spec/XMI/20131001" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" xmlns:uml="http://www.eclipse.org/uml2/5.0.0/UML" xmi:id="__og2wEO5EeezquIZgVUJBA" name="MyProfile" metaclassReference="__oiE4EO5EeezquIZgVUJBA">
  <eAnnotations xmi:type="ecore:EAnnotation" xmi:id="__olvQEO5EeezquIZgVUJBA" source="http://www.eclipse.org/uml2/2.0.0/UML">
    <contents xmi:type="ecore:EPackage" xmi:id="__olvQUO5EeezquIZgVUJBA" name="MyProfile" nsURI="http:///schemas/MyProfile/__okhIEO5EeezquIZgVUJBA/0" nsPrefix="MyProfile">
      <eAnnotations xmi:type="ecore:EAnnotation" xmi:id="__om9YEO5EeezquIZgVUJBA" source="PapyrusVersion">
        <details xmi:type="ecore:EStringToStringMapEntry" xmi:id="__om9YUO5EeezquIZgVUJBA" key="Version" value="0.0.1"/>
        <details xmi:type="ecore:EStringToStringMapEntry" xmi:id="__om9YkO5EeezquIZgVUJBA" key="Comment" value=""/>
        <details xmi:type="ecore:EStringToStringMapEntry" xmi:id="__om9Y0O5EeezquIZgVUJBA" key="Copyright" value=""/>
        <details xmi:type="ecore:EStringToStringMapEntry" xmi:id="__om9ZEO5EeezquIZgVUJBA" key="Date" value="28.05.17 17:26"/>
        <details xmi:type="ecore:EStringToStringMapEntry" xmi:id="__om9ZUO5EeezquIZgVUJBA" key="Author" value=""/>
      </eAnnotations>
      <eClassifiers xmi:type="ecore:EClass" xmi:id="__olvQkO5EeezquIZgVUJBA" name="MyStereotype">
        <eAnnotations xmi:type="ecore:EAnnotation" xmi:id="__olvQ0O5EeezquIZgVUJBA" source="http://www.eclipse.org/uml2/2.0.0/UML" references="__og2wUO5EeezquIZgVUJBA"/>
        <eStructuralFeatures xmi:type="ecore:EReference" xmi:id="__olvREO5EeezquIZgVUJBA" name="base_Class" ordered="false" lowerBound="1">
          <eType xmi:type="ecore:EClass" href="http://www.eclipse.org/uml2/5.0.0/UML#//Class"/>
        </eStructuralFeatures>
      </eClassifiers>
    </contents>
  </eAnnotations>
  <elementImport xmi:type="uml:ElementImport" xmi:id="__oiE4EO5EeezquIZgVUJBA">
    <importedElement xmi:type="uml:Class" href="pathmap://UML_METAMODELS/UML.metamodel.uml#Class"/>
  </elementImport>
  <packagedElement xmi:type="uml:Stereotype" xmi:id="__og2wUO5EeezquIZgVUJBA" name="MyStereotype">
    <ownedAttribute xmi:type="uml:Property" xmi:id="__oir8kO5EeezquIZgVUJBA" name="base_Class" association="__oir8EO5EeezquIZgVUJBA">
      <type xmi:type="uml:Class" href="pathmap://UML_METAMODELS/UML.metamodel.uml#Class"/>
    </ownedAttribute>
  </packagedElement>
  <packagedElement xmi:type="uml:Extension" xmi:id="__oir8EO5EeezquIZgVUJBA" name="Class_MyStereotype" memberEnd="__oir8UO5EeezquIZgVUJBA __oir8kO5EeezquIZgVUJBA">
    <ownedEnd xmi:type="uml:ExtensionEnd" xmi:id="__oir8UO5EeezquIZgVUJBA" name="extension_MyStereotype" type="__og2wUO5EeezquIZgVUJBA" aggregation="composite" association="__oir8EO5EeezquIZgVUJBA"/>
  </packagedElement>
</uml:Profile>
</code>```

generate.mtl:

```<code>[comment encoding = UTF-8 /]
[module generate('http://www.eclipse.org/papyrus/sysml/1.4/SysML/Blocks', 'http://www.eclipse.org/uml2/5.0.0/UML')]

[template public generateModel(model : Model)]
[comment @main/]
[file (model.name, false, 'UTF-8')]
    [for (c : Class | model.eContents(Class))]
[c.name/]
        [for (s : Stereotype | c.getAppliedStereotypes())]
  [s/]
        [/for]
    [/for]
[/file]
[/template]
</code>```

output:

```<code>Class1
  org.eclipse.uml2.uml.internal.impl.StereotypeImpl@485a3466 (name: MyStereotype, visibility: <unset>) (isLeaf: false, isAbstract: false, isFinalSpecialization: false) (isActive: false)
Class2
</code>```

papyrus_project:

```<code>papyrus_project
papyrus_project/model.uml
papyrus_project/MyProfile.profile.di
papyrus_project/MyProfile.profile.notation
papyrus_project/model.di
papyrus_project/.project
papyrus_project/MyProfile.profile.uml
papyrus_project/model.notation
</code>```

acceleo_project:

```<code>acceleo_project
acceleo_project/src
acceleo_project/src/acceleo_project
acceleo_project/src/acceleo_project/main
acceleo_project/src/acceleo_project/main/generate.mtl
acceleo_project/src/acceleo_project/main/Generate.java
acceleo_project/src/acceleo_project/Activator.java
acceleo_project/dst
acceleo_project/dst/RootElement
acceleo_project/build.properties
acceleo_project/tasks
acceleo_project/tasks/generate.xml
acceleo_project/tasks/generateTarget.xml
acceleo_project/.project
acceleo_project/bin
acceleo_project/bin/acceleo_project
acceleo_project/bin/acceleo_project/Activator.class
acceleo_project/bin/acceleo_project/main
acceleo_project/bin/acceleo_project/main/Generate.class
acceleo_project/bin/acceleo_project/main/generate.mtl
acceleo_project/bin/acceleo_project/main/generate.emtl
acceleo_project/.classpath
acceleo_project/META-INF
acceleo_project/META-INF/MANIFEST.MF
</code>```

答:
I'm not really sure what's happening in there but I'll take a wild guess and say Acceleo cannot resolve the SysML profile here.

If you look at your generated launcher (the java file beside your "@main" mtl template), you will see a "registerPackages" method. You will need to find the proper URI to register the SysML profile for use in your application; you can see an example of how it was done for previous versions of papyrus on the Acceleo FAQ.

Body:
I'm using Eclipse 4.6.3 (Neon.3) with Acceleo 3.6.6, Paprus 2.0.3 and Papyrus SysML 1.4 0.10.1.
How can I check from an Acceleo MTL script, whether a class of my model has the SysML Block stereotype applied? The method getAppliedStereotypes() only works for my own defined stereotypes but not for SysML 1.4 ones.

In my UML model (Papyrus project) I have created

"Class1" to which I have applied my own stereotype "MyProfile::MyStereotype" created in the "Model Explorer" via "Profile"/"Update Profile" and

"Class2" to which I have applied "SysML::Blocks::Block" under "Properties"/"Profile"/"Applied stereotypes"

In the Acceleo project in generate.mtl, if I'm calling getAppliedStereotypes() on each of these 2 classes, I only get the stereotype of "Class1", but none for "Class2".

model.uml:

<?xml version="1.0" encoding="UTF-8"?>
<xmi:XMI xmi:version="20131001" xmlns:xmi="http://www.omg.org/spec/XMI/20131001" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:Blocks="http://www.eclipse.org/papyrus/sysml/1.4/SysML/Blocks" xmlns:MyProfile="http:///schemas/MyProfile/__okhIEO5EeezquIZgVUJBA/0" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" xmlns:uml="http://www.eclipse.org/uml2/5.0.0/UML" xsi:schemaLocation="http://www.eclipse.org/papyrus/sysml/1.4/SysML/Blocks http://www.eclipse.org/papyrus/sysml/1.4/SysML#//blocks http:///schemas/MyProfile/__okhIEO5EeezquIZgVUJBA/0 MyProfile.profile.uml#__olvQUO5EeezquIZgVUJBA">
  <uml:Model xmi:id="_Jl27kEO4EeezquIZgVUJBA" name="RootElement">
    <packagedElement xmi:type="uml:Class" xmi:id="_LpXEYEO4EeezquIZgVUJBA" name="Class1"/>
    <packagedElement xmi:type="uml:Class" xmi:id="_ZFGQwEO4EeezquIZgVUJBA" name="Class2"/>
    <profileApplication xmi:type="uml:ProfileApplication" xmi:id="_SLhJ0EO4EeezquIZgVUJBA">
      <eAnnotations xmi:type="ecore:EAnnotation" xmi:id="_SLi_AEO4EeezquIZgVUJBA" source="http://www.eclipse.org/uml2/2.0.0/UML">
        <references xmi:type="ecore:EPackage" href="http://www.eclipse.org/papyrus/sysml/1.4/SysML#//blocks"/>
      </eAnnotations>
      <appliedProfile xmi:type="uml:Profile" href="pathmap://SysML14_PROFILES/SysML.profile.uml#SysML.package_packagedElement_Blocks"/>
    </profileApplication>
    <profileApplication xmi:type="uml:ProfileApplication" xmi:id="__om9ZkO5EeezquIZgVUJBA">
      <eAnnotations xmi:type="ecore:EAnnotation" xmi:id="__om9Z0O5EeezquIZgVUJBA" source="http://www.eclipse.org/uml2/2.0.0/UML">
        <references xmi:type="ecore:EPackage" href="MyProfile.profile.uml#__olvQUO5EeezquIZgVUJBA"/>
      </eAnnotations>
      <appliedProfile xmi:type="uml:Profile" href="MyProfile.profile.uml#__og2wEO5EeezquIZgVUJBA"/>
    </profileApplication>
  </uml:Model>
  <Blocks:Block xmi:id="_bBkkgEO4EeezquIZgVUJBA" base_Class="_ZFGQwEO4EeezquIZgVUJBA"/>
  <MyProfile:MyStereotype xmi:id="__ooykEO5EeezquIZgVUJBA" base_Class="_LpXEYEO4EeezquIZgVUJBA"/>
</xmi:XMI>

MyProfile.profile.uml:

<?xml version="1.0" encoding="UTF-8"?>
<uml:Profile xmi:version="20131001" xmlns:xmi="http://www.omg.org/spec/XMI/20131001" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" xmlns:uml="http://www.eclipse.org/uml2/5.0.0/UML" xmi:id="__og2wEO5EeezquIZgVUJBA" name="MyProfile" metaclassReference="__oiE4EO5EeezquIZgVUJBA">
  <eAnnotations xmi:type="ecore:EAnnotation" xmi:id="__olvQEO5EeezquIZgVUJBA" source="http://www.eclipse.org/uml2/2.0.0/UML">
    <contents xmi:type="ecore:EPackage" xmi:id="__olvQUO5EeezquIZgVUJBA" name="MyProfile" nsURI="http:///schemas/MyProfile/__okhIEO5EeezquIZgVUJBA/0" nsPrefix="MyProfile">
      <eAnnotations xmi:type="ecore:EAnnotation" xmi:id="__om9YEO5EeezquIZgVUJBA" source="PapyrusVersion">

      </eAnnotations>
      <eClassifiers xmi:type="ecore:EClass" xmi:id="__olvQkO5EeezquIZgVUJBA" name="MyStereotype">
        <eAnnotations xmi:type="ecore:EAnnotation" xmi:id="__olvQ0O5EeezquIZgVUJBA" source="http://www.eclipse.org/uml2/2.0.0/UML" references="__og2wUO5EeezquIZgVUJBA"/>
        <eStructuralFeatures xmi:type="ecore:EReference" xmi:id="__olvREO5EeezquIZgVUJBA" name="base_Class" ordered="false" lowerBound="1">
          <eType xmi:type="ecore:EClass" href="http://www.eclipse.org/uml2/5.0.0/UML#//Class"/>
        </eStructuralFeatures>
      </eClassifiers>
    </contents>
  </eAnnotations>
  <elementImport xmi:type="uml:ElementImport" xmi:id="__oiE4EO5EeezquIZgVUJBA">
    <importedElement xmi:type="uml:Class" href="pathmap://UML_METAMODELS/UML.metamodel.uml#Class"/>
  </elementImport>
  <packagedElement xmi:type="uml:Stereotype" xmi:id="__og2wUO5EeezquIZgVUJBA" name="MyStereotype">
    <ownedAttribute xmi:type="uml:Property" xmi:id="__oir8kO5EeezquIZgVUJBA" name="base_Class" association="__oir8EO5EeezquIZgVUJBA">
      <type xmi:type="uml:Class" href="pathmap://UML_METAMODELS/UML.metamodel.uml#Class"/>
    </ownedAttribute>
  </packagedElement>
  <packagedElement xmi:type="uml:Extension" xmi:id="__oir8EO5EeezquIZgVUJBA" name="Class_MyStereotype" memberEnd="__oir8UO5EeezquIZgVUJBA __oir8kO5EeezquIZgVUJBA">
    <ownedEnd xmi:type="uml:ExtensionEnd" xmi:id="__oir8UO5EeezquIZgVUJBA" name="extension_MyStereotype" type="__og2wUO5EeezquIZgVUJBA" aggregation="composite" association="__oir8EO5EeezquIZgVUJBA"/>
  </packagedElement>
</uml:Profile>

generate.mtl:

[comment encoding = UTF-8 /]
[module generate('http://www.eclipse.org/papyrus/sysml/1.4/SysML/Blocks', 'http://www.eclipse.org/uml2/5.0.0/UML')]

[template public generateModel(model : Model)]
[comment @main/]
[file (model.name, false, 'UTF-8')]
    [for (c : Class | model.eContents(Class))]
[c.name/]
        [for (s : Stereotype | c.getAppliedStereotypes())]
  [s/]
        [/for]
    [/for]
[/file]
[/template]

output:

Class1
  org.eclipse.uml2.uml.internal.impl.StereotypeImpl@485a3466 (name: MyStereotype, visibility: <unset>) (isLeaf: false, isAbstract: false, isFinalSpecialization: false) (isActive: false)
Class2

papyrus_project:

papyrus_project
papyrus_project/model.uml
papyrus_project/MyProfile.profile.di
papyrus_project/MyProfile.profile.notation
papyrus_project/model.di
papyrus_project/.project
papyrus_project/MyProfile.profile.uml
papyrus_project/model.notation

acceleo_project:

acceleo_project
acceleo_project/src
acceleo_project/src/acceleo_project
acceleo_project/src/acceleo_project/main
acceleo_project/src/acceleo_project/main/generate.mtl
acceleo_project/src/acceleo_project/main/Generate.java
acceleo_project/src/acceleo_project/Activator.java
acceleo_project/dst
acceleo_project/dst/RootElement
acceleo_project/build.properties
acceleo_project/tasks
acceleo_project/tasks/generate.xml
acceleo_project/tasks/generateTarget.xml
acceleo_project/.project
acceleo_project/bin
acceleo_project/bin/acceleo_project
acceleo_project/bin/acceleo_project/Activator.class
acceleo_project/bin/acceleo_project/main
acceleo_project/bin/acceleo_project/main/Generate.class
acceleo_project/bin/acceleo_project/main/generate.mtl
acceleo_project/bin/acceleo_project/main/generate.emtl
acceleo_project/.classpath
acceleo_project/META-INF
acceleo_project/META-INF/MANIFEST.MF


问:
Gradle compiler output when building C/C++ code
I'm building C/C++ code with gradle under Linux (gcc) and Windows (VS10) like it's described in Building native software documentation of gradle.

The build process is fine and I can start my application. If errors occur during the build process you can see the compiler output like warnings and errors on the console. This output is additionally written to a file: build/tmp/"TaskName"/output.txt.
The problem is that this output is not displayed on the console if the build runs without errors, nevertheless the file is written.

I'm searching for a way to display the compiler output like warnings or errors on console even if the build succeeded.

It's possible to start the gradle build with a higher log level: gradle build --info, but there is so much addional output that I do not want.

I already tried something like the code below in the build.gradle file to set the log level  only for all compiling tasks, but it makes no difference as I would start the gradle build just with: gradle build.

```<code>tasks.whenTaskAdded { task ->
   if (task instanceof CCompile || task instanceof CppCompile) {
      logging.setLevel(LogLevel.INFO)
   }
}
</code>```

My question:

Is there any way to get the compiler errors/warnings on the console without the overhead? Is it possible at all to set the LogLevel for some tasks? If so what's wrong with the code above?

Any help will be appreciated.

答: just add a cat outputfile.txt after you have run your gradle command

Body:
I'm building C/C++ code with gradle under Linux (gcc) and Windows (VS10) like it's described in Building native software documentation of gradle.

The build process is fine and I can start my application. If errors occur during the build process you can see the compiler output like warnings and errors on the console. This output is additionally written to a file: build/tmp/"TaskName"/output.txt.
The problem is that this output is not displayed on the console if the build runs without errors, nevertheless the file is written.

I'm searching for a way to display the compiler output like warnings or errors on console even if the build succeeded.

It's possible to start the gradle build with a higher log level: gradle build --info, but there is so much addional output that I do not want.

I already tried something like the code below in the build.gradle file to set the log level  only for all compiling tasks, but it makes no difference as I would start the gradle build just with: gradle build.

tasks.whenTaskAdded { task ->
   if (task instanceof CCompile || task instanceof CppCompile) {
      logging.setLevel(LogLevel.INFO)
   }
}

My question:

Is there any way to get the compiler errors/warnings on the console without the overhead? Is it possible at all to set the LogLevel for some tasks? If so what's wrong with the code above?

Any help will be appreciated.


问:
How to turn off information messages in Apache CXF dynamic client?
I made a dynamic client in java using Apache CXF. It works well and does all the things it is supposed to.

The one thing that is annoying me a bit, is that every time I start the program, it floods the console with information messages.

So I am wondering if it is possible to turn these off somehow? If no then I will just have to live with it.

答:
Disclaimer: I have to admit that I never used CXF.

Judging from the dependencies CXF uses Commons Logging for logging. You should head there in order to find out how to do this. Most commonly this involves finding out who logs what and then raising the log level of those classes to something like ERROR or NONE.


问:
Cannot compile bazel needed for tensorflow-android
I'm trying to explore the tensorflow android demo. I want to adapt the app using android studio.

However when I simply follow the instructions I get compilation errors no matter what I do:

Trying to compile tensorflow using bazel and NDK r12b:

```<code>$bazel build -c opt //tensorflow/examples/android:tensorflow_demo
ERROR: /home/myUser/libs/tensorflow_android/WORKSPACE:3:1: //external:io_bazel_rules_closure: no such attribute 'urls' in 'http_archive' rule.
ERROR: /home/myUser/libs/tensorflow_android/WORKSPACE:3:1: //external:io_bazel_rules_closure: missing value for mandatory attribute 'url' in 'http_archive' rule.
ERROR: com.google.devtools.build.lib.packages.BuildFileContainsErrorsException: error loading package '': Encountered error while reading extension file 'closure/defs.bzl': no such package '@io_bazel_rules_closure//closure': error loading package 'external': Could not load //external package.
INFO: Elapsed time: 0.129s
</code>```

Trying to compile a newer version of bazel following this advice:

```<code>$bazel version
Build label: 0.2.3-jdk7 // This is my current version of bazel
</code>```

via apt-get:

```<code>$sudo apt-get upgrade bazel
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
E: Unable to locate package bazel
</code>```

from source (tried bazel-0.4.2 and bazel-0.5.0):

```<code>$./compile.sh
INFO: You can skip this first step by providing a path to the bazel binary as second argument:
INFO:    ./compile.sh compile /path/to/bazel
  Building Bazel from scratch
ERROR: JDK version (1.7) is lower than 1.8, please set $JAVA_HOME.
</code>```

or

```<code>$bazel build //src:bazel
ERROR: /home/myUser/libs/bazel/bazel-0.4.2/tools/build_rules/genproto.bzl:45:16: Traceback (most recent call last):
    File "/home/myUser/libs/bazel/bazel-0.4.2/tools/build_rules/genproto.bzl", line 42
        rule(gensrcjar_impl, attrs = {"src": at..."), <2 more arguments>), "_proto_compiler": attr.label(default = Label("//third_party/p..."), <4 more arguments>), "_jar": attr.label(default = Label("@bazel_tools//t..."), <4 more arguments>), "_jdk": attr.label(default = Label("@bazel_tools//t..."), ...)}, ..."})
    File "/home/myUser/libs/bazel/bazel-0.4.2/tools/build_rules/genproto.bzl", line 45, in rule
        attr.label(allow_files = proto_filetype, sing...)
allow_files should be a boolean or a filetype object.
ERROR: /home/myUser/libs/bazel/bazel-0.4.2/src/BUILD:130:1: error loading package 'src/main/protobuf': Extension file 'tools/build_rules/genproto.bzl' has errors and referenced by '//src:embedded_tools'.
ERROR: Loading failed; build aborted.
INFO: Elapsed time: 0.251s
</code>```

switching aroung java-versions to see whether the bazel compiling issues come from there:

```<code>$sudo update-alternatives --config java
There are 4 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                            Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-8-oracle/jre/bin/java          1074      auto mode
  1            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1071      manual mode
* 2            /usr/lib/jvm/java-7-oracle/jre/bin/java          1072      manual mode
  3            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1069      manual mode
  4            /usr/lib/jvm/java-8-oracle/jre/bin/java          1074      manual mode
</code>```

No luck so far :-/. Has anyone successfully compiled tensorflow for android from source?

What version of Tensorflow, NDK, bazel, java are required / compatible with each other? Do I really need bazel? (never worked with it anyway) Can't I just compile the android demo in android-studio like any other app?

I'm using Ubuntu 14.04, Cuda8.0, cudnn_v5.1, Titan X Pascal (not sure if these things matter)

答:
Installing Bazel on Ubuntu can be done without compiling.

Follow all steps of the dedicated documentation: Install Bazel on Ubuntu

Body:
I'm trying to explore the tensorflow android demo. I want to adapt the app using android studio.

However when I simply follow the instructions I get compilation errors no matter what I do:

Trying to compile tensorflow using bazel and NDK r12b:

$bazel build -c opt //tensorflow/examples/android:tensorflow_demo
ERROR: /home/myUser/libs/tensorflow_android/WORKSPACE:3:1: //external:io_bazel_rules_closure: no such attribute 'urls' in 'http_archive' rule.
ERROR: /home/myUser/libs/tensorflow_android/WORKSPACE:3:1: //external:io_bazel_rules_closure: missing value for mandatory attribute 'url' in 'http_archive' rule.
ERROR: com.google.devtools.build.lib.packages.BuildFileContainsErrorsException: error loading package '': Encountered error while reading extension file 'closure/defs.bzl': no such package '@io_bazel_rules_closure//closure': error loading package 'external': Could not load //external package.
INFO: Elapsed time: 0.129s

Trying to compile a newer version of bazel following this advice:

$bazel version
Build label: 0.2.3-jdk7 // This is my current version of bazel

via apt-get:

$sudo apt-get upgrade bazel
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
E: Unable to locate package bazel

from source (tried bazel-0.4.2 and bazel-0.5.0):

$./compile.sh
INFO: You can skip this first step by providing a path to the bazel binary as second argument:
INFO:    ./compile.sh compile /path/to/bazel
  Building Bazel from scratch
ERROR: JDK version (1.7) is lower than 1.8, please set $JAVA_HOME.

or

$bazel build //src:bazel
ERROR: /home/myUser/libs/bazel/bazel-0.4.2/tools/build_rules/genproto.bzl:45:16: Traceback (most recent call last):
    File "/home/myUser/libs/bazel/bazel-0.4.2/tools/build_rules/genproto.bzl", line 42
        rule(gensrcjar_impl, attrs = {"src": at..."), <2 more arguments>), "_proto_compiler": attr.label(default = Label("//third_party/p..."), <4 more arguments>), "_jar": attr.label(default = Label("@bazel_tools//t..."), <4 more arguments>), "_jdk": attr.label(default = Label("@bazel_tools//t..."), ...)}, ..."})
    File "/home/myUser/libs/bazel/bazel-0.4.2/tools/build_rules/genproto.bzl", line 45, in rule
        attr.label(allow_files = proto_filetype, sing...)
allow_files should be a boolean or a filetype object.
ERROR: /home/myUser/libs/bazel/bazel-0.4.2/src/BUILD:130:1: error loading package 'src/main/protobuf': Extension file 'tools/build_rules/genproto.bzl' has errors and referenced by '//src:embedded_tools'.
ERROR: Loading failed; build aborted.
INFO: Elapsed time: 0.251s

switching aroung java-versions to see whether the bazel compiling issues come from there:

$sudo update-alternatives --config java
There are 4 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                            Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-8-oracle/jre/bin/java          1074      auto mode
  1            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1071      manual mode
* 2            /usr/lib/jvm/java-7-oracle/jre/bin/java          1072      manual mode
  3            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1069      manual mode
  4            /usr/lib/jvm/java-8-oracle/jre/bin/java          1074      manual mode

No luck so far :-/. Has anyone successfully compiled tensorflow for android from source?

What version of Tensorflow, NDK, bazel, java are required / compatible with each other? Do I really need bazel? (never worked with it anyway) Can't I just compile the android demo in android-studio like any other app?

I'm using Ubuntu 14.04, Cuda8.0, cudnn_v5.1, Titan X Pascal (not sure if these things matter)


问:
the simcardio is not available in java 1.7?
I am trying to work the Java smartcardio API but I can not find its classes in Java 1.7.  At this page stands it is in JSR 268 which was released on 11 Dec, 2006
https://docs.oracle.com/javase/7/docs/jre/api/security/smartcardio/spec/
Do someone know the reason why I can not import the ATR classes? Do I have to import the api? if yes where can I find the jar?

答:
The Smart Card I/O API is available in JDK 7, I am able to import its classes successfully.

The problem lies in your environment.


问:
How to update edited row in DataTables
I am trying to edit row in a Datatable.Data is loading from the database.after clicking on row popup will come. then editing the field after clicking on submit button it's not updating.
In console network error is 403.
Forbidden. How to update edited row ? </p>

```<code>var workorder_path = "/dashboard/workorder_list/0/?format=json";

var editor = new $.fn.dataTable.Editor( {
    ajax: {

edit: {
                        type: 'PUT',
                        dataType:"json",
                        contentType: "application/json",
                        url: '/dashboard/workorder_list/0/?format=json',
                        data: function ( d ) {
                            return JSON.stringify( d );
                        }
                    },

  },
    table: "#workorder_table",
    idSrc: "id",
    fields: [
        { label: "ID:", name: "id" },
        { label: "Task:",   name: "task.name" },
        { label: "Description:",   name: "description" },

        { label: "Start Date:",   name: "start_date",
                "type": "datetime" },
        { label: "End Date:",   name: "end_date",
                "type": "datetime" }
    ]
} );

var workorder_table = $('#workorder_table').dataTable({
    dom: 'Blfrtip',
    JQueryUI: true,
    bPaginate: false,
    sScrollX: "100%",
    responsive: true,
    select: true,
    buttons: [
        {
            text: 'New',
            action: function () {
                create_workorder_window();
            },
            className: 'btn btn-warning btn-outline'
        },
        { extend: "edit",   editor: editor, className: 'btn btn-warning btn-outline' },
       // { extend: "create", editor: editor },
        { extend: 'colvis', text: 'Show', className: 'btn btn-warning btn-outline'}
    ],
    ajax: {
        url: workorder_path,
        dataSrc: ''
    },
    columns: [
        {"data": "id", "class": "workorder_id"},
        {"data": "thumb", "render": function(data, type, row) {
                                        return `<a href=` + data + ` data-fancybox> <img src=` + data + ` width="80" height="45"> </a>`;
                                    }},
        {"data": "task.name"},
        {"data": "description"},
        {"data": "status", "class":"v-a-m", "render": function (status, type, row) {
                                                return `<div class="media media-auto">
                                                            <div class="media-left">
                                                                <div class="avatar">
                                                                    <img class="media-object img-circle"
                                                                         src=${ status.image }
                                                                         alt=${ status.name }
                                                                         title=${ status.name }>
                                                                </div>
                                                            </div>
                                                           <div class="media-body">
                                                                <span class="media-heading">${ status.name }</span>
                                                            </div>
                                                        </div>`;

        } },
        {"data": "start_date", "visible": false},
        {"data": "end_date", "visible": false},
        {"data": "assign_to", "width": "400px", "defaultContent": "None", "render": function (assign_to, type, row) {

                                                return `<div class="media media-auto">
                                                        <div class="media-left">
                                                            <div class="avatar">
                                                                <img class="media-object img-circle"
                                                                     src=${ assign_to.photo }
                                                                     alt=${ assign_to.official_name }>
                                                            </div>
                                                        </div>
                                                        <div class="media-body">
                                                            <span class="media-heading text-white">${ assign_to.official_name }</span>
                                                            <br>
                                                            <span class="text-gray-lighter"><span>${ assign_to.designation.designation }</span></span>
                                                        </div>
                                                    </div>`

        } },
        {"data": "creation_time", "visible": false},
        {"data": "modified_time", "visible": false}
    ]
});
</code>```

答:
You are calling same function for both (to load data in data table as well as to update a record), I mean the URL that you have mentioned in your question.

So, inside your edit ajax function, you need to call another server side method, where you can pass your data. For example,

```<code>[HttpPut]
public returnType EditRecord(int id, WorkorderModel model)
 {
   //Here you can update the record then return a success message or whatever
   return message;
 }
</code>```

Note:  See, I don't know in which Language you are writing. As I'm writing in C#, so I added HttpPut attribute on top of the EditRecord method, to make it PUT. You need to change it accordingly.

Then, from your client side edit ajax, you can call it like this,

```<code>url: '/dashboard/EditRecord/'+d.id,
</code>```

Just change the URL, that you have written in your ajax edit. See, here d.id is nothing but your record id, that you are going to update.

Hope it helps :)

Title: How to update edited row in DataTables

Body:
I am trying to edit row in a Datatable.Data is loading from the database.after clicking on row popup will come. then editing the field after clicking on submit button it's not updating.
In console network error is 403.
Forbidden. How to update edited row ?

var workorder_path = "/dashboard/workorder_list/0/?format=json";

var editor = new $.fn.dataTable.Editor( {
    ajax: {

edit: {
                        type: 'PUT',
                        dataType:"json",
                        contentType: "application/json",
                        url: '/dashboard/workorder_list/0/?format=json',
                        data: function ( d ) {
                            return JSON.stringify( d );
                        }
                    },

  },
    table: "#workorder_table",
    idSrc: "id",
    fields: [
        { label: "ID:", name: "id" },
        { label: "Task:",   name: "task.name" },
        { label: "Description:",   name: "description" },

        { label: "Start Date:",   name: "start_date",
                "type": "datetime" },
        { label: "End Date:",   name: "end_date",
                "type": "datetime" }
    ]
} );

var workorder_table = $('#workorder_table').dataTable({
    dom: 'Blfrtip',
    JQueryUI: true,
    bPaginate: false,
    sScrollX: "100%",
    responsive: true,
    select: true,
    buttons: [
        {
            text: 'New',
            action: function () {
                create_workorder_window();
            },
            className: 'btn btn-warning btn-outline'
        },
        { extend: "edit",   editor: editor, className: 'btn btn-warning btn-outline' },
       // { extend: "create", editor: editor },
        { extend: 'colvis', text: 'Show', className: 'btn btn-warning btn-outline'}
    ],
    ajax: {
        url: workorder_path,
        dataSrc: ''
    },
    columns: [
        {"data": "id", "class": "workorder_id"},
        {"data": "thumb", "render": function(data, type, row) {
                                        return `<a href=` + data + ` data-fancybox> <img src=` + data + ` width="80" height="45"> </a>`;
                                    }},
        {"data": "task.name"},
        {"data": "description"},
        {"data": "status", "class":"v-a-m", "render": function (status, type, row) {
                                                return `

                                                                ${ status.name }

`;

        } },
        {"data": "start_date", "visible": false},
        {"data": "end_date", "visible": false},
        {"data": "assign_to", "width": "400px", "defaultContent": "None", "render": function (assign_to, type, row) {

                                                return `

                                                            ${ assign_to.official_name }

                                                            ${ assign_to.designation.designation }

`

        } },
        {"data": "creation_time", "visible": false},
        {"data": "modified_time", "visible": false}
    ]
});

Body:
You are calling same function for both (to load data in data table as well as to update a record), I mean the URL that you have mentioned in your question.

So, inside your edit ajax function, you need to call another server side method, where you can pass your data. For example,

[HttpPut]
public returnType EditRecord(int id, WorkorderModel model)
 {
   //Here you can update the record then return a success message or whatever
   return message;
 }

Note:  See, I don't know in which Language you are writing. As I'm writing in C#, so I added HttpPut attribute on top of the EditRecord method, to make it PUT. You need to change it accordingly.

Then, from your client side edit ajax, you can call it like this,

url: '/dashboard/EditRecord/'+d.id,

Just change the URL, that you have written in your ajax edit. See, here d.id is nothing but your record id, that you are going to update.

Hope it helps :)


问:
Unable to add reference in Visual Studio
I have a project in VS 2017 all was working well until I update Mysql connector and hence mysql.data reference.

As you can see in the picture, when I open the reference dialog box, only come up the new version of the referenceand when i try to select it and save, an error arises:

The error says: "Already exists a reference to 'MySql.Data' in the project"

The question is: How can I remove the older reference? It's not shown in the dialogbox and do not know where to find it.

Any help;

答:
Weird! I use VS 2010 and was able to add reference more than once without this error popping up.

The References can be found in project structure in "Solution Explorer" . Just remove the old reference and add new. If you are unable to find the Solution explorer you can go to "view" tab and activate it.


问:
I want to print PHP query with parameters
I have the following code

```<code>$name = 'myname';
$mail = 'my@mail.it';
$qwt = "INSERT INTO `agenz` (`name`, `email`) VALUES (?,?)";
$result = $connessione->prepare($qwt);
$result->bind_param('ss', $name, $mail);
$result->execute();
</code>```

I want print the query

```<code>"INSERT INTO `agenz` (`name`, `email`) VALUES ('myname','my@mail.it')"
</code>```

for creating a log.So how to do that?

thanx.

答:
I have solved!</p>

```<code>  $qwt = "INSERT INTO `age` (`name`,`email`) VALUES (?,?)";
  $par = array($name, $mail);

  $result = $connessione->prepare($qwt);
  $result->bind_param('ss', $par[0], $par[1]);
  $result->execute();

  echo "contenuto: " .SqlDebug($qwt, $par);

  function SqlDebug($raw_sql, $params=array())
  {
  $keys = array();
  $values = $params;
  foreach ($params as $key => $value)
  {
    // check if named parameters (':param') or anonymous parameters ('?') are    used
    if (is_string($key)) { $keys[] = '/:'.$key.'/'; }
    else                 { $keys[] = '/[?]/'; }
    // bring parameter into human-readable format
    if (is_string($value))    { $values[$key] = "'" . $value . "'"; }
    elseif (is_array($value)) { $values[$key] = implode(',', $value); }
    elseif (is_null($value))  { $values[$key] = 'NULL'; }
  }
  $raw_sql = preg_replace($keys, $values, $raw_sql, 1, $count);
  return $raw_sql;
  }
</code>```

Body:
I have the following code

$name = 'myname';
$mail = 'my@mail.it';
$qwt = "INSERT INTO `agenz` (`name`, `email`) VALUES (?,?)";
$result = $connessione->prepare($qwt);
$result->bind_param('ss', $name, $mail);
$result->execute();

I want print the query

"INSERT INTO `agenz` (`name`, `email`) VALUES ('myname','my@mail.it')"

for creating a log.So how to do that?

thanx.

Body:
I have solved!

  $qwt = "INSERT INTO `age` (`name`,`email`) VALUES (?,?)";
  $par = array($name, $mail);

  $result = $connessione->prepare($qwt);
  $result->bind_param('ss', $par[0], $par[1]);
  $result->execute();

  echo "contenuto: " .SqlDebug($qwt, $par);

  function SqlDebug($raw_sql, $params=array())
  {
  $keys = array();
  $values = $params;
  foreach ($params as $key => $value)
  {
    // check if named parameters (':param') or anonymous parameters ('?') are    used
    if (is_string($key)) { $keys[] = '/:'.$key.'/'; }
    else                 { $keys[] = '/[?]/'; }
    // bring parameter into human-readable format
    if (is_string($value))    { $values[$key] = "'" . $value . "'"; }
    elseif (is_array($value)) { $values[$key] = implode(',', $value); }
    elseif (is_null($value))  { $values[$key] = 'NULL'; }
  }
  $raw_sql = preg_replace($keys, $values, $raw_sql, 1, $count);
  return $raw_sql;
  }


问:
How to change local class variable IBAction
everyone!
If anyone can help me i'll be very glad^)

The problem is:
I have IBAction method (checkbox clicking) in my class and i want to change font attribute by clicking the checkbox (into bold state).
I trying to change local class variable in IBAction method for checking it in my - drawRect: method, by it's not working - variable doesn't changes.
How to change a local variable in IBAction method or maybe there's another way?
Thanks.

```<code>#import <Foundation/Foundation.h>
@interface BigLetterView : NSView {
NSColor *bgColor;
NSString *string;
NSString *testString;
BOOL isHighlighted;
BOOL isBold;
BOOL isItalic;
IBOutlet NSButton *boldButton;
NSMutableDictionary *attributes;

}
@property(retain, readwrite) NSColor *bgColor;
@property(copy, readwrite) NSString *string;
@property(readwrite) BOOL isBold;

- (void)drawStringCenteredIn:(NSRect)r;
- (void)prepareAttributes;
- (void)changeIsBold;
- (IBAction)savePDF:(id)sender;
- (IBAction)makeBold:(id)sender; //it's that method
- (IBAction)setItalic:(id)sender;
</code>```

Here below variable 'isBold' changes to 'YES'. (Method getting called - i test in in debugger).

```<code>- (IBAction)makeBold:(id)sender
{
if ([boldButton state] == NSOnState) {
isBold = YES;
NSLog(@"Action bold=%d", isBold);
}
else {
isBold = NO;
NSLog(@"Action bold=%d", isBold);
}

}
</code>```

But here isBold is still 'NO' again.

```<code>- (void)drawRect:(NSRect)rect {
NSRect bounds = [self bounds];
[bgColor set];
[NSBezierPath fillRect:bounds];
[self drawStringCenteredIn:bounds];
NSLog(@"isBold: %d",isBold); //HERE prints 'isBold:0'
if (isBold == YES) {
NSFont *aFont = [attributes objectForKey:NSFontAttributeName];
NSFontManager *fontManager = [NSFontManager sharedFontManager];
[attributes setObject:[fontManager convertFont:aFont toHaveTrait:NSBoldFontMask] forKey:NSFontAttributeName];
}

//whether this view is firstResponder
if ([[self window] firstResponder] == self &&
[NSGraphicsContext currentContextDrawingToScreen]) {
[NSGraphicsContext saveGraphicsState];
NSSetFocusRingStyle(NSFocusRingOnly);
[NSBezierPath fillRect:bounds];
[NSGraphicsContext restoreGraphicsState];

}
} // drawRect
</code>```

P.S.I doing chapter 20 from Aaron Hillegass book.

答:
What you’ve shown so far looks good, but obviously it’s not working or you wouldn’t be here. Try adding this line to the end of your -makeBold: method:

```<code>[self setNeedsDisplay];
</code>```

This will force the view to re-draw itself; it’s possible that your problem is just that the view isn’t being redrawn.

Body:
everyone!
If anyone can help me i'll be very glad^)

The problem is:
I have IBAction method (checkbox clicking) in my class and i want to change font attribute by clicking the checkbox (into bold state).
I trying to change local class variable in IBAction method for checking it in my - drawRect: method, by it's not working - variable doesn't changes.
How to change a local variable in IBAction method or maybe there's another way?
Thanks.

#import <Foundation/Foundation.h>
@interface BigLetterView : NSView {
NSColor *bgColor;
NSString *string;
NSString *testString;
BOOL isHighlighted;
BOOL isBold;
BOOL isItalic;
IBOutlet NSButton *boldButton;
NSMutableDictionary *attributes;

}
@property(retain, readwrite) NSColor *bgColor;
@property(copy, readwrite) NSString *string;
@property(readwrite) BOOL isBold;

- (void)drawStringCenteredIn:(NSRect)r;
- (void)prepareAttributes;
- (void)changeIsBold;
- (IBAction)savePDF:(id)sender;
- (IBAction)makeBold:(id)sender; //it's that method
- (IBAction)setItalic:(id)sender;

Here below variable 'isBold' changes to 'YES'. (Method getting called - i test in in debugger).

- (IBAction)makeBold:(id)sender
{
if ([boldButton state] == NSOnState) {
isBold = YES;
NSLog(@"Action bold=%d", isBold);
}
else {
isBold = NO;
NSLog(@"Action bold=%d", isBold);
}

}

But here isBold is still 'NO' again.

- (void)drawRect:(NSRect)rect {
NSRect bounds = [self bounds];
[bgColor set];
[NSBezierPath fillRect:bounds];
[self drawStringCenteredIn:bounds];
NSLog(@"isBold: %d",isBold); //HERE prints 'isBold:0'
if (isBold == YES) {
NSFont *aFont = [attributes objectForKey:NSFontAttributeName];
NSFontManager *fontManager = [NSFontManager sharedFontManager];
[attributes setObject:[fontManager convertFont:aFont toHaveTrait:NSBoldFontMask] forKey:NSFontAttributeName];
}

//whether this view is firstResponder
if ([[self window] firstResponder] == self &&
[NSGraphicsContext currentContextDrawingToScreen]) {
[NSGraphicsContext saveGraphicsState];
NSSetFocusRingStyle(NSFocusRingOnly);
[NSBezierPath fillRect:bounds];
[NSGraphicsContext restoreGraphicsState];

}
} // drawRect

P.S.I doing chapter 20 from Aaron Hillegass book.

Body:
What you’ve shown so far looks good, but obviously it’s not working or you wouldn’t be here. Try adding this line to the end of your -makeBold: method:

[self setNeedsDisplay];

This will force the view to re-draw itself; it’s possible that your problem is just that the view isn’t being redrawn.


问:
Determining the proper amount of Neurons for a Neural Network
I have been doing some research with neural networks and the concept and theory as a whole makes sense to me. Although the one question that sticks out to me, which I haven't been able to find an answer to yet, is how many neurons should be used in a Neural Net. to achieve proper/efficient results. Including Hidden Layers, neurons per Hidden Layer, etc. Do more neurones necessarily more accurate results (while being more taxing on the system) or will less neurons still be sufficient? Is there some sort of governing rule to help determine those numbers? Does it depend on the type of training/learning algorithm that is being implemented into the neural net. Does it depend on the type of data/input that is being presented to the network?

If it makes it easier to answer the questions, I will most likely be using feedforwarding and backpropogation as the main method for training and prediction.

On a side note, is there a prediction algorithm/firing rule or learning algorithm that is generally regraded to as "the best/most practical", or is that also dependant on the type of data being presented to the network?

Thanks to anyone with any input, it's always appreciated!

EDIT: Regarding the C# tag, that is the language in which I'll be putting together my neural network. If that information helps at all.

答:
Some general rules are the following based on this paper: 'Approximating Number of Hidden layer neurons in Multiple Hidden Layer BPNN Architecture' by Saurabh Karsoliya. Source here

The number of hidden layer neurons are 2/3 (or 70%
to 90%) of the size of the input layer. If this is
insufficient then number of output layer neurons can
be added later on.

The number of hidden layer neurons should be less
than twice of the number of neurons in input layer.

The size of the hidden layer neurons is between the
input layer size and the output layer size.


问:
Get variable using string
Lets say i have 2 arrays called fruitbasket01 and fruitbasket02.

I want to get the fruitbasket based on my id, which could be 01 or 02.

```<code>var fruitbasket01 = ['apple','orange'];
var fruitbasket02 = ['mango','grapes','peach','potato']
var id1 = '01';
var id2 = '02';

if (condition 1) {
     var string = 'fruitbasket'.concat(id1);
} else {
     var string = 'fruitbasket'.concat(id2);
}

for (var i=0; i<string.length; i++) {
     /** more code here **/
}
</code>```

may I know what is wrong with this method and how can I go about it instead.

答:
Why not something like this

```<code>var fruitbasket = {
    '01': ['apple','orange'],
    '02': ['mango','grapes','peach','potato']
};

var id1 = '01';
var id2 = '02';

if (condition 1) {
     var string = fruitbasket[id1];
} else {
     var string = fruitbasket[id2];
}

for (var i=0; i<string.length; i++) {
     /** more code here **/
}
</code>```

Here string will be an array with the desired basket items

Title: Get variable using string

Body:
Lets say i have 2 arrays called fruitbasket01 and fruitbasket02.

I want to get the fruitbasket based on my id, which could be 01 or 02.

var fruitbasket01 = ['apple','orange'];
var fruitbasket02 = ['mango','grapes','peach','potato']
var id1 = '01';
var id2 = '02';

if (condition 1) {
     var string = 'fruitbasket'.concat(id1);
} else {
     var string = 'fruitbasket'.concat(id2);
}

for (var i=0; i<string.length; i++) {
     /** more code here **/
}

may I know what is wrong with this method and how can I go about it instead.

Body:
Why not something like this

var fruitbasket = {
    '01': ['apple','orange'],
    '02': ['mango','grapes','peach','potato']
};

var id1 = '01';
var id2 = '02';

if (condition 1) {
     var string = fruitbasket[id1];
} else {
     var string = fruitbasket[id2];
}

for (var i=0; i<string.length; i++) {
     /** more code here **/
}

Here string will be an array with the desired basket items