问:
onBackPressed to Home Fragment from another Fragment in Navigation Drawer
In my app I have created a Navigation Drawer with six Fragments. The MainOption Fragment is not included in the Navigation item menu list. Now I want to activate Back button on mobile device to redirect to Main Fragment. For example if I have fragments A,B,C,D,E,F, and now if I click B, then if I press back button, it will back to A. In the same way if I Press back button on Fragment E it will redirect to Fragment A. Now how can I achive this logic in my code. Hence I have tried lots of code from the website, but nothis was working at all. Here is my code snepet for Navigation Drawer</p>

```<code>private NavigationView navigationView;
private DrawerLayout drawerLayout;
private Toolbar toolbar ;
private View navigationHeader;
private ImageView imgProfile;
private TextView txtName, txtWebsite;

// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mHandler = new Handler();

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    navigationView = (NavigationView) findViewById(R.id.nav_view);

    // Navigation view header
    navigationHeader= navigationView.getHeaderView(0);
    txtName = navigationHeader.findViewById(R.id.username);
    txtWebsite = navigationHeader.findViewById(R.id.email);
    imgProfile = navigationHeader.findViewById(R.id.profile_image);

    // load nav menu header data
    loadNavHeader();

    //Set the Home Fragment initially
    OptionMenuFragment fragment = new OptionMenuFragment();
    android.support.v4.app.FragmentTransaction fragmentTransaction =
            getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment, "OptionMenuFragment");
    fragmentTransaction.commit();

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawerLayout.setDrawerListener(toggle);
    toggle.syncState();

    navigationView.setNavigationItemSelectedListener(this);
 }

 private void loadNavHeader() {
    // name, website
    txtName.setText("Hallo");
    txtWebsite.setText("mail.com");
    imgProfile.setImageResource(R.drawable.profile_image);

    //ToDo: Image should be uploaded from web
}

 String lastFragmentTag;
 boolean showingFirstFragment = true;

 public void addNewFragment(Fragment fragment, String fragmentTag) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();

    if (lastFragmentTag != null) {
        Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
        transaction.remove(currentFragment);
    } else {
        Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragment_container);
        transaction.hide(currentFragment);
    }

    transaction.add(R.id.fragment_container, fragment, fragmentTag);
    transaction.commit();

    lastFragmentTag = fragmentTag;
    showingFirstFragment = false;

 }
 @Override
 public void onBackPressed() {
    //Here we're gonna remove the last fragment added, and show OptionMenuFragment again
    if (!showingFirstFragment)
    {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        Fragment firstFragment = fragmentManager.findFragmentByTag("OptionMenuFragment");
        Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);

        transaction.remove(currentFragment);
        transaction.show(firstFragment);

        transaction.commit();

        showingFirstFragment = true;
    } else {
        super.onBackPressed();
    }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.blu_home) {
        Intent intent = new Intent(this, MainOptionPage.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);
  }

 @SuppressWarnings("StatementWithEmptyBody")
 @Override
 public boolean onNavigationItemSelected(MenuItem item) {

    String fragmentTag=null;
    // Handle navigation view item clicks here.
    Fragment fragment = null;
    FragmentManager fragmentManager = getSupportFragmentManager();
    switch (item.getItemId()) {
        case R.id.view_profile:
            fragment = new ViewProfileFragment();
            fragmentTag = "ViewProfileFragment";
            break;
        case R.id.todo_list:
            fragment =new ToDoListFragment();
            fragmentTag="ToDoListFragment";
            break;
        case R.id.logout:
            showAlertDialogLogOut();
            break;
        case R.id.settings:
            fragment = new SettingsFragment();
            fragmentTag="SettingFragment";
            break;
        case R.id.about:
            fragment = new AboutFragment();
            fragmentTag="AboutFragment";
            break;
        case R.id.info:
            fragment=new InfoFragment();
            fragmentTag="InfoFragment";
            break;
    }
    if(fragment!=null){
        fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit();
    }
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerLayout.closeDrawer(GravityCompat.START);
    return true;
 }

 private void showAlertDialogLogOut() {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Logout");
    builder.setMessage("Are you sure you want to log out?");

    builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            // close the dialog, go to login page
            dialog.dismiss();
            startActivity(new Intent(MainOptionPage.this, LoginPage.class));
        }
    });

    builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // Do nothing
            dialog.dismiss();
        }
    });

    AlertDialog alert = builder.create();
    alert.show();
  }
}
</code>```

答:
For that approach, you will want to use the add(containerViewId, fragment, tag) method instead of replace(containerViewId, fragment), since replace will call remove(Fragment) for ALL fragments previously added to the container, before adding the new fragment. Also, you will want to use addToBackStack(name).

Here's a method I created for a project, and slightly modified for you:

```<code>String lastFragmentTag;
boolean showingFirstFragment = true;

public void addNewFragment(Fragment fragment, String fragmentTag) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();

    if (lastFragmentTag != null) {
        Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
        transaction.remove(currentFragment);
    } else {
        Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragment_container);
        transaction.hide(currentFragment);
    }

    transaction.add(R.id.fragment_container, fragment, fragmentTag);
    transaction.commit();

    lastFragmentTag = fragmentTag;
    showingFirstFragment = false;
}
</code>```

Then you just have to make this change inside onNavigationItemSelected:

```<code>Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();

String fragmentTag;

switch (item.getItemId()) {
    case R.id.view_profile:
        fragment = new ViewProfileFragment();
        fragmentTag = "ViewProfileFragment";

        break;
    ...
}

if(fragment!=null){
        addNewFragment(fragment, fragmentTag);
}
</code>```

Where "fragmentTag", is going to be a String variable which you change according to the fragment instantiated.

EDIT: Some more changes since the code wasn't working as intended:

```<code>@Override
public void onBackPressed() {
    //Here we're gonna remove the last fragment added, and show OptionMenuFragment again
    if (!showingFirstFragment)
    {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        Fragment firstFragment = fragmentManager.findFragmentByTag("OptionMenuFragment");
        Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);

        transaction.remove(currentFragment);
        transaction.show(firstFragment);

        transaction.commit();

        showingFirstFragment = true;
    } else {
        super.onBackPressed();
    }
}
</code>```

And when adding OptionMenuFragment, do this instead:

```<code>fragmentTransaction.replace(R.id.fragment_container, fragment, "OptionMenuFragment");
</code>```

Body:
In my app I have created a Navigation Drawer with six Fragments. The MainOption Fragment is not included in the Navigation item menu list. Now I want to activate Back button on mobile device to redirect to Main Fragment. For example if I have fragments A,B,C,D,E,F, and now if I click B, then if I press back button, it will back to A. In the same way if I Press back button on Fragment E it will redirect to Fragment A. Now how can I achive this logic in my code. Hence I have tried lots of code from the website, but nothis was working at all. Here is my code snepet for Navigation Drawer

private NavigationView navigationView;
private DrawerLayout drawerLayout;
private Toolbar toolbar ;
private View navigationHeader;
private ImageView imgProfile;
private TextView txtName, txtWebsite;

// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mHandler = new Handler();

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    navigationView = (NavigationView) findViewById(R.id.nav_view);

    // Navigation view header
    navigationHeader= navigationView.getHeaderView(0);
    txtName = navigationHeader.findViewById(R.id.username);
    txtWebsite = navigationHeader.findViewById(R.id.email);
    imgProfile = navigationHeader.findViewById(R.id.profile_image);

    // load nav menu header data
    loadNavHeader();

    //Set the Home Fragment initially
    OptionMenuFragment fragment = new OptionMenuFragment();
    android.support.v4.app.FragmentTransaction fragmentTransaction =
            getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment, "OptionMenuFragment");
    fragmentTransaction.commit();

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawerLayout.setDrawerListener(toggle);
    toggle.syncState();

    navigationView.setNavigationItemSelectedListener(this);
 }

 private void loadNavHeader() {
    // name, website
    txtName.setText("Hallo");
    txtWebsite.setText("mail.com");
    imgProfile.setImageResource(R.drawable.profile_image);

    //ToDo: Image should be uploaded from web
}

 String lastFragmentTag;
 boolean showingFirstFragment = true;

 public void addNewFragment(Fragment fragment, String fragmentTag) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();

    if (lastFragmentTag != null) {
        Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
        transaction.remove(currentFragment);
    } else {
        Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragment_container);
        transaction.hide(currentFragment);
    }

    transaction.add(R.id.fragment_container, fragment, fragmentTag);
    transaction.commit();

    lastFragmentTag = fragmentTag;
    showingFirstFragment = false;

 }
 @Override
 public void onBackPressed() {
    //Here we're gonna remove the last fragment added, and show OptionMenuFragment again
    if (!showingFirstFragment)
    {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        Fragment firstFragment = fragmentManager.findFragmentByTag("OptionMenuFragment");
        Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);

        transaction.remove(currentFragment);
        transaction.show(firstFragment);

        transaction.commit();

        showingFirstFragment = true;
    } else {
        super.onBackPressed();
    }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.blu_home) {
        Intent intent = new Intent(this, MainOptionPage.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);
  }

 @SuppressWarnings("StatementWithEmptyBody")
 @Override
 public boolean onNavigationItemSelected(MenuItem item) {

    String fragmentTag=null;
    // Handle navigation view item clicks here.
    Fragment fragment = null;
    FragmentManager fragmentManager = getSupportFragmentManager();
    switch (item.getItemId()) {
        case R.id.view_profile:
            fragment = new ViewProfileFragment();
            fragmentTag = "ViewProfileFragment";
            break;
        case R.id.todo_list:
            fragment =new ToDoListFragment();
            fragmentTag="ToDoListFragment";
            break;
        case R.id.logout:
            showAlertDialogLogOut();
            break;
        case R.id.settings:
            fragment = new SettingsFragment();
            fragmentTag="SettingFragment";
            break;
        case R.id.about:
            fragment = new AboutFragment();
            fragmentTag="AboutFragment";
            break;
        case R.id.info:
            fragment=new InfoFragment();
            fragmentTag="InfoFragment";
            break;
    }
    if(fragment!=null){
        fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit();
    }
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerLayout.closeDrawer(GravityCompat.START);
    return true;
 }

 private void showAlertDialogLogOut() {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Logout");
    builder.setMessage("Are you sure you want to log out?");

    builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            // close the dialog, go to login page
            dialog.dismiss();
            startActivity(new Intent(MainOptionPage.this, LoginPage.class));
        }
    });

    builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // Do nothing
            dialog.dismiss();
        }
    });

    AlertDialog alert = builder.create();
    alert.show();
  }
}

Body:
For that approach, you will want to use the add(containerViewId, fragment, tag) method instead of replace(containerViewId, fragment), since replace will call remove(Fragment) for ALL fragments previously added to the container, before adding the new fragment. Also, you will want to use addToBackStack(name).

Here's a method I created for a project, and slightly modified for you:

String lastFragmentTag;
boolean showingFirstFragment = true;

public void addNewFragment(Fragment fragment, String fragmentTag) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();

    if (lastFragmentTag != null) {
        Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
        transaction.remove(currentFragment);
    } else {
        Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragment_container);
        transaction.hide(currentFragment);
    }

    transaction.add(R.id.fragment_container, fragment, fragmentTag);
    transaction.commit();

    lastFragmentTag = fragmentTag;
    showingFirstFragment = false;
}

Then you just have to make this change inside onNavigationItemSelected:

Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();

String fragmentTag;

switch (item.getItemId()) {
    case R.id.view_profile:
        fragment = new ViewProfileFragment();
        fragmentTag = "ViewProfileFragment";

        break;
    ...
}

if(fragment!=null){
        addNewFragment(fragment, fragmentTag);
}

Where "fragmentTag", is going to be a String variable which you change according to the fragment instantiated.

EDIT: Some more changes since the code wasn't working as intended:

@Override
public void onBackPressed() {
    //Here we're gonna remove the last fragment added, and show OptionMenuFragment again
    if (!showingFirstFragment)
    {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        Fragment firstFragment = fragmentManager.findFragmentByTag("OptionMenuFragment");
        Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);

        transaction.remove(currentFragment);
        transaction.show(firstFragment);

        transaction.commit();

        showingFirstFragment = true;
    } else {
        super.onBackPressed();
    }
}

And when adding OptionMenuFragment, do this instead:

fragmentTransaction.replace(R.id.fragment_container, fragment, "OptionMenuFragment");


来源: stackexchange

问:
How to use templates with angular 1.x and webpack
Im trying to use webpack with my angular app but whenever I try loading in the html to the template I get errors. This is the one I'm currently getting:

Module parse failed: C:\Users\Fabian\Dropbox\FixMyCity\FixMyCity\src\FixMyCity.Web\App\settings\settings.html Unexpected token (1:0)

  You may need an appropriate loader to handle this file type.

Which makes me think that I don't have the right loader for html, but i've tried it with both raw-loader and html-load and neither of them have worked for me.

Here is my current webpack.config.js

```<code>module.exports = {
    entry: './App/app.js',
    output: {
        filename: './wwwroot/app-bundle.js'
    },
    loaders: [

            { test: /\.html$/, loader: 'html' },
            { test: /\.css$/, loader: 'style!css' },
    ]
};
</code>```

app.js

```<code>var app = angular.module('app', ['auth0', 'angular-storage', 'angular-jwt', 'ngRoute'])
.config(['$routeProvider', 'authProvider', 'jwtInterceptorProvider', '$httpProvider', configFunction])

function configFunction($routeProvider, authProvider, jwtInterceptorProvider, $httpProvider) {
    // Configure routes for your application
    $routeProvider
      .when('/', {
          controller: 'HomeCtrl',
          template: require('./home/home.html'),
          requiresLogin: true
      })
}
</code>```

答:
You must install html-loader from npm, after that you have to put in property loader the value 'html-loader'.

Like this:

```<code>module.exports = {
entry: './App/app.js',
output: {
    filename: './wwwroot/app-bundle.js'
},
loaders: [

        { test: /\.html$/, loader: 'html-loader' },
        { test: /\.css$/, loader: 'style!css' },
]};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im trying to use webpack with my angular app but whenever I try loading in the html to the template I get errors. This is the one I'm currently getting:

Module parse failed: C:\Users\Fabian\Dropbox\FixMyCity\FixMyCity\src\FixMyCity.Web\App\settings\settings.html Unexpected token (1:0)

  You may need an appropriate loader to handle this file type.

Which makes me think that I don't have the right loader for html, but i've tried it with both raw-loader and html-load and neither of them have worked for me.

Here is my current webpack.config.js

module.exports = {
    entry: './App/app.js',
    output: {
        filename: './wwwroot/app-bundle.js'
    },
    loaders: [

            { test: /\.html$/, loader: 'html' },
            { test: /\.css$/, loader: 'style!css' },
    ]
};

app.js

var app = angular.module('app', ['auth0', 'angular-storage', 'angular-jwt', 'ngRoute'])
.config(['$routeProvider', 'authProvider', 'jwtInterceptorProvider', '$httpProvider', configFunction])

function configFunction($routeProvider, authProvider, jwtInterceptorProvider, $httpProvider) {
    // Configure routes for your application
    $routeProvider
      .when('/', {
          controller: 'HomeCtrl',
          template: require('./home/home.html'),
          requiresLogin: true
      })
}

Body:
You must install html-loader from npm, after that you have to put in property loader the value 'html-loader'.

Like this:

module.exports = {
entry: './App/app.js',
output: {
    filename: './wwwroot/app-bundle.js'
},
loaders: [

        { test: /\.html$/, loader: 'html-loader' },
        { test: /\.css$/, loader: 'style!css' },
]};

ContentLicense: CC BY-SA 4.0


问:
Mod Rewrite - Force HTTPS and Rewrite Variable?
I am running on Heroku and have added Rewrite rules to clean up the URL and also force https. I am having a small issue when the url is rewritten from http to https and don't understand rewrite rules enough yet to figure out what I am doing wrong.

Current .htaccess on Heroku

```<code>    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ ?id=$1 [QSA]
    ##Force SSL
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
</code>```

When I visit https://example.com/12345 everything works great.
When I visit http://example.com/12345 the url is rewritten to https://example.com/12345?id=12345

I'd like http to rewrite to https://example.com/12345

What am I missing? Thanks in advance!

答:
Looks like you do not need the 2nd and 3rd rows. So your conf will be:

```<code>RewriteEngine On
##Force SSL
RewriteCond %{HTTP:X-Forwarded-Proto} !https
</code>```

And I do not see any RewriteRule after the last RewriteCond.
Did you forget to add something like the following to your question or to your conf?

```<code>RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=301]
</code>```

Body:
I am running on Heroku and have added Rewrite rules to clean up the URL and also force https. I am having a small issue when the url is rewritten from http to https and don't understand rewrite rules enough yet to figure out what I am doing wrong.

Current .htaccess on Heroku

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ ?id=$1 [QSA]
    ##Force SSL
    RewriteCond %{HTTP:X-Forwarded-Proto} !https

When I visit https://example.com/12345 everything works great.
When I visit http://example.com/12345 the url is rewritten to https://example.com/12345?id=12345

I'd like http to rewrite to https://example.com/12345

What am I missing? Thanks in advance!

Body:
Looks like you do not need the 2nd and 3rd rows. So your conf will be:

RewriteEngine On
##Force SSL
RewriteCond %{HTTP:X-Forwarded-Proto} !https

And I do not see any RewriteRule after the last RewriteCond.
Did you forget to add something like the following to your question or to your conf?

RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=301]


问:
TypeError when calling document.getElementById
the following code should display the word Test...but instead the message TypeError: document.getElementById(...) is displayed.
I can't figure out why:

```<code><html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>
  </head>
  <script>
    document.getElementById("kaptree").innerHTML="TEST";
  </script>
  <body>
     <div id="kaptree"></div>
  </body>
</html>
</code>```

Can anyone help me to open my eyes?

答:
You're trying to access the kaptree element before it's loaded. Run your script after loading the DOM.

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Testtree</title>

```

Body:
the following code should display the word Test...but instead the message TypeError: document.getElementById(...) is displayed.
I can't figure out why:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>

Can anyone help me to open my eyes?

Body:
You're trying to access the kaptree element before it's loaded. Run your script after loading the DOM.

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Testtree</title>
</head>
<body>
  <div id="kaptree"></div>
  <script>
    document.getElementById("kaptree").innerHTML = "TEST";
  </script>
</body>
</html>


答:
Your script is defined before the element that you try to reference.

Move it after :

```<code><html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>
  </head>
  <body>
     <div id="kaptree"></div>
  </body>
   <script>
    document.getElementById("kaptree").innerHTML="TEST";
  </script>
</html>
</code>```

Or more readable and maintainable solution, use a function :

```<code><html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>
     <script>
           function changeValue(){
               document.getElementById('kaptree').innerHTML='TEST';
            }
     </script>
  </head>
  <body>
     <div id="kaptree"></div>
    <script>changeValue()</script>
  </body>

</html>
</code>```

Title: TypeError when calling document.getElementById

Body:
Your script is defined before the element that you try to reference.

Move it after :

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>
  </head>
  <body>
     <div id="kaptree"></div>
  </body>
   <script>
    document.getElementById("kaptree").innerHTML="TEST";
  </script>
</html>

Or more readable and maintainable solution, use a function :

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>
     <script>
           function changeValue(){
               document.getElementById('kaptree').innerHTML='TEST';
            }
     </script>
  </head>
  <body>
     <div id="kaptree"></div>
    <script>changeValue()</script>
  </body>

</html>


问:
Derby how to change port number (also for stop script)
I noticed that if I set another port number instead of the default one in derby (1527) in the derby.properties with for instance:

```<code>derby.drda.portNumber=1528
</code>```

It will then correctly start up the server on that new port but unfortunately when calling stop script it will still attempt to kill something on the default port and leaving the derby alive. Is that a bug or is there something else that needs to be addressed in the properties file to make it work?

答: You are probably looking for the -p portnumber argument to stopNetworkServer: http://db.apache.org/derby/docs/10.13/adminguide/tadminconfigshuttingdownthenetworkserver.html

Body:
I noticed that if I set another port number instead of the default one in derby (1527) in the derby.properties with for instance:

derby.drda.portNumber=1528

It will then correctly start up the server on that new port but unfortunately when calling stop script it will still attempt to kill something on the default port and leaving the derby alive. Is that a bug or is there something else that needs to be addressed in the properties file to make it work?


问:
Get source rows of LINQ query result?
In the following LINQ example, how can you get a list of index numbers from the original rows that the group is made up of? I would like to show the user where the data comes from.

```<code>    Dim inputDt As New DataTable
    inputDt.Columns.Add("Contractor")
    inputDt.Columns.Add("Job_Type")
    inputDt.Columns.Add("Cost")

    inputDt.Rows.Add({"John Smith", "Roofing", "2408.68"})
    inputDt.Rows.Add({"John Smith", "Electrical", "1123.08"})
    inputDt.Rows.Add({"John Smith", "Framing", "900.99"})
    inputDt.Rows.Add({"John Smith", "Electrical", "892.00"})

    Dim results = From rows In inputDt Where rows!Contractor <> ""
                  Group rows By rows!Job_Type
                    Into cost_total = Sum(CDec(rows!Cost))

    For Each r In results
        ' Show results.
        'r.Job_Type
        'r.cost_total

        ' Show line numbers of original rows... ?
    Next
</code>```

For the result (Job_Type="Electrical", cost_total=2015.08), the original index numbers are 1 and 3.

Thanks

答:
First and perhaps foremost, set Option Strict On.  This will not allow the old VB6 style rows!Cost type notation.  But this is for the better because that way always returns Object and the data rarely is.  This is no loss at all as NET has better ways to type and convert variables.

Second, and somewhat related, is that all your DataTable columns are text even though one is clearly decimal.  Next, your query relates to working with the data in the table but you want to also include a DataRow property which is a bit odd.  Better would be to add an Id or Number to the data to act as the identifier.  This will also help the results make sense if the View (order of rows) changes.

You did not clarify whether you wanted a CSV of indices (now IDs) or a collection of them.  A CSV of them seems simpler, so thats what this does.

The code also uses more idiomatic names and demonstrates casting data to the needed type using other extension methods.  It also uses the extension method approach.  First the DataTable with non-string Data Types specified:

```<code>Dim inputDt As New DataTable
inputDt.Columns.Add("ID", GetType(Int32))
inputDt.Columns.Add("Contractor")
inputDt.Columns.Add("JobType")
inputDt.Columns.Add("Cost", GetType(Decimal))

inputDt.Rows.Add({1, "John Smith", "Roofing", "2408.68"})
inputDt.Rows.Add({5, "John Smith", "Electrical", "1123.08"})
inputDt.Rows.Add({9, "John Smith", "Framing", "900.99"})
inputDt.Rows.Add({17, "John Smith", "Electrical", "892.00"})
</code>```

then the query:

```<code>Dim summary = inputDt.AsEnumerable().GroupBy(Function(g) g.Field(Of String)("JobType"),
                                             Function(k, v) New With {.Job = k,
                                                                    .Cost = v.Sum(Function(q) q.Field(Of Decimal)("Cost")),
                                                                    .Indices = String.Join(",", inputDt.AsEnumerable().
                                                                                Where(Function(q) q.Field(Of String)("JobType") = k).
                                                                                Select(Function(j) j.Field(Of Int32)("Id")))
                                                                    }).
                                 OrderBy(Function(j) j.Cost).
                                 ToArray()

' Debug, test:
For Each item In summary
    Console.WriteLine("Job: {0}, Cost: {1}, Ids: {2}", item.Job, item.Cost, item.Indices)
Next
</code>```

The excessive scroll is unfortunate but I left it to allow the clauses to align with what "level" they are acting at.  As you can see, a separate query is run on the DataTable to get the matching Indicies.

It is a little more typical to write such a thing as

```<code>Dim foo = Something.GroupBy(...).Select(...)
</code>```

But you can skip the SELECT by using this overload of GroupBy as the above does:

```<code>Dim foo = Something.GroupBy(Function (g) ..., Function (k, v) ... )
</code>```

Results:

Job: Framing, Cost: 900.99, Ids: 9

  Job: Electrical, Cost: 2015.08, Ids: 5,17

  Job: Roofing, Cost: 2408.68, Ids: 1

Title: Get source rows of LINQ query result?

Body:
In the following LINQ example, how can you get a list of index numbers from the original rows that the group is made up of? I would like to show the user where the data comes from.

    Dim inputDt As New DataTable
    inputDt.Columns.Add("Contractor")
    inputDt.Columns.Add("Job_Type")
    inputDt.Columns.Add("Cost")

    inputDt.Rows.Add({"John Smith", "Roofing", "2408.68"})
    inputDt.Rows.Add({"John Smith", "Electrical", "1123.08"})
    inputDt.Rows.Add({"John Smith", "Framing", "900.99"})
    inputDt.Rows.Add({"John Smith", "Electrical", "892.00"})

    Dim results = From rows In inputDt Where rows!Contractor <> ""
                  Group rows By rows!Job_Type
                    Into cost_total = Sum(CDec(rows!Cost))

    For Each r In results
        ' Show results.
        'r.Job_Type
        'r.cost_total

        ' Show line numbers of original rows... ?
    Next

For the result (Job_Type="Electrical", cost_total=2015.08), the original index numbers are 1 and 3.

Thanks

Body:
First and perhaps foremost, set Option Strict On.  This will not allow the old VB6 style rows!Cost type notation.  But this is for the better because that way always returns Object and the data rarely is.  This is no loss at all as NET has better ways to type and convert variables.

Second, and somewhat related, is that all your DataTable columns are text even though one is clearly decimal.  Next, your query relates to working with the data in the table but you want to also include a DataRow property which is a bit odd.  Better would be to add an Id or Number to the data to act as the identifier.  This will also help the results make sense if the View (order of rows) changes.

You did not clarify whether you wanted a CSV of indices (now IDs) or a collection of them.  A CSV of them seems simpler, so thats what this does.

The code also uses more idiomatic names and demonstrates casting data to the needed type using other extension methods.  It also uses the extension method approach.  First the DataTable with non-string Data Types specified:

Dim inputDt As New DataTable
inputDt.Columns.Add("ID", GetType(Int32))
inputDt.Columns.Add("Contractor")
inputDt.Columns.Add("JobType")
inputDt.Columns.Add("Cost", GetType(Decimal))

inputDt.Rows.Add({1, "John Smith", "Roofing", "2408.68"})
inputDt.Rows.Add({5, "John Smith", "Electrical", "1123.08"})
inputDt.Rows.Add({9, "John Smith", "Framing", "900.99"})
inputDt.Rows.Add({17, "John Smith", "Electrical", "892.00"})

then the query:

Dim summary = inputDt.AsEnumerable().GroupBy(Function(g) g.Field(Of String)("JobType"),
                                             Function(k, v) New With {.Job = k,
                                                                    .Cost = v.Sum(Function(q) q.Field(Of Decimal)("Cost")),
                                                                    .Indices = String.Join(",", inputDt.AsEnumerable().
                                                                                Where(Function(q) q.Field(Of String)("JobType") = k).
                                                                                Select(Function(j) j.Field(Of Int32)("Id")))
                                                                    }).
                                 OrderBy(Function(j) j.Cost).
                                 ToArray()

' Debug, test:
For Each item In summary
    Console.WriteLine("Job: {0}, Cost: {1}, Ids: {2}", item.Job, item.Cost, item.Indices)
Next

The excessive scroll is unfortunate but I left it to allow the clauses to align with what "level" they are acting at.  As you can see, a separate query is run on the DataTable to get the matching Indicies.

It is a little more typical to write such a thing as

Dim foo = Something.GroupBy(...).Select(...)

But you can skip the SELECT by using this overload of GroupBy as the above does:

Dim foo = Something.GroupBy(Function (g) ..., Function (k, v) ... )

Results:

Job: Framing, Cost: 900.99, Ids: 9

  Job: Electrical, Cost: 2015.08, Ids: 5,17

  Job: Roofing, Cost: 2408.68, Ids: 1


问:
How to install opencv library in python 3.5?
I've created a project in Pycharm IDE. I've used python 3.5, tensorflow library. Now I want to install opencv in this.

I have tried so many videos available on youtube and some tutorials in the internet. But when import open cv in python shell it gives me following error. How can I fix it?

import code

```<code>import cv2
</code>```

Error message

Traceback (most recent call last):
    File "", line 1, in
      import cv2
  ImportError: Module use of python27.dll conflicts with this version of Python.

I have noticed that python 2.7 is used to install opencv. Is it a must o use 2.7 version?

Also as I know tensorflow will not support if I use another version of python(other than 3.5)

答:
Since PyCharm is tagged I'm assuming you are wanting to know how to get opencv installed in PyCharm specifically. There is a PyCharm guide for installing packages here.

Step by step would be...

File | Settings | Project:MyProject | Project Interpreter

Click the + symbol on the right

Type opencv-python

Select opencv-python

Click Install Package at the bottom left

Opencv should now be added to PyCharm. You can verify that it is by...

Tools | Python Console...

Clicking in the console window which pops up on the bottom

import cv2

Body:
I've created a project in Pycharm IDE. I've used python 3.5, tensorflow library. Now I want to install opencv in this.

I have tried so many videos available on youtube and some tutorials in the internet. But when import open cv in python shell it gives me following error. How can I fix it?

import code

import cv2

Error message

Traceback (most recent call last):
    File "", line 1, in
      import cv2
  ImportError: Module use of python27.dll conflicts with this version of Python.

I have noticed that python 2.7 is used to install opencv. Is it a must o use 2.7 version?

Also as I know tensorflow will not support if I use another version of python(other than 3.5)


答: You should place your scripts after your html elements.</p>


问:
Select angular don´t show results
I have an angular application whre I want to get results into select, so I have it as:

HTML

```<code><div class="col-xs-12 col-sm-6 col-md-4">
  <div class="form-group">
    <label>Register: </label>
    <select class="form-control" ng-options="item.Nombre for item in GetCatalogoPadre"></select>
    <br />
  </div>
</div>
</code>```

AngularCtrl

```<code>     function cargarCatalogo() {
         apiService.get("../../api/Catalogo/GetCatalogoPadre/", null,
            function (res) {
                $scope.Catalogos = res.data;
            }, errorCatalogo);
</code>```

Controller

```<code>namespace PortalDeTransporte.Web.Controllers
{
    //[Authorize]
    [RoutePrefix("api/Catalogo")]
    public class CatalogoRegistroController : ApiControllerBase
    {

    [System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpGet]
    [Route("GetCatalogoPadre")]

    public HttpResponseMessage GetCatalogoPadre(HttpRequestMessage request)
    {
     //some code there for get results
    }

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

Something extrange happens there, if I try to get results using postman with GET action like:

```<code>http://localhost:55720/api/Catalogo/GetCatalogoPadre
</code>```

I get correct results as:

```<code>{
        "ID": "1",
        "Codigo": "BMX",
        "Nombre": "BANAMEX",
        "Padre": 0,
        "Catalogo": "BAN"
    },
    {
        "ID": "2",
        "Codigo": "KNW",
        "Nombre": "KENWORTH",
        "Padre": 0,
        "Catalogo": "MAR"
    },
</code>```

But them dont appear into select list, can someone view something wrong in code?. Regards

答:
It should be,

```<code><select class="form-control" ng-options="item.Nombre for item in Catalogos "></select>
</code>```

also ensure that you are calling the function on ng-init

```<code> <div class="form-group" ng-init="cargarCatalogo()">
    <label>Register: </label>
    <select class="form-control" ng-options="item.Nombre for item in Catalogos"></select>
    <br />
  </div>
</code>```

DEMO

var myApp=angular.module('myApp',[]);
 myApp.controller('thecontroller',function($scope){
       $scope.cargarCatalogo = function (){
            $scope.catalogos = [{
        "ID": "1",
        "Codigo": "BMX",
        "Nombre": "BANAMEX",
        "Padre": 0,
        "Catalogo": "BAN"
    },
    {
        "ID": "2",
        "Codigo": "KNW",
        "Nombre": "KENWORTH",
        "Padre": 0,
        "Catalogo": "MAR"
    }];
    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
    <html>
        <head>
          <title>ng-Messages Service</title>
          <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
            <script src='https://code.angularjs.org/1.5.0-rc.0/angular.min.js'></script>
        </head>
        <body ng-app="myApp">
            <div ng-controller='thecontroller' ng-init="cargarCatalogo()">
           <div class="col-xs-12 col-sm-6 col-md-4">
  <div class="form-group">
    <label>Register: </label>
    <select class="form-control" ng-model="SelectedOption"       ng-options="choice.Codigo for choice in catalogos track by choice.ID">></select>
    <br />
  </div>
</div>
            </div>
        </body>
    </html></code>```

Title: Select angular don´t show results

Body:
I have an angular application whre I want to get results into select, so I have it as:

HTML

    Register:
    <select class="form-control" ng-options="item.Nombre for item in GetCatalogoPadre"></select>

AngularCtrl

     function cargarCatalogo() {
         apiService.get("../../api/Catalogo/GetCatalogoPadre/", null,
            function (res) {
                $scope.Catalogos = res.data;
            }, errorCatalogo);

Controller

namespace PortalDeTransporte.Web.Controllers
{
    //[Authorize]
    [RoutePrefix("api/Catalogo")]
    public class CatalogoRegistroController : ApiControllerBase
    {

    [System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpGet]
    [Route("GetCatalogoPadre")]

    public HttpResponseMessage GetCatalogoPadre(HttpRequestMessage request)
    {
     //some code there for get results
    }

            return response;
        });
    }
    }

Something extrange happens there, if I try to get results using postman with GET action like:

http://localhost:55720/api/Catalogo/GetCatalogoPadre

I get correct results as:

{
        "ID": "1",
        "Codigo": "BMX",
        "Nombre": "BANAMEX",
        "Padre": 0,
        "Catalogo": "BAN"
    },
    {
        "ID": "2",
        "Codigo": "KNW",
        "Nombre": "KENWORTH",
        "Padre": 0,
        "Catalogo": "MAR"
    },

But them dont appear into select list, can someone view something wrong in code?. Regards

Body:
It should be,

<select class="form-control" ng-options="item.Nombre for item in Catalogos "></select>

also ensure that you are calling the function on ng-init

 <div class="form-group" ng-init="cargarCatalogo()">
    <label>Register: </label>
    <select class="form-control" ng-options="item.Nombre for item in Catalogos"></select>
    <br />
  </div>

DEMO

var myApp=angular.module('myApp',[]);
 myApp.controller('thecontroller',function($scope){
       $scope.cargarCatalogo = function (){
            $scope.catalogos = [{
        "ID": "1",
        "Codigo": "BMX",
        "Nombre": "BANAMEX",
        "Padre": 0,
        "Catalogo": "BAN"
    },
    {
        "ID": "2",
        "Codigo": "KNW",
        "Nombre": "KENWORTH",
        "Padre": 0,
        "Catalogo": "MAR"
    }];
    };
});

<!DOCTYPE html>
    <html>
        <head>
          <title>ng-Messages Service</title>
          <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
            <script src='https://code.angularjs.org/1.5.0-rc.0/angular.min.js'></script>
        </head>
        <body ng-app="myApp">
            <div ng-controller='thecontroller' ng-init="cargarCatalogo()">
           <div class="col-xs-12 col-sm-6 col-md-4">
  <div class="form-group">
    <label>Register: </label>
    <select class="form-control" ng-model="SelectedOption"       ng-options="choice.Codigo for choice in catalogos track by choice.ID">></select>
    <br />
  </div>
</div>
            </div>
        </body>
    </html>


问:
Umbraco - Current node image
I'm trying to get an image from the current node, in Umbraco. I know the way I'm using it is not the best, but I'm trying to understand something. Here is my code :

```<code>var image = Node.GetCurrent().GetProperty("image").Value.ToString();
var url = @Umbraco.Media(image).Url;
</code>```

First, I'm getting the Image value :  umb://media/b59274b4328f4f39866144bef8edef58

From this value, I'm trying to get the Url, but my var url is empty.

But, when I try :

```<code>@Umbraco.Media(Model.Content.GetPropertyValue("image").ToString()).Url
</code>```

Everything is working.

I don't understand this.

答:
Ok. I've not found the why.

I really want someone to answer me why this is not working.

I've found a workaround :

```<code>@CurrentPage.Image.Url
</code>```

Thanks !

Title: Umbraco - Current node image

Body:
I'm trying to get an image from the current node, in Umbraco. I know the way I'm using it is not the best, but I'm trying to understand something. Here is my code :

var image = Node.GetCurrent().GetProperty("image").Value.ToString();
var url = @Umbraco.Media(image).Url;

First, I'm getting the Image value :  umb://media/b59274b4328f4f39866144bef8edef58

From this value, I'm trying to get the Url, but my var url is empty.

But, when I try :

@Umbraco.Media(Model.Content.GetPropertyValue("image").ToString()).Url

Everything is working.

I don't understand this.

Body:
Ok. I've not found the why.

I really want someone to answer me why this is not working.

I've found a workaround :

@CurrentPage.Image.Url

Thanks !


答:
You need to append time data to your values in order to use lag properly. The shift will then be done in the time component of your time series while the values remain the same. Here is an example.

```<code>myTs <- ts(dat$y1, start = c(2000, 2), frequency = 12)

myTs
#         Feb    Mar    Apr    May    Jun    Jul    Aug    Sep
# 2000 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25

lag(myTs, 1)
#         Jan    Feb    Mar    Apr    May    Jun    Jul    Aug
# 2000 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25

lag(myTs, -3)
#         May    Jun    Jul    Aug    Sep    Oct    Nov    Dec
# 2000 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25
</code>```

lag is also defined for (numeric) vectors, but behaves somewhat different. The shift is saved as an (start/end/stepsize) attribute but the results are rather difficult to use later on (at least for me)

```<code>y1 <- dat$y1

y1
# [1] 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25

lag(y1, 1)
# [1] 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25
# attr(,"tsp")
# [1] 0 7 1

lag(y1, -3)
# [1] 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25
# attr(,"tsp")
# [1]  4 11  1
</code>```

Title: Lag a Time Series in R

Body:
I have a column "y1" and I am trying to take the log difference and then find lag 1, 2, 3, and 4.

> # Data Import
> dat <- read.csv("book1.csv", header=TRUE, sep=",")
> dat
   year Month     y1
1 2000   Feb 125.25
2 2000   Mar 145.23
3 2000   Apr 588.23
4 2000   May 244.12
5 2000   Jun 100.25
6 2000   Jul 585.00
7 2000   Aug 782.25
8 2000   Sep  12.25
> y1 <- dat[,3]       # y1 column
> y1
[1] 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25
> dy1 <- c(diff(log(y1)))
> y11 <- lag(dy1, 1)  # Lag-1
> y12 <- lag(dy1, 2)  #Lag-2
> y13 <- lag(dy1, 3)  #Lag-3
> y14 <- lag(dy1, 4)  #lag-4
>
> y <- cbind(dy1,y11,y12,y13,y14)
> y
        dy1        y11        y12        y13        y14
 [1,]  0.1480070  0.1480070  0.1480070  0.1480070  0.1480070
 [2,]  1.3987993  1.3987993  1.3987993  1.3987993  1.3987993
 [3,] -0.8794581 -0.8794581 -0.8794581 -0.8794581 -0.8794581
 [4,] -0.8899928 -0.8899928 -0.8899928 -0.8899928 -0.8899928
 [5,]  1.7639448  1.7639448  1.7639448  1.7639448  1.7639448
 [6,]  0.2905625  0.2905625  0.2905625  0.2905625  0.2905625
 [7,] -4.1566484 -4.1566484 -4.1566484 -4.1566484 -4.1566484

I was expecting once I take the log difference, the first value would be missing and replaced by "NA". Also, I was expecting the first two value would be "NA" once I take lag-1 for the series and so on. Any help would be appreciated it. Thank you in advance.

Body:
You need to append time data to your values in order to use lag properly. The shift will then be done in the time component of your time series while the values remain the same. Here is an example.

myTs <- ts(dat$y1, start = c(2000, 2), frequency = 12)

myTs
#         Feb    Mar    Apr    May    Jun    Jul    Aug    Sep
# 2000 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25

lag(myTs, 1)
#         Jan    Feb    Mar    Apr    May    Jun    Jul    Aug
# 2000 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25

lag(myTs, -3)
#         May    Jun    Jul    Aug    Sep    Oct    Nov    Dec
# 2000 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25

lag is also defined for (numeric) vectors, but behaves somewhat different. The shift is saved as an (start/end/stepsize) attribute but the results are rather difficult to use later on (at least for me)

y1 <- dat$y1

y1
# [1] 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25

lag(y1, 1)
# [1] 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25
# attr(,"tsp")
# [1] 0 7 1

lag(y1, -3)
# [1] 125.25 145.23 588.23 244.12 100.25 585.00 782.25  12.25
# attr(,"tsp")
# [1]  4 11  1


问:
What SQL magic do I need to turn one column into several?
I need to print some tickets, each of which has enough room to hold one set of customer details along with codes for up to five items ordered by that customer. Customers who have ordered more than five items get multiple tickets. So from an orders table like this,

```
Customer | Item
---------|------
Bob      | FTMCH
Bob      | ZORP
Bob      | KLUGE
Carol    | FTMCH
Carol    | MEEP
Carol    | ZORP
Ted      | FOON
Ted      | SMOCK
Alice    | ORGO
Carol    | SQICK
Carol    | BLECH
Carol    | KLUGE
Carol    | GLURP
```

I need a query that returns this:

```
Customer | Item1 | Item2 | Item3 | Item4 | Item5
---------|-------|-------|-------|-------|------
Alice    | ORGO  | null  | null  | null  | null
Bob      | FTMCH | ZORP  | KLUGE | null  | null
Carol    | FTMCH | MEEP  | ZORP  | SQICK | BLECH
Carol    | KLUGE | GLURP | null  | null  | null
Ted      | FOON  | SMOCK | null  | null  | null
```

Can some kind soul help me with the SQL for this? HSQL embedded database in OpenOffice.org Base, if it makes a difference.

答:
I believe this is only usable for T-SQL, but you can use PIVOT: http://msdn.microsoft.com/en-us/library/ms177410.aspx

I did something similar with a list of dates becoming the columns for calculations.

ContentLicense: CC BY-SA 2.5

Body:
I need to print some tickets, each of which has enough room to hold one set of customer details along with codes for up to five items ordered by that customer. Customers who have ordered more than five items get multiple tickets. So from an orders table like this,

Customer | Item
---------|------
Bob      | FTMCH
Bob      | ZORP
Bob      | KLUGE
Carol    | FTMCH
Carol    | MEEP
Carol    | ZORP
Ted      | FOON
Ted      | SMOCK
Alice    | ORGO
Carol    | SQICK
Carol    | BLECH
Carol    | KLUGE
Carol    | GLURP

I need a query that returns this:

Customer | Item1 | Item2 | Item3 | Item4 | Item5
---------|-------|-------|-------|-------|------
Alice    | ORGO  | null  | null  | null  | null
Bob      | FTMCH | ZORP  | KLUGE | null  | null
Carol    | FTMCH | MEEP  | ZORP  | SQICK | BLECH
Carol    | KLUGE | GLURP | null  | null  | null
Ted      | FOON  | SMOCK | null  | null  | null

Can some kind soul help me with the SQL for this? HSQL embedded database in OpenOffice.org Base, if it makes a difference.


问:
Link to open a Google Drive file in Sheets
Using the Google Drive API I can get a file's webViewLink to link to the file-preview in Drive, and the user can then select 'Open with Google Sheets' in the top bar to open the file up in Sheets.

Is there a way to skip that intermediary step, and link directly to that file in Google Sheets?

答:
What are you seeing in webViewLink?

When I try, I get

```<code>"webViewLink": https://docs.google.com/spreadsheets/d/1egZQnArX7TOHlQWSHiba3TTNt9Y7JoqgDAIJMdM0MQ/edit?usp=drivesdk"
</code>```

which directly opens the sheet.

So a couple of things:-

Are you sure that the file in question is a native Google spreadsheet, or is it, for example, an uploaded Excel

If your webViewLink is different, you could construct the URL yourself by setting your own file's ID after the /d/

Body:
What are you seeing in webViewLink?

When I try, I get

"webViewLink": https://docs.google.com/spreadsheets/d/1egZQnArX7TOHlQWSHiba3TTNt9Y7JoqgDAIJMdM0MQ/edit?usp=drivesdk"

which directly opens the sheet.

So a couple of things:-

Are you sure that the file in question is a native Google spreadsheet, or is it, for example, an uploaded Excel

If your webViewLink is different, you could construct the URL yourself by setting your own file's ID after the /d/


问:
Laravel 5.3 : Method [show] does not exist
When post my form to the controller, the laravel shows this error:

Method PTA_OIMS\Http\Controllers\InstructionsController::show() does
  not exist in
  /home/rad/public_html/pta_oims/vendor/laravel/framework/src/Illuminate/Routing/Route.php:333

this is my web.php file:

```<code>Route::post('instructions/view','InstructionsController@view')->name('view');
Route::post('instructions/assign','InstructionsController@assign');
Route::get('instructions/sent','InstructionsController@sent')->name('sent');
Route::post('instructions/reject','InstructionsController@reject')->name('reject');
Route::resource('instructions','InstructionsController');
</code>```

and blade view:

```<code> <form action=" {{url('instructions/assign')}}"
</code>```

Became more complete:

InstructionsController and added show(),view() and assign() method

```<code>public function show()
{
    return 'show() method done!!';
}
</code>```

view() method

```<code>public function view(Request $request)
{
    $boxes = $this->getBoxesList();
    $id = $request->input('id');
    $data = Kartable::where('id', '=', $id)
        ->with('instruction')
        ->first();
    if ($data->view_date == NULL) {
        $this->insertViewDate($id);
    }

    return view('instructions.view', array('data' => $data, 'boxes' => $boxes));
}
</code>```

view blade file, The form that sends the data to assign() method:

```<code><form method="POST" action=" {{url('instructions/assign')}}"
    class="form-horizontal" role="form" data-toggle="validator">

    {{csrf_field()}}
</code>```

assign() method

```<code>public function assign(Request $input)
{
    try {

        $inst_id = $input->input('inst_id');
//        $childsInsts = Instructions::where('parent_id', '=', $inst_id)
//             ->where('status', '=', 0)
//             ->get();
        $formData = $input->all();
        $step = 0;
        foreach ($formData['box'] as $box) {
            foreach ($box as $id_reciver)
                DB::transaction(function () use ($formData, $inst_id, $id_reciver, $step) {
                    $kar = new Kartable();

                    $kartable_id = $formData['kartable_id'];
                    $current_box = $formData['current_box'];
                    $kar->inst_id = $inst_id;
                    $kar->parent_id = $kartable_id;
                    $kar->id_sender = $current_box;
                    $kar->id_reciver = $id_reciver;
                    $kar->status = 1;
                    $kar->save(); // insert for new record of kartable
                    $step += 1;
                    if ($step < 2) {
                        $kartable = new Kartable();
                        $kartable
                            ->where('id', '=', $kartable_id)
                            ->update(['status' => 3]); //change status of old row kartable
                    }
                });

            return redirect()->route('instructions.index');
        }
    } catch (\Exception $e) {
        dd($e);
    }
}
</code>```

答:
have you checked that in your "InstructionsController" has an "show" method?

Because you're declaring Route::resource('instructions','InstructionsController');
Then you Laravel assumes that the controller has the methods below:

Check this docs from Laravel bro.

Hope that helps you.

Body:
When post my form to the controller, the laravel shows this error:

Method PTA_OIMS\Http\Controllers\InstructionsController::show() does
  not exist in
  /home/rad/public_html/pta_oims/vendor/laravel/framework/src/Illuminate/Routing/Route.php:333

this is my web.php file:

Route::post('instructions/view','InstructionsController@view')->name('view');
Route::post('instructions/assign','InstructionsController@assign');
Route::get('instructions/sent','InstructionsController@sent')->name('sent');
Route::post('instructions/reject','InstructionsController@reject')->name('reject');
Route::resource('instructions','InstructionsController');

and blade view:

 <form action=" {{url('instructions/assign')}}"

Became more complete:

InstructionsController and added show(),view() and assign() method

public function show()
{
    return 'show() method done!!';
}

view() method

public function view(Request $request)
{
    $boxes = $this->getBoxesList();
    $id = $request->input('id');
    $data = Kartable::where('id', '=', $id)
        ->with('instruction')
        ->first();
    if ($data->view_date == NULL) {
        $this->insertViewDate($id);
    }

    return view('instructions.view', array('data' => $data, 'boxes' => $boxes));
}

view blade file, The form that sends the data to assign() method:

<form method="POST" action=" {{url('instructions/assign')}}"
    class="form-horizontal" role="form" data-toggle="validator">

    {{csrf_field()}}

assign() method

public function assign(Request $input)
{
    try {

        $inst_id = $input->input('inst_id');
//        $childsInsts = Instructions::where('parent_id', '=', $inst_id)
//             ->where('status', '=', 0)
//             ->get();
        $formData = $input->all();
        $step = 0;
        foreach ($formData['box'] as $box) {
            foreach ($box as $id_reciver)
                DB::transaction(function () use ($formData, $inst_id, $id_reciver, $step) {
                    $kar = new Kartable();

                    $kartable_id = $formData['kartable_id'];
                    $current_box = $formData['current_box'];
                    $kar->inst_id = $inst_id;
                    $kar->parent_id = $kartable_id;
                    $kar->id_sender = $current_box;
                    $kar->id_reciver = $id_reciver;
                    $kar->status = 1;
                    $kar->save(); // insert for new record of kartable
                    $step += 1;
                    if ($step < 2) {
                        $kartable = new Kartable();
                        $kartable
                            ->where('id', '=', $kartable_id)
                            ->update(['status' => 3]); //change status of old row kartable
                    }
                });

            return redirect()->route('instructions.index');
        }
    } catch (\Exception $e) {
        dd($e);
    }
}


问:
When should this-> be used?
I was wondering if this-> should be used both:

```<code>void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}
</code>```

I'm wondering if the latter is necessary to be proper or if isEnabled = enabled would suffice.

Thanks

答: I think in C++ you leave out the this->, however it's probably personal preference.  With or without the code still does the same thing.

Title: When should this-> be used?

Body:
I was wondering if this-> should be used both:

void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}

I'm wondering if the latter is necessary to be proper or if isEnabled = enabled would suffice.

Thanks


问:
YouTube: How to present embed video with sound muted
I'm trying to embed a video with the sound muted but I can not figure out how it make it work.

Currently I'm using this but doesn't work:

```<code><iframe src="https://www.youtube.com/embed/uNRGWVJ10gQ?rel=0&autoplay=1" width="560" height="315" frameborder="0" allowfullscreen></iframe>
</code>```

Any of you knows how can I make this work ?

答:
```<code><iframe width="560" height="315" src="https://www.youtube.com/embed/ULzr7JsFp0k?list=PLF8tTShmRC6vp9YTjkVdm1qKuTimC6K3e&rel=0&autoplay=1&controls=1&loop=1" rel=0&amp frameborder="0" allowfullscreen></iframe>
</code>```

Body:
I'm trying to embed a video with the sound muted but I can not figure out how it make it work.

Currently I'm using this but doesn't work:

Any of you knows how can I make this work ?

Body: <iframe width="560" height="315" src="https://www.youtube.com/embed/ULzr7JsFp0k?list=PLF8tTShmRC6vp9YTjkVdm1qKuTimC6K3e&rel=0&amp;autoplay=1&controls=1&loop=1" rel=0&amp frameborder="0" allowfullscreen></iframe>


问:
Creating category-subcategory model upto nth level in rails
I want to create a model of categories with nth level subcategories. I can create upto 2 levels but could not go beyond it.

```<code>class Category < ActiveRecord::Base
   has_many :subcategories, :class_name => "Category", :foreign_key => "parent_id", :dependent => :destroy
   belongs_to :parent, :class_name => "Category"
end
</code>```

I do not want to use any gem for it.

答:
Edit i would try this

```<code>#category.rb
has_many :sub_category_ones
has_many :sub_category_twos, through: :sub_category_ones
has_many :sub_category_threes, through: :sub_category_twos
has_many :sub_category_fours, through: :sub_category_threes

#sub_category_one.rb
belongs_to :category
has_many :sub_category_twos

#sub_category_two.rb
belongs_to :sub_category_one
has_many :sub_category_threes

#sub_category_three.rb
belongs_to :sub_category_two
has_many :sub_category_fours

#sub_category_fours
belongs_to :sub_category_three
</code>```

And then you can say:

category.sub_category_fours # I think! :)

Will you please send me the strong-params if it works and you build a accepts_nested_attributes_for corresponding system, so you can save it all with @category.save!

Good luck! I hope it works. :)

Body:
I want to create a model of categories with nth level subcategories. I can create upto 2 levels but could not go beyond it.

class Category < ActiveRecord::Base
   has_many :subcategories, :class_name => "Category", :foreign_key => "parent_id", :dependent => :destroy
   belongs_to :parent, :class_name => "Category"
end

I do not want to use any gem for it.

Body:
Edit i would try this

#category.rb
has_many :sub_category_ones
has_many :sub_category_twos, through: :sub_category_ones
has_many :sub_category_threes, through: :sub_category_twos
has_many :sub_category_fours, through: :sub_category_threes

#sub_category_one.rb
belongs_to :category
has_many :sub_category_twos

#sub_category_two.rb
belongs_to :sub_category_one
has_many :sub_category_threes

#sub_category_three.rb
belongs_to :sub_category_two
has_many :sub_category_fours

#sub_category_fours
belongs_to :sub_category_three

And then you can say:

category.sub_category_fours # I think! :)

Will you please send me the strong-params if it works and you build a accepts_nested_attributes_for corresponding system, so you can save it all with @category.save!

Good luck! I hope it works. :)


问:
Installed modules not displayed for editor user role Prestashop 1.6.1.11
I created a user role called Editor, allow show/add/edit of modules and services for them, but when I log in with that role, uninstalled modules are listed only.
I set filter to Installed modules, but no results in the list.

How can I list installed/enabled modules for the new Editor role?

答: I think You did not selected the module's permission in Editor's permission please check the screenshot (https://i.stack.imgur.com/xZ09E.jpg) you will get. Just select View and it will show you all modules in that role. Thanks</p>


问:
How to bind individual Border CornerRadius?
I made a round window with Border like this:

```<code><Border CornerRadius="{Binding WindowCornerRadius}" Background="{StaticResource BackgroundDarkBrush}">
    <Border.Effect>
        <DropShadowEffect ShadowDepth="0" Opacity="0.2"></DropShadowEffect>
    </Border.Effect>
</Border>
<Grid>
    <Grid.RowDefinitions>
        <!--Title Bar-->
        <RowDefinition Height="{Binding TitleHeightGridLength}"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>
    <!--Title Bar-->
    <Border Background="{StaticResource TitleBrush}" CornerRadius="{Binding WindowCornerRadius,WindowCornerRadius,0,0}">
        <Grid Grid.Column="0" Panel.ZIndex="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto" />
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="auto"/>
            </Grid.ColumnDefinitions>
            <Button Style="{StaticResource SystemIconButton}" Command="{Binding MenuCommand}">
                <Image Source="Images/Logo/Wink.png"></Image>
            </Button>
        </Grid>
    </Border>
</Grid>
</Grid>
</Border>
</code>```

As you see I changed Background of first GridRow and this prevents it to be round(To have corner radius) and I would like to correct it adding border to first GridRow But I failed. The code above gives me error in CornerRadius="{Binding WindowCornerRadius,WindowCornerRadius,0,0}" :

No constructor for type "Binding" has 4 arguments.

My question is am I doing it correct by adding another border? (If yes how can I Bind CornerRadius individually).

答:
You cannot use a binding like this. A binding on CornerRadius will look for a Thickness-typed property from your DataContext, with the Path given inside the binding. The path is implicit in a binding, but you can set it explicitely : Property="{Binding Path=blabla}". More info here.

Does the CornerRadius dynamically change? Why?

Also have a look at this :
Binding only part of the margin property of WPF control

Body:
I made a round window with Border like this:

<Border CornerRadius="{Binding WindowCornerRadius}" Background="{StaticResource BackgroundDarkBrush}">
    <Border.Effect>
        <DropShadowEffect ShadowDepth="0" Opacity="0.2"></DropShadowEffect>
    </Border.Effect>
</Border>
<Grid>
    <Grid.RowDefinitions>

        <RowDefinition Height="{Binding TitleHeightGridLength}"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <Border Background="{StaticResource TitleBrush}" CornerRadius="{Binding WindowCornerRadius,WindowCornerRadius,0,0}">
        <Grid Grid.Column="0" Panel.ZIndex="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto" />
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="auto"/>
            </Grid.ColumnDefinitions>
            <Button Style="{StaticResource SystemIconButton}" Command="{Binding MenuCommand}">
                <Image Source="Images/Logo/Wink.png"></Image>
            </Button>
        </Grid>
    </Border>
</Grid>
</Grid>
</Border>

As you see I changed Background of first GridRow and this prevents it to be round(To have corner radius) and I would like to correct it adding border to first GridRow But I failed. The code above gives me error in CornerRadius="{Binding WindowCornerRadius,WindowCornerRadius,0,0}" :

No constructor for type "Binding" has 4 arguments.

My question is am I doing it correct by adding another border? (If yes how can I Bind CornerRadius individually).


答:
A. Put the script inside head or body.

B. Either put the script after #kaptree, or add a document ready statement. You try to call something that isn't there yet.

```<code>        <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Testtree</title>
      <script>
        document.addEventListener('DOMContentLoaded', function(){
          document.getElementById("kaptree").innerHTML="TEST";
        }, false);
      </script>
      </head>
      <body>
         <div id="kaptree"></div>
      </body>
    </html>
</code>```

Body:
the following code should display the word Test...but instead the message TypeError: document.getElementById(...) is displayed.
I can't figure out why:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>

Can anyone help me to open my eyes?

Body:
A. Put the script inside head or body.

B. Either put the script after #kaptree, or add a document ready statement. You try to call something that isn't there yet.

        <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Testtree</title>
      <script>
        document.addEventListener('DOMContentLoaded', function(){
          document.getElementById("kaptree").innerHTML="TEST";
        }, false);
      </script>
      </head>
      <body>
         <div id="kaptree"></div>
      </body>
    </html>


答:
The element with the id "kaptree" is not available at this place. Move the script block below the body and it works.

Otherwise you have to wait for the document-ready state.


问:
Circle with thickness drawing algorithm
Currently I am using Bresenham's circle drawing algorithm, which draws circles fine, however I would like a relatively fast and efficient way to draw a circle with a specified thickness (since Bresenham's method only draws a single pixel thickness). I realise that I could simply draw multiple circles with different radii, but I believe this would be very inefficient (and efficiency is important because this will be running on an Arduino where every microsecond is precious).
I am currently using the following code:

```<code>void circle(byte xc, byte yc, int radius, Colour colour) {
  int x = -radius, y = 0, err = 2 - 2 * radius;
  while(x < 0) {
    setPixel(xc - x, yc + y, colour);
    setPixel(xc - y, yc - x, colour);
    setPixel(xc + x, yc - y, colour);
    setPixel(xc + y, yc + x, colour);
    radius = err;
    if(radius <= y) {
      err += ++y * 2 + 1;
    }
    if(radius > x || err > y) {
      err += ++x * 2 + 1;
    }
  }
}
</code>```

How could I modify this to allow for specification of the circle's thickness?
PS I don't want to use any external libraries, please!

答:
The solution below can be slow, however, it is very simple.

First, draw the inner and outern circles using Bresenham's algorithm. Then, check condition:

```<code>if (pow(i - centre, 2) + pow(j - centre, 2) <= pow(outern_radius,2) &&
            pow(i - centre, 2) + pow(j - centre, 2) >= pow(inner_radius,2))
</code>```

If it is satisfied, setPixel(i,j).

Title: Circle with thickness drawing algorithm

Body:
Currently I am using Bresenham's circle drawing algorithm, which draws circles fine, however I would like a relatively fast and efficient way to draw a circle with a specified thickness (since Bresenham's method only draws a single pixel thickness). I realise that I could simply draw multiple circles with different radii, but I believe this would be very inefficient (and efficiency is important because this will be running on an Arduino where every microsecond is precious).
I am currently using the following code:

void circle(byte xc, byte yc, int radius, Colour colour) {
  int x = -radius, y = 0, err = 2 - 2 * radius;
  while(x < 0) {
    setPixel(xc - x, yc + y, colour);
    setPixel(xc - y, yc - x, colour);
    setPixel(xc + x, yc - y, colour);
    setPixel(xc + y, yc + x, colour);
    radius = err;
    if(radius <= y) {
      err += ++y * 2 + 1;
    }
    if(radius > x || err > y) {
      err += ++x * 2 + 1;
    }
  }
}

How could I modify this to allow for specification of the circle's thickness?
PS I don't want to use any external libraries, please!

Body:
The solution below can be slow, however, it is very simple.

First, draw the inner and outern circles using Bresenham's algorithm. Then, check condition:

if (pow(i - centre, 2) + pow(j - centre, 2) <= pow(outern_radius,2) &&
            pow(i - centre, 2) + pow(j - centre, 2) >= pow(inner_radius,2))

If it is satisfied, setPixel(i,j).


问:
Convert this Excel formula into VBA code
```<code>=IF((effDate)-curDate>0,0,IF(curDate-(effDate)+1>nDays,0,nSpend/4))+IF((effDate+365/4*1)-curDate>0,0,IF(curDate-(effDate+365/$4*1)+1>nDays,0,nSpend/4))+IF((effDate+365/4*2)-curDate>0,0,IF(curDate-(effDate+365/4*2)+1>nDays,0,nSpend/4))+IF((effDate+365/4*3)-curDate>0,0,IF(curDate-(effDate+365/4*3)+1>nDays,0,nSpend/4))

effDate: 1/1/2017 (as value)
curDate: 1/31/2017 (as value)
nSpend: 1600
nDays: 60
Correct answer: 400
</code>```

Above is a long formula I'm trying to covert to VBA code. The way I've been trying to do it is long and I tried breaking it up into smaller functions, but it's not giving me the right answer. My VBA skills are very beginner so I'm not sure what else to try. I keep getting the wrong answer or no answer at all.

This is what I've been trying:

```<code>If effdate - curdate > 0 Then
val1 = 0
Exit Function
End If

If curdate - effDate + 1 > nDays Then
val1 = 0
Else
val1 = nSpend / 4

End If

If (effDate + (365 / 4)) - curdate > 0 Then
val2 = 0
Exit Function
End If

If curdate - (effDate + (365 / 4)) + 1 > nDays Then
val2 = 0
Else
val2 = nSpend / 4
End If

If effDate + (365 / (4 * 2)) - curdate > 0 Then
val3 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 2))) + 1 > nDays Then
val3 = 0
Else
val3 = nSpend / 4
End If

If effDate + (365 / (4 * 3)) - curdate > 0 Then
val4 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 3))) + 1 > nDays Then
val4 = 0
Else
val4 = nSpend / 4
End If
End If

APFcst = val1 + val2 + val3 + val4

End Function
</code>```

I dimmed everything correctly, it's the actual conversion that I have problems with.
I would appreciate the help! This is also a huge learning stretch for me since I just started learning VBA coding.
Thank you!

答:
If you know the formula then you can use Evaluate() to achieve what you want.

```<code>Sub Sample()
    Dim f1, f2, f3, f4

    f1 = "=IF((effDate)-curDate>0,0,IF(curDate-(effDate)+1>nDays,0,nSpend/4))"
    f2 = "=IF((effDate+365/4*1)-curDate>0,0,IF(curDate-(effDate+365/4*1)+1>nDays,0,nSpend/4))"
    f3 = "=IF((effDate+365/4*2)-curDate>0,0,IF(curDate-(effDate+365/4*2)+1>nDays,0,nSpend/4))"
    f4 = "=IF((effDate+365/4*3)-curDate>0,0,IF(curDate-(effDate+365/4*3)+1>nDays,0,nSpend/4))"

    '~~> Change Sheet1 to the relevant sheet code name
    Debug.Print Sheet1.Evaluate(f1) + Sheet1.Evaluate(f2) + Sheet1.Evaluate(f3) + Sheet1.Evaluate(f4)
End Sub
</code>```

Body:
=IF((effDate)-curDate>0,0,IF(curDate-(effDate)+1>nDays,0,nSpend/4))+IF((effDate+365/4*1)-curDate>0,0,IF(curDate-(effDate+365/$4*1)+1>nDays,0,nSpend/4))+IF((effDate+365/4*2)-curDate>0,0,IF(curDate-(effDate+365/4*2)+1>nDays,0,nSpend/4))+IF((effDate+365/4*3)-curDate>0,0,IF(curDate-(effDate+365/4*3)+1>nDays,0,nSpend/4))

effDate: 1/1/2017 (as value)
curDate: 1/31/2017 (as value)
nSpend: 1600
nDays: 60
Correct answer: 400

Above is a long formula I'm trying to covert to VBA code. The way I've been trying to do it is long and I tried breaking it up into smaller functions, but it's not giving me the right answer. My VBA skills are very beginner so I'm not sure what else to try. I keep getting the wrong answer or no answer at all.

This is what I've been trying:

If effdate - curdate > 0 Then
val1 = 0
Exit Function
End If

If curdate - effDate + 1 > nDays Then
val1 = 0
Else
val1 = nSpend / 4

End If

If (effDate + (365 / 4)) - curdate > 0 Then
val2 = 0
Exit Function
End If

If curdate - (effDate + (365 / 4)) + 1 > nDays Then
val2 = 0
Else
val2 = nSpend / 4
End If

If effDate + (365 / (4 * 2)) - curdate > 0 Then
val3 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 2))) + 1 > nDays Then
val3 = 0
Else
val3 = nSpend / 4
End If

If effDate + (365 / (4 * 3)) - curdate > 0 Then
val4 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 3))) + 1 > nDays Then
val4 = 0
Else
val4 = nSpend / 4
End If
End If

APFcst = val1 + val2 + val3 + val4

End Function

I dimmed everything correctly, it's the actual conversion that I have problems with.
I would appreciate the help! This is also a huge learning stretch for me since I just started learning VBA coding.
Thank you!

Body:
If you know the formula then you can use Evaluate() to achieve what you want.

Sub Sample()
    Dim f1, f2, f3, f4

    f1 = "=IF((effDate)-curDate>0,0,IF(curDate-(effDate)+1>nDays,0,nSpend/4))"
    f2 = "=IF((effDate+365/4*1)-curDate>0,0,IF(curDate-(effDate+365/4*1)+1>nDays,0,nSpend/4))"
    f3 = "=IF((effDate+365/4*2)-curDate>0,0,IF(curDate-(effDate+365/4*2)+1>nDays,0,nSpend/4))"
    f4 = "=IF((effDate+365/4*3)-curDate>0,0,IF(curDate-(effDate+365/4*3)+1>nDays,0,nSpend/4))"

    '~~> Change Sheet1 to the relevant sheet code name
    Debug.Print Sheet1.Evaluate(f1) + Sheet1.Evaluate(f2) + Sheet1.Evaluate(f3) + Sheet1.Evaluate(f4)
End Sub


问:
N-Series Virtual Machine not available on bizspark subscription
I have a Bizspark Subscription with Rs.10,000 in credit. I want to setup a GPU with N-Series Virtual Machine. But it is showing "This size is not available in the location for the subscription." Even after entering the appropriate regions shown on Azure Products by Region

Why is this happening?

Also my partner had been using NV-12 Virtual Machine from 3 months with Bizspark Subscription.

How is this possible?

答: You could be restricted by Azure to certain regions, say only south east asia. Create a support ticket to lift that limitation and\or learn the exact set of regions you are allowed to use</p>


问:
a simple person class in objective c
I'm starting to learn objective c, I made a simple person class, i get 6 errors,
expected specifier-qualifier-list before '-' token

just wondering if someone can explain to me what I'm doing wrong,

thanks

```<code>#import <Foundation/Foundation.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>

@interface Person:NSObject
{
    NSString *firstName;
    NSString *lastName;

    -(void) setFName:(NSString *) theFirstName;
    -(void) setLName:(NSString *) theLastName;
    -(void) printName;
}
@end

@implementation Person
{

    -(void) setFName:(NSString *) theFirstName
    {
        firstName = [[NSString alloc]initWithString: theFirstName];
    }

    -(void) setLName:(NSString *) theLastName
    {
        lastName = [[NSString alloc]initWithString: theLastName];
    }

    -(void) printName
    {
        NSLog(@"The person's full name is",firstName,lastName);
    }

}

@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Person *person = [[Person alloc] init];

    [person setFName:@"Amir"];
    [person setLName:@"Karimian"];
    [person printName];

    [person release];
    [pool drain];
    return 0;
}
</code>```

答:
Method declaration will be outside of closing brace.

```<code>@interface Person:NSObject
{
    NSString *firstName;
    NSString *lastName;
}

-(void) setFName:(NSString *) theFirstName;
-(void) setLName:(NSString *) theLastName;
-(NSString *) firstName;
-(NSString *) lastName;
-(void) printName;

@end
</code>```

And in implementation no brace is required.

```<code>@implementation Person
// { is not required
-(void) setFName:(NSString *) theFirstName {
    // code
}

-(void) setLName:(NSString *) theLastName {

}

// in this way

// } is not required
@end
</code>```

There are at least two logical errors. In printName

```<code>NSLog(@"The person's full name is %@ %@",firstName,lastName);
</code>```

Your format string was wrong.

And in main

```<code>[person setLName:@"Karimian"];
</code>```

You have user "ser" instead of "set".

Title: a simple person class in objective c

Body:
I'm starting to learn objective c, I made a simple person class, i get 6 errors,
expected specifier-qualifier-list before '-' token

just wondering if someone can explain to me what I'm doing wrong,

thanks

#import <Foundation/Foundation.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>

@interface Person:NSObject
{
    NSString *firstName;
    NSString *lastName;

    -(void) setFName:(NSString *) theFirstName;
    -(void) setLName:(NSString *) theLastName;
    -(void) printName;
}
@end

@implementation Person
{

    -(void) setFName:(NSString *) theFirstName
    {
        firstName = [[NSString alloc]initWithString: theFirstName];
    }

    -(void) setLName:(NSString *) theLastName
    {
        lastName = [[NSString alloc]initWithString: theLastName];
    }

    -(void) printName
    {
        NSLog(@"The person's full name is",firstName,lastName);
    }

}

@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Person *person = [[Person alloc] init];

    [person setFName:@"Amir"];
    [person setLName:@"Karimian"];
    [person printName];

    [person release];
    [pool drain];
    return 0;
}

Body:
Method declaration will be outside of closing brace.

@interface Person:NSObject
{
    NSString *firstName;
    NSString *lastName;
}

-(void) setFName:(NSString *) theFirstName;
-(void) setLName:(NSString *) theLastName;
-(NSString *) firstName;
-(NSString *) lastName;
-(void) printName;

@end

And in implementation no brace is required.

@implementation Person
// { is not required
-(void) setFName:(NSString *) theFirstName {
    // code
}

-(void) setLName:(NSString *) theLastName {

}

// in this way

// } is not required
@end

There are at least two logical errors. In printName

NSLog(@"The person's full name is %@ %@",firstName,lastName);

Your format string was wrong.

And in main

[person setLName:@"Karimian"];

You have user "ser" instead of "set".


问:
Loading .dot file in graphviz
I was looking for a way to create Digraph instance using graphviz package from existing .dot (or .gv) file, is that possible?

I want to do that in order to add/change attributes in the graph and then render altered graph.

NOTE:

1) I tried loading .dot file using Source class, however it does not seem to have methods to change the loaded graph. (Mentioned here How to parse a DOT file in Python).

2) I cannot use any other packages (i.e. pygraphviz, pydot etc.)

3) The .dot file contains a correctly formatted graph.

答: You could parse the .dot source file using ANTLR4 and this grammar., and the python binding for ANTLR4.  I use C# myself with ANTLR4 but believe there is a python implementation.

Title: Loading .dot file in graphviz


问:
Web Scraping in R with loop from data.frame
```<code>library(rvest)

df <- data.frame(Links = c("Qmobile_Noir-M6", "Qmobile_Noir-A1", "Qmobile_Noir-E8"))

for(i in 1:3) {
  webpage <- read_html(paste0("https://www.whatmobile.com.pk/", df$Links[i]))
  data <- webpage %>%
    html_nodes(".specs") %>%
    .[[1]] %>%
    html_table(fill = TRUE)
}
</code>```

want to make loop works for all 3 values in df$Links but above code just download the last one, and downloaded data must also be identical with variables (may be a new column with variables name)

答:
it is capturing all three values, but it writes over them with each loop. That's why it only shows one value, and that one value being for the last page

You need to initialise a variable first before you go into your loop, I suggest a list so you can store data for each successive loop. So something like

```<code>final_table <- list()

for(i in 1:3) {
   webpage <- read_html(paste0("https://www.whatmobile.com.pk/",   df$Links[i]))
   data <- webpage %>%
   html_nodes(".specs") %>%
   .[[1]] %>%
html_table(fill= TRUE)

 final_table[[i]] <- data.frame(data, stringsAsFactors = F)
}
</code>```

In this was, it appends new data to the list with each loop.

Body:
library(rvest)

df <- data.frame(Links = c("Qmobile_Noir-M6", "Qmobile_Noir-A1", "Qmobile_Noir-E8"))

for(i in 1:3) {
  webpage <- read_html(paste0("https://www.whatmobile.com.pk/", df$Links[i]))
  data <- webpage %>%
    html_nodes(".specs") %>%
    .[[1]] %>%
    html_table(fill = TRUE)
}

want to make loop works for all 3 values in df$Links but above code just download the last one, and downloaded data must also be identical with variables (may be a new column with variables name)

Body:
it is capturing all three values, but it writes over them with each loop. That's why it only shows one value, and that one value being for the last page

You need to initialise a variable first before you go into your loop, I suggest a list so you can store data for each successive loop. So something like

final_table <- list()

for(i in 1:3) {
   webpage <- read_html(paste0("https://www.whatmobile.com.pk/",   df$Links[i]))
   data <- webpage %>%
   html_nodes(".specs") %>%
   .[[1]] %>%
html_table(fill= TRUE)

 final_table[[i]] <- data.frame(data, stringsAsFactors = F)
}

In this was, it appends new data to the list with each loop.


问:
How to configure the note types in XFS with the 'WFS_CMD_CIM_CONFIGURE_NOTETYPES' command
I want to configure specific note types during cash in operation

Input parameter should be in the following format: LPUSHORT lpusNoteIDs;

When I execute the below commands I get invalid data error (-52)

```<code>LPUSHORT* lpusNoteIDs;
lpusNoteIDs = (LPUSHORT*)malloc(7*sizeof(LPUSHORT));
for(int i =0;i<7;i++)
{
    lpusNoteIDs[i]=(LPUSHORT)malloc(sizeof(USHORT));
}

lpusNoteIDs[0] = (LPUSHORT)0x2700;
lpusNoteIDs[1] = (LPUSHORT)0x2710;
lpusNoteIDs[2] = (LPUSHORT)0x2701;
lpusNoteIDs[3] = (LPUSHORT)0x2711;
lpusNoteIDs[4] = (LPUSHORT)0x2721;
lpusNoteIDs[5] = (LPUSHORT)0x2732;
lpusNoteIDs[6] = (LPUSHORT)0x2704;
hResult = WFSExecute(hService, WFS_CMD_CIM_CONFIGURE_NOTETYPES, (LPVOID)lpusNoteIDs, 400000, &res);
return (int)hResult;
</code>```

I have even tried the below code but it gives me the same error

```<code>LPUSHORT* lpusNoteIDs;
USHORT abc[]={1000,9985,10001,10017,10034,9988};
lpusNoteIDs=(LPUSHORT*)abc;
hResult = WFSExecute(hService, WFS_CMD_CIM_CONFIGURE_NOTETYPES,(LPVOID)lpusNoteIDs, 600000, &res);
return (int)hResult;
</code>```

In  CIM Service Provider Implementation Specification document it says:

lpusNoteIDs :-Pointer to a NULL terminated list of unsigned shorts which contains the note IDs of the bank notes

Any help as to how the values must be passed would be very useful..
Thanks in advance.

答:
You must use WFMAllocate and WFMAllocateMore functions to allocate memory for XFS structures to transfer it between application and service provider.
Your example bellow:</p>

```<code>LPUSHORT lpusNoteIDs = NULL;
const int countNotes = 7;
// Always use WFMAllocate* functions for XFS memory allocation
WFSRESULT hr = WFMAllocateBuffer(sizeof(USHORT)*(countNotes+1), WFS_MEM_ZEROINIT|WFS_MEM_SHARE, (void**)&lpusNoteIDs);

// Fill note ID's
lpusNoteIDs[0] = (USHORT)0x2700;
lpusNoteIDs[1] = (USHORT)0x2710;
lpusNoteIDs[2] = (USHORT)0x2701;
lpusNoteIDs[3] = (USHORT)0x2711;
lpusNoteIDs[4] = (USHORT)0x2721;
lpusNoteIDs[5] = (USHORT)0x2732;
lpusNoteIDs[6] = (USHORT)0x2704;

hr = WFSExecute(hService, WFS_CMD_CIM_CONFIGURE_NOTETYPES, (LPVOID)&lpusNoteIDs, 400000, &res);
</code>```

Body:
I want to configure specific note types during cash in operation

Input parameter should be in the following format: LPUSHORT lpusNoteIDs;

When I execute the below commands I get invalid data error (-52)

LPUSHORT* lpusNoteIDs;
lpusNoteIDs = (LPUSHORT*)malloc(7*sizeof(LPUSHORT));
for(int i =0;i<7;i++)
{
    lpusNoteIDs[i]=(LPUSHORT)malloc(sizeof(USHORT));
}

lpusNoteIDs[0] = (LPUSHORT)0x2700;
lpusNoteIDs[1] = (LPUSHORT)0x2710;
lpusNoteIDs[2] = (LPUSHORT)0x2701;
lpusNoteIDs[3] = (LPUSHORT)0x2711;
lpusNoteIDs[4] = (LPUSHORT)0x2721;
lpusNoteIDs[5] = (LPUSHORT)0x2732;
lpusNoteIDs[6] = (LPUSHORT)0x2704;
hResult = WFSExecute(hService, WFS_CMD_CIM_CONFIGURE_NOTETYPES, (LPVOID)lpusNoteIDs, 400000, &res);
return (int)hResult;

I have even tried the below code but it gives me the same error

LPUSHORT* lpusNoteIDs;
USHORT abc[]={1000,9985,10001,10017,10034,9988};
lpusNoteIDs=(LPUSHORT*)abc;
hResult = WFSExecute(hService, WFS_CMD_CIM_CONFIGURE_NOTETYPES,(LPVOID)lpusNoteIDs, 600000, &res);
return (int)hResult;

In  CIM Service Provider Implementation Specification document it says:

lpusNoteIDs :-Pointer to a NULL terminated list of unsigned shorts which contains the note IDs of the bank notes

Any help as to how the values must be passed would be very useful..
Thanks in advance.

Body:
You must use WFMAllocate and WFMAllocateMore functions to allocate memory for XFS structures to transfer it between application and service provider.
Your example bellow:

LPUSHORT lpusNoteIDs = NULL;
const int countNotes = 7;
// Always use WFMAllocate* functions for XFS memory allocation
WFSRESULT hr = WFMAllocateBuffer(sizeof(USHORT)*(countNotes+1), WFS_MEM_ZEROINIT|WFS_MEM_SHARE, (void**)&lpusNoteIDs);

// Fill note ID's
lpusNoteIDs[0] = (USHORT)0x2700;
lpusNoteIDs[1] = (USHORT)0x2710;
lpusNoteIDs[2] = (USHORT)0x2701;
lpusNoteIDs[3] = (USHORT)0x2711;
lpusNoteIDs[4] = (USHORT)0x2721;
lpusNoteIDs[5] = (USHORT)0x2732;
lpusNoteIDs[6] = (USHORT)0x2704;

hr = WFSExecute(hService, WFS_CMD_CIM_CONFIGURE_NOTETYPES, (LPVOID)&lpusNoteIDs, 400000, &res);