text:
Q: How to delete information in jsf pages, which use a session managed bean as data resource? i have a question concerning two java beans, which was declared in faces-config.xml and have two different managed-bean-scopes in JSF 1.2. First of all i would like to explain the problem, which i have now.
I have the possibility to export some information from my java system into an another system (the details of the data and their concret transport way are not so important i think).
Important is in my opinion, that the java bean, which triggers that export, has the managed bean scope "session". The data export works i the background of my system and need this session scope.
The user can see an information in the jsf / xhtml page, that the export was started and here is the concret problem:
<ui:repeat value="#{adminArea.informationForExport}" var="info">
    <h:outputText value="#{info}" />
</ui:repeat>

This information is a part of the HTML DOM each time and will not disappears, if the user watch an another xhtml page in my system and goes back to this xhtml page, on that he can start the data export.
My Bean "adminArea" was declared in faces-config.xml with the managed bean scope "session" and implemented the java code for the data export:
<managed-bean>
    <managed-bean-name>adminArea</managed-bean-name>
    <managed-bean-class>resources.adminArea</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

The declared bean "adminArea" was refered as a managed property in the bean "newCalculation", which was the managed bean scope "request":
<managed-bean>
    <managed-bean-name>newCalculation</managed-bean-name>
    <managed-bean-class>resources.calculation</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>adminArea</property-name>
        <value>#{adminArea}</value>
    </managed-property>
</managed-bean>

This bean needs the managed bean scope "request".
Is the only way the change the managed bean scope of the bean "adminArea" from "session" into "request"? But that causes the problem, that my data export doesn´t work in the background.
Or can i solve this problem with other instruments?
Greetz
Marwied

A: Final answer:

*

*Move to JSF 2.0. It has many useful features described here.

*If you want to display specific information on a specific page try to use view scope. Take a look at here to see the difference between Request and View scopes. Try to link user interface directly with view scoped beans. All session or application information you can recieve by ManagedProperty injection.

*I suggest you to refuse from xml-configured beans and move to annotations. Good comment about that you can read here.

*About background processing in JSF. Those things are usually performed by Enterprise Java Beans (EJBs). Take a look at EJB 3 and maybe Timer Service.


text:
Q: Load file from input type = file , Typescript I have input
            <input
                accept="image/*"
                id="contained-button-file"
                multiple
                type="file"
            />

And i want to load the file selected using:
 const selectedFile = ( document.getElementById('contained-button-file') as HTMLInputElement  ).files[0];

But Typescript complains:
TS2531: Object is possibly 'null'.
How can i work around this or make sure it has file selected ( as i want to send it to server ) ?
THanks for help

A: You can check if files is truthy then get files[0]
const input = document.getElementById('contained-button-file') as HTMLInputElement;
const file = input.files ? input.files[0] : null;

A: Quick and dirty solution:
const selectedFile = (
  document.getElementById('contained-button-file') as HTMLInputElement
).files![0];

This says that files will not be null, which is true in this case. TS just doesn't know that the input is of type file.

Error handling solution
const element = document.getElementById('contained-button-file');
if (!element || !(element instanceof HTMLInputElement))
  throw Error('Could not retrieve file input element');

const input = element as HTMLInputElement;
if (!input.files) throw Error('File input is not of type "file"');

const selectedFile = input.files[0];

Typescript is able to see that you've put these guards in place and knows that the objects cannot be null in the code underneath them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PhpStorm project still using PHP5 even though I installed PHP7 and added it as an interpreter I tried to run composer install on a project and received this error:

Problem 1
     - This package requires php ^7.0.0 but your PHP version (5.5.12) does not satisfy that requirement.

So I've installed downloaded the PHP 7 zip from php.net then followed this tutorial step by step until (and including) step 4 https://www.sitepoint.com/how-to-install-php-on-windows/
Then at step 5 the commands didn't work and I stopped. I've added PHP 7 as an interpreter in PhpStrom as seen in the picture below but when I run composer install again it still gives me the same error.

Please advise me on how to fix this problem. Thanks in advance.

A: The problem is not with PHPStorm but with your CLI. You need to go to your console type "which php" and you will see from where PHP is executed. Setup your CLI PHP version as PHP7 and it will solve the problem.
If you are on windows then you need to check from PATH variable where php.exe is located and change the path to PHP7 location.
See also manual page about installation php on windows


text:
Q: i dont see hello packets in trace file I am using AODV routing protocol for neighbor discovery in ns2 but the trace file does not show any hello packet. The trace file looks like :
s 1.000000000 _0_ AGT  --- 0 cbr 210 [0 0 0 0] ------- [0:0 1:0 32 0] [0] 0 0
r 1.000000000 _0_ RTR  --- 0 cbr 210 [0 0 0 0] ------- [0:0 1:0 32 0] [0] 0 0
s 1.000000000 _0_ RTR  --- 0 AODV 48 [0 0 0 0] ------- [0:255 -1:255 30 0] [0x2 1 1 [1 0] [0 4]] (REQUEST)
s 1.003750000 _0_ AGT  --- 1 cbr 210 [0 0 0 0] ------- [0:0 1:0 32 0] [1] 0 0
r 1.003750000 _0_ RTR  --- 1 cbr 210 [0 0 0 0] ------- [0:0 1:0 32 0] [1] 0 0

A: In default hello packets is in disable mode in AODV protocol.
You can enable hello packets by doing below things,
comment or remove the below lines from your aodv.cc  (ns-all-in-one/ns2.xx/aodv)
#define AODV_LINK_LAYER_DETECTION

#define AODV_USE_LL_METRIC

execute make clean and make in your terminal.
re execute your tcl.. now hello packets will printed in your trace file.

A: Sir,
I am using NS2.35 version, In that version the for file aodv.cc,following lines by default commented.
define AODV_LINK_LAYER_DETECTION
define AODV_USE_LL_METRIC
once, simulate the script not able to see hello msg in trace file


text:
Q: Array elements in methods and returning value back to array I am working on some code for a product (no particular item) program.  Here's what I need help learning:
I need to take two array elements(numbers[4] and numbers[5]), make a method, add them together in that method, then return and store them back to array element numbers[6].
How can I create a method that can read the information already stored in the array?
Here's my code:
// This is an inventory program part 1 "Section 1"
public class inventory {

    public static void main(String[] args) {

        String[] inventory = new String[8];

        inventory[0] = "hammer";
        inventory[1] = "shovel";
        inventory[2] = "Product#";
        inventory[3] = "Product Name";
        inventory[4] = "Units In Stock";
        inventory[5] = "Price";
        inventory[6] = "Total Value Of Product";
        inventory[7] = "Total Value of Entire Inventory";

        float[] numbers = new float[7];

        numbers[0] = 1585;// hammers in stock
        numbers[1] = 900;// shovels in stock
        numbers[2] = (float) 7.48;// hammer price
        numbers[3] = (float) 9.98;// shovel price
        numbers[4] = ( numbers[0] * numbers[2] );// total value of hammers in inventory
        numbers[5] = ( numbers[1] * numbers[3] );// total value of shovels in inventory
        numbers[6] = ( numbers[4] + numbers[5] );// total value of products in inventory

        int[] productNum = new int[2];
        productNum[0] = 5211;// hammer part #
        productNum[1] = 5212;// shovel part #

        System.out.print(numbers[6]);
    }
    public static float total(){
        return 0;
    }
}

A: If you just want your total method to add the two elements then change it to:
public static float total(float x, float y)
{
    return x + y;
}

and you would call this as follows
numbers[6] = total(numbers[4], numbers[5]);


text:
Q: CSS horizontal menu doesnt work I have a problem with my css menu.. It doesn't work....
I want to use a hover over a button, to switch a display attribute from another element.
I use CSS3 Grid-System. I don't know if that is the problem?
First things first, here is my code:
First a css part (only the affected):

.navigation{
        grid-column: 1;
        grid-row: 2 / 3;
        justify-items: end;
        justify-self: end;

        width: auto;
        margin: 0;
        padding: 0;

        background-color: rgba(0,0,0,0.7);

        display: grid;
        grid-template-columns: 1;
        grid-template-rows: 50px 50px;
    }

    .navigationButton-icon{
        display: none;
        background-color: white;
        border: 2px solid;
        border-color: deepskyblue;
        border-radius: 10px;
        cursor: pointer;

        margin-top: 5px;
        padding-left: 50px;
        padding-right: 50px;
    }

    .navigation #butInsert{
        grid-column: 1;
        grid-row: 1 / 2;
        justify-self: start;
        width: 100%;
    }

    .navigation #butCreate{
        grid-column: 1;
        grid-row: 2 / 3;
        justify-self: start;
        width: 100%;
    }

    #butMenu:hover .navigationButton-icon{
        display: block;
    }

        <!DOCTYPE html>

            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Surveys</title>

            <link rel="stylesheet" type="text/css" href="styles/inline.css">
            <link rel="stylesheet" type="text/css" href="styles/fontello.css">
            <link href="https://fonts.googleapis.com/css?family=Nunito:300,400" rel="stylesheet">

            <container class="container">

Surveys

                    <button id="butRefresh" class="headerButton-icon"></button>
                    <button id="butMenu" class="headerButton-icon"></button>

                <?php include('snippets/survey.php'); ?>

            <navigation class="navigation">
                    <button id="butInsert" class="navigationButton-icon">Insert</button>
                    <button id="butCreate" class="navigationButton-icon">Create</button>
            </navigation>

                IMPRESSUM

            </container>

I hope you can help me. I tried it for like 3 hours now..
I can manipulate attributes from the hover element but it doesn't work for other elements of the dom.
Greetings

A: That's not how CSS works. #butMenu:hover .navigationButton-icon means #butMenu has to be an ancestor of .navigationButton-icon element.
You need JavaScript.
// jQuery
$('#butMenu').hover(
    function () {
        $('.navigation').addClass('butMenu-hover');
    }, function () {
        $('.navigation').removeClass('butMenu-hover');
    }
);

// Vanilla JS
(function () {
    var butMenu = document.getElementById('butMenu');
    var navigation = document.getElementsByClassName('navigation')[0];
    butMenu.onmouseenter = function () {
        navigation.classList.add('butMenu-hover');
    };
    butMenu.onmouseleave = function () {
        navigation.classList.remove('butMenu-hover');
    };
})();

And in your CSS:
.navigation.butMenu-hover .navigationButton-icon {
    display: block;
}


text:
Q: NODEJS Error when try to start a prod enviroment hope somebody can help me, Im pretty new dealing with prod enviroment, Im trying to deploy my nodejs backend on aws ec2 linux instance. Using pm2 to run the enviroment but after y use pm2 start ecosystem.config.js --env production command and I log the output I've got this logs:
at process.emit (events.js:327:22)
at emit (internal/child_process.js:876:12)
at processTicksAndRejections (internal/process/task_queues.js:85:21)
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
Error: bind EACCES null:80
at listenOnMasterHandle (net.js:1380:18)
at rr (internal/cluster/child.js:132:12)
at Worker.<anonymous> (internal/cluster/child.js:99:7)
at process.onInternalMessage (internal/cluster/utils.js:47:8)
at process.emit (events.js:327:22)
at emit (internal/child_process.js:876:12)
at processTicksAndRejections (internal/process/task_queues.js:85:21)


text:
Q: What app.set function does (express.js)? I am new to node.js and was going through an example could not understand app.set('title', 'My Site'); does please help?

A: I know I am a bit late to the party but I had the same problem and that's how I got here.
After I did some research, I fell that the answer is a bit incomplete.
In case that first parameter is an application setting, the following table must be read.
Property ->
Type ->
Description
case sensitive routing ->
Boolean  ->
Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same.
env ->
String ->
Environment mode. Be sure to set to "production" in a production environment; see Production best practices: performance and reliability.
process.env.NODE_ENV (NODE_ENV environment variable) or "development" if NODE_ENV is not set.
etag ->
Varied ->
Set the ETag response header. For possible values, see the etag options table.
jsonp callback name ->
String ->
Specifies the default JSONP callback name.
json replacer ->
Varied ->
The 'replacer' argument used by JSON.stringify.
NOTE: Sub-apps will inherit the value of this setting.
json spaces ->
Varied ->
The 'space' argument used by JSON.stringify. This is typically set to the number of spaces to use to indent prettified JSON.
NOTE: Sub-apps will inherit the value of this setting.
query parser ->
Varied   ->
Disable query parsing by setting the value to false, or set the query parser to use either "simple" or "extended" or a custom query string parsing function.
The simple query parser is based on Node's native query parser, querystring.
The extended query parser is based on qs.
A custom query string parsing function will receive the complete query string, and must return an object of query keys and their values.
strict routing ->
Boolean  ->
Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different. Otherwise, the router treats "/foo" and "/foo/" as the same.
NOTE: Sub-apps will inherit the value of this setting.
subdomain offset ->
Number ->
The number of dot-separated parts of the host to remove to access subdomain.
trust proxy ->
Varied   ->
Indicates the app is behind a front-facing proxy, and to use the X-Forwarded-* headers to determine the connection and the IP address of the client. NOTE: X-Forwarded-* headers are easily spoofed and the detected IP addresses are unreliable.
When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The req.ips property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the trust proxy options table.
The trust proxy setting is implemented using the proxy-addr package. For more information, see its documentation.
NOTE: Sub-apps will inherit the value of this setting, even though it has a default value.
views  ->
String or Array ->
A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array.
process.cwd() + '/views'
view cache ->
Boolean  ->
Enables view template compilation caching.
view engine ->
String ->
The default engine extension to use when omitted.
NOTE: Sub-apps will inherit the value of this setting.
x-powered-by ->
Boolean ->
Enables the "X-Powered-By: Express" HTTP header.

A: You can use the express instance to store and retrieve variables. In this case, you can set the title to be "My Site" and retrieve it later with something like
var title = app.get('title');

without the need to declare and keep a global variable messing around.
The name of the parameter means nothing. You could do
app.set('jabberwocky', 'correct battery horse staples');

as well. If you're using express with jade, for example, you might need to retrieve the value of 'jabberwocky' in a template, further along the line.

Edit: Since this answer got marked as correct and it's the most upvoted, It's my duty to point you to the one further below by Vlad Pana https://stackoverflow.com/a/44007538/1030087
Quire a few keynames you set on the app instance do have a special meaning.

A: Use the following
app.set('views', path.join(__dirname, 'views'));

This will set your apps view folder to something like:
/Users/jilles/Project/myApp/views


text:
Q: Combining two tables in a database I have made two tables. The first table holds the metadata of a file.
create table filemetadata (
id varchar(20) primary key ,
filename varchar(50),
path varchar(200),
size varchar(10),
author varchar(50)
) ;

+-------+-------------+---------+------+---------+
| id    | filename    | path    | size | author  |
+-------+-------------+---------+------+---------+
| 1     | abc.txt     | c:\files| 2kb  | eric    |
+-------+-------------+---------+------+---------+
| 2     | xyz.docx    | c:\files| 5kb  | john    |
+-------+-------------+---------+------+---------+
| 3     | pqr.txt     |c:\files | 10kb | mike    |
+-------+-------------+---------+------+---------+

The second table contains the "favourite" info about a particular file in the above table.
create table filefav (
fid varchar(20) primary key ,
id varchar(20),
favouritedby varchar(300),
favouritedtime varchar(10),
FOREIGN KEY (id) REFERENCES filemetadata(id)
) ;

+--------+------+-----------------+----------------+
| fid    | id   | favouritedby    | favouritedtime |
+--------+------+-----------------+----------------+
| 1      | 1    | ross            | 22:30          |
+--------+------+-----------------+----------------+
| 2      | 1    | josh            | 12:56          |
+--------+------+-----------------+----------------+
| 3      | 2    | johny           | 03:03          |
+--------+------+-----------------+----------------+
| 4      | 2    | sean            | 03:45          |
+--------+------+-----------------+----------------+

here "id' is a foreign key.
The second table is showing which person has marked which document as his/her favourite.
Eg the file abc.txt represented by id = 1 has been marked favourite (see column favouritedby) by ross and josh.
so what i wanna do is to get a table/view which shows the info as following -
+-------+-------------+---------+------+---------+---------------+
| id    | filename    | path    | size | author  | favouritedby  |
+-------+-------------+---------+------+---------+---------------+
| 1     | abc.txt     | c:\files| 2kb  | eric    | ross, josh    |
+-------+-------------+---------+------+---------+---------------+
| 2     | xyz.docx    | c:\files| 5kb  | john    | johny, sean   |
+-------+-------------+---------+------+---------+---------------+
| 3     | pqr.txt     |c:\files | 10kb | mike    | NULL          |
+-------+-------------+---------+------+---------+---------------+

How do i achieve this?

A: Use JOIN (from the top of my head, no checks done):
SELECT filemetadata.id, filename, path, size, author, GROUP_CONCAT(favouritedby)
FROM filemetadata
LEFT JOIN filefav ON filemetadata.id=filefav.id GROUP BY filemetadata.id

A: Select A.*,B.favouritedby FROM filemetadata A Left join (Select id,Group_Concat(favouritedby) from filefav  group by id) B ON A.Id=B.Id

A: Create a view that creates a UNION of the two tables:
CREATE VIEW filefavs AS
SELECT * FROM filemetadata
UNION
SELECT * FROM filefav


text:
Q: Grub-install: device vs partition Grub can be installed to a device (grub-install /dev/sda) and to a certain partition (grub-install /dev/sda1) - as I understood. My question - if we install it to a partition will grub-installer write something to MBR? If not, how bios/uefi will find out from what partition to load?

A: If you install Grub to a partition, nothing is modified outside that partition. In particular, the MBR (if the disk has classical DOS partitions) is not modified. If you do that, Linux can only be booted if the bootloader in the BIOS or UEFI knows where to look for it. The reason to install Grub on a partition is when you already have another bootloader in the MBR that knows where to load it, typically another operating system that has its own boot menu. Many bootloaders from other operating systems offer to boot primary partitions that have the "active" flag set.


text:
Q: Parse.com MealSpotting tutorial onitemclicklistener not working i'm having some trouble getting the onclicklistener to work with a customadapter from parse.com's mealspotting android app. When I try clicking on an item in the list nothing happens in the logcat (except for the standard "can't load audio" or whatever), i'm pretty sure i need to attach something to the adapter but i haven't found a way to implement that with parse's APIs. When a list item is clicked I want it to show the DetailViews class activity by the way.
This is where i'm trying to implement the onclicklistener

package com.parse.mealspotting;
import java.util.Arrays;

import android.content.Context;

import android.util.Log;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import android.widget.TextView;
import android.widget.Toast;

import com.parse.GetDataCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseImageView;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;

public class MealSpottingViewYay extends ParseQueryAdapter<Meal> implements OnItemClickListener {

  private ParseQueryAdapter<Meal> posts;
  private static final String TAG = "MealSpottingViewYay";

  public MealSpottingViewYay(Context context) {
      super(context, new ParseQueryAdapter.QueryFactory<Meal>() {
          public ParseQuery<Meal> create() {
              // Here we can configure a ParseQuery to display
              // only top-rated meals.
              ParseQuery query = new ParseQuery("Meal");
              return query;

          }
      });
  }

  @Override
  public View getItemView(Meal meal, View v, ViewGroup parent) {

      if (v == null) {
          v = View.inflate(getContext(), R.layout.main_list_view, null);
      }

      super.getItemView(meal, v, parent);

      ParseImageView mealImage = (ParseImageView) v.findViewById(R.id.icon);
      ParseFile photoFile = meal.getParseFile("photo");
      if (photoFile != null) {
          mealImage.setParseFile(photoFile);
          mealImage.loadInBackground(new GetDataCallback() {
              @Override
              public void done(byte[] data, ParseException e) {
                  // nothing to do

              }});

      }

      TextView titleTextView = (TextView) v.findViewById(R.id.text1);
      titleTextView.setText(meal.getTitle());
      TextView ratingTextView = (TextView) v
              .findViewById(R.id.favorite_meal_rating);
      ratingTextView.setText(meal.getRating());
      return v;
  }

  public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            Log.d(TAG, "onItemClick");

        ParseObject parseObject = posts.getItem(position);

        // Use the parseobject here
        Context context = getContext();
        Toast toast = Toast.makeText(context, "Clicked!", Toast.LENGTH_SHORT);
        toast.show();

        }
    }

and this is my mainactivity class

package com.parse.mealspotting;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.parse.ParseObject;
import com.parse.ParseQueryAdapter;

public class MealListActivity extends ListActivity {

  private MealSpottingViewYay mainAdapter;
  private FavoriteMealAdapter22 favoritesAdapter;

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      getListView().setClickable(false);

      mainAdapter = new MealSpottingViewYay(this);

      // There's probably a better way to do this
      if (mainAdapter != null){
          updateMealList();
      }

      // Subclass of ParseQueryAdapter
      favoritesAdapter = new FavoriteMealAdapter22(this);

  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.activity_meal_list, menu);
      return true;
  }

  /*
   * Posting meals and refreshing the list will be controlled from the Action
   * Bar.
   */

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {

      case R.id.action_refresh: {
          updateMealList();
          break;
      }

      case R.id.action_favorites: {
          showFavorites();
          break;
      }

      case R.id.action_new: {
          newMeal();
          break;
      }
      }
      return super.onOptionsItemSelected(item);
  }

  private void updateMealList() {
      mainAdapter.loadObjects();
      setListAdapter(mainAdapter);
  }

  private void showFavorites() {
      favoritesAdapter.loadObjects();
      setListAdapter(favoritesAdapter);
  }

  private void newMeal() {
      Intent i = new Intent(this, NewMealActivity.class);
      startActivityForResult(i, 0);
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
      if (resultCode == Activity.RESULT_OK) {
          // If a new post has been added, update
          // the list of posts
          updateMealList();
      }
  }

}

Thanks!

A: You haven't set a click listener to your listview. Try this getListView().setOnItemClickListener(mainAdapter) as your adapter has implemented an onItemClickListenerinterface.


text:
Q: How to display only the non chosen language in the language switcher menu in a multilingual drupal 7 website?  Hi. I'm a newbie in Drupal development.
I'm building a multilingual website in French and English using Drupal 7.
I'm using Internationalization and Entity translation modules to translate contents and blocks in the page.
I'm using the theme Omega, with the sub-theme Foundation downloaded from the website friendlymachine to which I added another sub-theme file to modify the CSS.
I'm already having a language switcher block which is working properly.
My question is: what code in which file can I modify (and how?) to display in the language switcher only the non chosen (i.e the needed) language?
i.e: If I'm currently using the website in French, Only the option "English" is displayed on the language switcher menu. And vice versa. (if I'm using the website in English, only the option "French" is displayed in the language switcher menu).

Any help would be welcomed.
Thank you.

A: Hide the current language link (which is not link but text) for the Language Switcher block with css. It has a specific class for that purpose.


text: Q: Error when using suggest mode in a GitHub pull request (large file) In our GitHub pull requests, we are using suggestion mode successfully when we edit smaller files, however, when we try to suggest a change in a large file (in this case a large ontology file), I get this error when I try to commit suggested changes: This diff has recently been updated. Refresh and try again. It does, however, not work when I refresh and try again (same message).


text:
Q: Cant get fscanf to perform correctly in simple program I keep getting a Seg fault on line 51 fscanf(fp, "%d", lenPtr). Everytime I run the program, "1" is printed, but it never gets to 2 before seg faulting. I have done this many times, and cannot seem to figure out the trouble. I know it is incorrect, but when I replace line 51 with fscanf(fp,"%d", *lenPtr);, it doesn't cause a segmentation fault.
//Brendan Sullivan
//Section D
//Prelab 5

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef enum {
    PENNY   = 1,
    NICKEL  = 2,
    DIME    = 10,
    QUARTER = 25,
} Denomination;

typedef struct {
    Denomination denomination;
    int quantity;
} Coin;

typedef Coin *PiggyBank;

PiggyBank loadBank(const char *filename, int *lenPtr);
int totalMoney(PiggyBank bank, int length);

int main(int argc, char *argv[]) {
    int *length;
    PiggyBank piggyBank = loadBank(argv[1], length);

    /*for (i = 0; i < (*lenPtr); i++) {
            printf("%d %d", piggyBank[i].denomination, piggyBank[i].quantity);
    }*/
    return 0;
}

PiggyBank loadBank(const char *filename, int *lenPtr) {
    FILE *fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("File could not be opened\n");
        *lenPtr = 0;
        return NULL;
    }
    printf("1\n");
    fscanf(fp, "%d", lenPtr); //Line 51
    printf("2\n");
    printf("%d\n", *lenPtr);
    PiggyBank piggyBank = malloc(sizeof(Coin) * (*lenPtr));

    int i;
    for (i = 0; i < *lenPtr; i++) {
        fscanf(fp,"%u %d", &piggyBank[i].denomination, &piggyBank[i].quantity);
    }
    return piggyBank;
    fclose(fp);
}

A: You call loadBank with a uninitialized int* length as the destination pointer.  Undefined behavior ensues.  You should instead to this:
int main(int argc, char *argv[]) {
    int i, length;
    PiggyBank piggyBank = loadBank(argv[1], &length);

    for (i = 0; i < length; i++) {
        printf("%d %d\n", piggyBank[i].denomination, piggyBank[i].quantity);
    }
    return 0;
}

Note that the code in loadBank does not allocate anything and returns an undefined variable piggyBank in the middle of the function.  Either your code does not compile or you are not posting it correctly.


text:
Q: SQL-Server - Bulk Insert Error 7301 Using SQL Server 2016, I am working on a legacy system that requires its nightly import to run via bulk insert. I know SSIS is a better option, but not one that's available to me.
I am uploading the file from the local machine with the following command:
BULK INSERT DataImports.staging_Companies
FROM 'D:\xxxxx\companies_20180802093057.txt'
WITH (BATCHSIZE = 1000
,     DATAFILETYPE = 'char'
,     FIRSTROW = 2
,     FIELDTERMINATOR = '   ' -- Tab Character here
,     ROWTERMINATOR = '\n'
,     ERRORFILE = 'D:\xxxxx\company_errors.txt');

No format file is being used, and due to our dynamic handling, we would not be able to use one. When uploading the file I am getting an error as:

Msg 7301, Level 16, State 2, Line 4
  Cannot obtain the required interface ("IID_IColumnsInfo") from OLE DB provider "BULK" for linked server "(null)".

The general opinion on this is that there is an issue with the row/line terminators. This is not the case here. The issue seems to be around file size or number of rows. The import works fine up to 2482 rows but falls over at 2483. By moving rows around I have ruled out an error on the data itself.
Once the file size/rowcount is exceeded, the command does not run at all. I have added a trigger to the destination table and a batch size, and see results for the smaller size, and none at all for the larger size.
From this, I am wondering if there is something that causes an interruption while reading the file, and cuts it off halfway through a line? I have used and maintained this system for a while and have seen far larger files processed before in terms of both rows, and data size.
Update:
Have just transferred this file onto my local machine, and ran the import on my test db (SQL2017).  The bulk insert ran fine with no errors. My local version 14.0.1000.169, client server 13.0.1601.5.
Also tested on another 2016 Server (13.0.4474.0) and that ran fine.  Is there anything in server setup that may be causing this issue? Or even something from the main file system? Am clutching at straws now.
Any ideas gratefully received.


text:
Q: CSS Overflow Scroll issue with Complex Nested Div's I have a floating div (popup window) that contains a div header, a scrolling content section and a footer.  This is a simplification:

html,
body,
.outer {
  height: 200px;
  background: pink;
  border: 1px
}
.inner {
  display: inline-block;
  height: 100%;
  width: 100%;
  background: lime;
  border: 1px;
  overflow: hidden
}
.tabs {
  height: 50px;
  background: blue;
}
.header {
  height: 50px;
  background: yellow;
}
.main {
  height: auto;
  overflow: scroll;
  background: orange;
}
.footer {
  background: red;
  position: absolute;
  padding: 1em;
  bottom: 0;
  width: 100%;
}

      Tabs

      Header Info

      .. line1 ..

.. line2 ..

.. line3 ..

.. line4 ..

.. line5 ..

.. line6 ..

.. line7 ..

.. line8 ..

.. line9 ..

.. line10 ..

.. line11 ..

.. line12 ..

      Footer Info

Here is is in JSFiddle: JSFiddle Example
The problem is the content in the main seciton gets clipped instead of scrolling.

A: Specify the height on .main instead of .outer.
http://jsfiddle.net/fknc5p27/1/
https://jsfiddle.net/gptuk4uz/6/

html,
body,
.outer {
  /*height: 200px;*/
  background: pink;
  border: 1px
}
.inner {
  display: inline-block;
  height: 100%;
  width: 100%;
  background: lime;
  border: 1px;
  overflow: hidden
}
.tabs {
  height: 50px;
  background: blue;
}
.header {
  height: 50px;
  background: yellow;
}
.main {
  height: 150px;
  overflow: auto;
  background: orange;
}
.footer {
  background: red;
  position: absolute;
  padding: 1em;
  bottom: 0;
  width: 100%;
}

      Tabs

      Header Info

      .. line1 ..

.. line2 ..

.. line3 ..

.. line4 ..

.. line5 ..

.. line6 ..

.. line7 ..

.. line8 ..

.. line9 ..

.. line10 ..

.. line11 ..

.. line12 ..

      Footer Info


text:
Q: Determine protocol of a network drive Is there a way to determine the protocol name (SMB/CIFS,NFS) and version that is used for a mounted network drive on windows? (in C#)
EDIT
Using info from Rusted's answer, i got the following information from a windows 7 computer on the network.
NETRESOURCE res = WinApiWNETwrapper.GetResourceInfo("\\Test-PC");

res.dwDisplayType = SERVER
res.dwScope       = 0
res.dwType        = ANY
res.dwUsage       = CONTAINER
res.lpComment     = ""
res.lpLocalName   = null
res.lpProvider    = "Microsoft Windows Network"
res.lpLocalName   = "\\Test-PC"

NETINFOSTRUCT netinfo = WinApiWNETwrapper.GetNetworkInfo("\\Test-PC");

netinfo.cbStructureSize   = 32
netinfo.dwCharacteristics = 0
netinfo.dwDrives          = -1
netinfo.dwHandle          = 1880621056
netinfo.dwPrinters        = -1
netinfo.dwProviderVersion = 1024
netinfo.dwStatus          = Running
netinfo.wNetType          = LANMAN

SERVER_TRANSPORT_INFO_1[] transports = WinApiNETwrapper.ServerTransportEnum_1("\\Test-PC");

transports[0].svti1_domain                 = "WORKGROUP"
transports[0].svti1_networkaddress         = "TEST-PC"
transports[0].svti1_numberofvcs            = 0
transports[0].svti1_transportaddress       = 73107336
transports[0].svti1_transportaddresslength = ...
transports[0].TransportAddress             = "TEST-PC"

transports[0].svti1_transportname          = "\\Device\\NetbiosSmb"
transports[1].svti1_transportname          = "\\Device\\NetBT_Tcpip_{F4C75115-...}"
transports[2].svti1_transportname          = "\\Device\\NetBT_Tcpip_{70BD9048-...}"

The important part seems to be:
transports[0].svti1_transportname          = "\\Device\\NetbiosSmb"

But i cannot find the version number of the SMB protocol anywhere. Any ideas?

A: I suppose you've need the Windows Networking (WNet) API, a value from NetType field in NETINFOSTRUCT returned by WNetGetNetworkInformation function.
Here is open-source project in C#, check files in WnetApi folder for .NET wrappers for Wnet API.
To get the UNC path for a mapped drive use PathToUNC method from this project.


text:
Q: Draw a border around an oval picturebox I've an oval picturebox (Code below). I want to add a border around the picturebox. I allready tried to add a second rect but this only made my region smaller. Is there any way to make a border?
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

class OvalPictureBox : PictureBox
{
    public OvalPictureBox()
    {

    }

    protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);
        using (var gp = new GraphicsPath())
        {
            gp.AddEllipse(new Rectangle(0, 0, this.Width - 1, this.Height - 1));

            this.Region = new Region(gp);
        }
    }

    private void InitializeComponent()
    {
        ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
        this.SuspendLayout();
        //
        // OvalPictureBox
        //
        ((System.ComponentModel.ISupportInitialize)(this)).EndInit();
        this.ResumeLayout(false);
    }
}

EDIT
I figured it out. I just draw an ellipse in the picturebox.
float penWidth = 5F;
Pen myPen = new Pen(Color.FromArgb(242, 141, 1), penWidth);
e.Graphics.DrawEllipse(myPen, new RectangleF(new PointF(0, 0), new
SizeF((float)(portraitPicture.Width - 1), portraitPicture.Height - 1)));
myPen.Dispose();

Is there a cleaner or better way? Or is this the best way?

A: Just draw ellipse that is bigger than the one you already have. But this ellipse should be drawn first, otherwise it would cover the other ellipse.
How much should it be bigger? Border width :)


text:
Q: Check last Database backup date in C# - SQL Server 2008 I have a C# windows Forms application and when the start-up Form loads, i want to check the last time a backup was performed on the database the application connects to.

A: you could create a store procedure that does the work for you. then you can execute it within the form's OnLoad event or where ever it fits for your need.
Have a look at the below for getting the T-SQL that does the trick
http://www.mssqltips.com/sqlservertip/1601/script-to-retrieve-sql-server-database-backup-history-and-no-backups/

A: These are taken from my automation of backups:
First get a list of all databases, including their database GUID:
select db.name, db.database_id, rec.database_guid
  from sys.databases db
    inner join sys.database_recovery_status rec on db.database_id = rec.database_id
  where db.source_database_id is null and db.name <> 'tempdb'

The condition on source_database_id excludes snapshots.
Then using the GUID from the above, get the date of the last full backup type='D' that isn't COPY_ONLY:
SELECT MAX(backup_finish_date) as backup_finish_date
  from msdb..backupset
  where type='D' and database_guid = @DbGuid and is_copy_only=0


text:
Q: References request: Auslander-Reiten theory of algebras like $B_{k,n}$ In the paper A categorification of Grassmannian cluster algebras, an algebra $B_{k,n}$ is defined as follows.
Denote by $C=(C_0, C_1)$ the circular graph with
vertex set $C_0=\mathbb{Z}_{n}$ clockwise around the circle, and with the edge set $C_1=\mathbb{Z}_n$, with edge
$i$ joining vertices $i-1$ and $i$, see Figure 3 on page 8 of the paper.
Denote by $Q_C$ the quiver with the same vertex set $C_0$ and with arrows
$x_i: i-1 \to i$, $y_i: i \to i-1$ for every $i \in C_0$, see Figure 3 on page 8 of the paper.
The algebra $B_{k,n}$ (it is denoted by $\overline{A}$ in the paper, see the paragraph before Remark 3.4 in the paper) is the quotient of the complete path algebra $\widehat{\mathbb{C} Q_C}$ by the ideal generated
by the $2n$ relations $x y = y x$, $x^{k} = y^{n-k}$ (two relations for each vertex of $Q_C$), where $x, y$ are arrows of the form $x_i, y_j$
for appropriate $i,j$.
Is the algebra $B_{k,n}$ an Artin algebra? If it is not an Artin algebra, has the Auslander-Reiten theory developed for this type of algebras? I am asking this question because I found that Auslander-Reiten theory is used in the paper and I would like to know some references. Thank you very much.

A: I think the algebra you describe is actually the algebra denoted by $\hat{A}$ in the paper you reference. $\bar{A}$ is an uncompleted version.
Neither algebra is an Artin algebra, or even an artinian ring, since the powers of the ideal generated by the arrows form an infinite decreasing sequence of ideals.
As far as I can see, the paper only uses the existence of Auslander-Reiten sequences for the category of (maximal) Cohen-Macaulay $\hat{A}$-modules, and justify their existence by a reference in Remark 3.3 to Auslander's paper:
Auslander, Maurice, Isolated singularities and existence of almost split sequences. Notes by Louise Unger, Representation theory II, Groups and orders, Proc. 4th Int. Conf., Ottawa/Can. 1984, Lect. Notes Math. 1178, 194-242 (1986); identical with: Representations of algebras, Proc. 4th Int. Conf., Ottawa/Can. 1984, Vol. 1, Carleton-Ottawa Math. Lect. Note Ser. 1, W5, 49 p. (1985). ZBL0633.13007.


text:
Q: How to style row header column in DataGrid I am using ComponentOne C1DataGrid. I have been able to style it to the full extent except row header column.
How can I style it in XAML?
You can see the image:
here
Thanks,
flot

A: Answering my own question in case somebody else is interesting:
There is a special presenter, DataGridRowHeaderPresenter, that can be styled.
I wanted to replace a standard row details toggle with the tree-like "+" and "-" signs and I did it as follows:
    <Style x:Key="DataGridRowHeaderStyle2" TargetType="{x:Type c1:DataGridRowHeaderPresenter}">
    <Setter Property="FontWeight" Value="Bold" />
    <Setter Property="FontSize" Value="12" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type c1:DataGridRowHeaderPresenter}">
                <!-- BulletDecorator is used to provide baseline alignment between the sign and the Content -->
                <BulletDecorator Background="#BFEFF2F5">
                    <BulletDecorator.Bullet>
                        <Grid Width="13" Height="13">
                            <Image Name="sign" Source="/myControls;component/Resources/Images/plus.png" />
                        </Grid>
                    </BulletDecorator.Bullet>
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/>
                </BulletDecorator>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsSelected" Value="true">
                        <Setter Property="Source"  Value="/myControls;component/Resources/Images/minus.png"  TargetName="sign"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


text:
Q: One WinPE for multiple different installations Im building a PXE boot environment to move away from many CD's / DVD's to one organized fast source for tools and installations. I want to do some unattended Windows installations and know the way I have to go. I setup WinPE for PXE boot and it's working. I also have the needed installations files ready and can install one Windows edition this way. However I would like to be able to install different versions of Windows with one WinPE, but I would need some kind of parameter which I can pass to WinPE to choose which installation file should be used to install the system.
I was thinking about a unix like init=/some/script/to/execute.sh parameter for the WinPE kernel, but it seems like WinPE does not accept any parameter at all.
My last way would be to just show Windows Install as menu entry in the PXE menu and then wait until WinPE got loaded and started a installation script which would provide a menu with the different installations listed, but I would prefer to have everything in PXE only.
I also thought about using a file which gets read by WinPE over the net which contains some sort of Key<->Value structure to save which installation was selected at PXE selection however I would need to write from the PXE menu to a remote file system which is, as far as I know, not possible.
Does anyone have a better idea?

A: What you are trying to do is pretty complex to create and a nightmare to maintain.
Microsoft already does it in RIS, WDS, MDT, and SCCM. Serva also does it implementing simpler versions of MS RIS and WDS (I'm related to Serva development).

A: I realize this is an old question and may not be relevant for OP, but I ran into a similar situation a few weeks ago, and this is the solution I'm using:
For the PXE server, I'm using iPXE, mainly because of a utility called wimboot, which, besides allowing you to boot directly into a WIM image, allows you to "patch" in additional files that appear within the WinPE virtual filesystem. I'm using this to pass in configuration files for a custom installer script, but you could simply pass in whatever unattend.xml, and WinPE will use it to install any install image you want.


text:
Q: Partial import of pyvirtualcam, python 3.8 on windows I want to set up a virtual webcam on windows.
Final aim being directing the output of OpenCV to meet (Say GMeet) frame by frame
Steps Done
A normal pip install showed the package not found.
I installed using the wheel distribution for python version 3.8.7 from pypi.
I also installed OBS Studio, and OBS-VirtualCam 2.0.4. As mentioned in the installation guide here.
I extracted the zip from the OBS-VritualCam release and could successfully start the virtualcam from the .dll file in the /bin/32bit directory by
regsvr32 /n /i:1 "obs-virtualsource.dll"

I could import pyvirtualcam!
But on running the code given with the package.
import pyvirtualcam
import numpy as np

with pyvirtualcam.Camera(width=1280, height=720, fps=30) as cam:
    while True:
        frame = np.zeros((cam.height, cam.width, 4), np.uint8) # RGBA
        frame[:,:,:3] = cam.frames_sent % 255 # grayscale animation
        frame[:,:,3] = 255
        cam.send(frame)
        cam.sleep_until_next_frame()

I get the error

Traceback (most recent call last):
File "pyvirtualcam.py", line 1, in
import pyvirtualcam
File "D:\sem7\DSL\Project\try\pyvirtualcam.py", line 4, in
with pyvirtualcam.Camera(width=1280, height=720, fps=30) as cam:
AttributeError: partially initialized module 'pyvirtualcam' has no
attribute 'Camera' (most likely due to a circular import)

Sources:
Capturing and manipulating a webcam feed and exposing it as a "virtual webcam" - in Python, on Windows

A: Rename your file to something else than pyvirtualcam.py otherwise Python tries to import that one when you do import pyvirtualcam.


text:
Q: Change Cell Color Based on Specific RGB Values in the Same Row I have an Excel spreadsheet using about 1200 rows and 5 columns. The A column contains names of colors. The B, C and D columns contain the Red, Green and Blue values of those colors. The E column is empty, but I would like each cell in the E column to be colored with the color with RGB values equal to those in the B, C and D columns in that row.
I have very little experience with VBA, and I have found no solutions in my searches.

A: Thanks pnuts, that link put me on the right track. For any interested, I added
For i as integer = 2 to 1200
    Cells(i, 5).Interior.Color = RGB(Cells(i, 4), Cells(i, 3), Cells(i, 2))
Next i

within the Worksheet Change event.


text:
Q: Get current (logged) user in ASP.NET Core 3.0 .razor page I'm testing the waters with a blazer server-side app and trying to get the logged user in a .razor page. This
UserManager.GetUserAsync(User)

works in .cshtml view, but I cannot find a way to get it to work in .razor page. There is no "User" property to access. I use the IdentityUser with my ApplicationUser model that extends IdentityUser. I'm using AspNetCore 3.0 Preview 6.

A: What I did:

*

*added this to Startup.ConfigureServices
services.AddHttpContextAccessor();

*used this to get the username in my .razor page, these 2 lines first

@inject UserManager<WebPageUser> UserManager
@inject IHttpContextAccessor HttpContextAccessor

*then the call to show the username like this:

Hello @UserManager.GetUserName(HttpContextAccessor.HttpContext.User)

A: If you surround your code with the AuthorizeView component you can get access to a context object that supplies the current user.
<AuthorizeView>
    <Authorized>

Hello, @context.User.Identity.Name!

You can only see this content if you're authenticated.

    </Authorized>
    <NotAuthorized>

Authentication Failure!

You're not signed in.

    </NotAuthorized>
</AuthorizeView>

If you don't want to use that approach you can request a cascading parameter called authenticationStateTask, which is provided by the CascadingAuthenticationState.
@page "/"

<button @onclick="@LogUsername">Log username</button>

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    private async Task LogUsername()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            Console.WriteLine($"{user.Identity.Name} is authenticated.");
        }
        else
        {
            Console.WriteLine("The user is NOT authenticated.");
        }
    }
}

A: this one works for Razor page .cshtml
@using Microsoft.AspNetCore.Identity
@using [yourproject].Areas.Identity.Data

@inject UserManager<NassPayUser> UserManager

@{
var currentuser=UserManager.GetUserAsync(User).Result;
}

if you want to get current user in .cs you can use the folowing.
private readonly UserManager<AppUser> _userManager;
public constucturModel(UserManager<AppUser> userManager)
        {
            _userManager = userManager;
        }

now you can reach any user you want by
var user = await _userManager.FindByIdAsync(userId);

or just loop through
var users = _userManager.Users;


text:
Q: Node.js SFTP client I want to access sftp servers through a node.js app. Do you know a library for this? Or have you an idea how I could realize this?
Thanks for your answers!

A: May be SSH2(https://www.npmjs.org/package/ssh2) library will help you

A: I don't think there is a library already written for this, but you could perhaps use the sftp client via a child process.


text:
Q: How is the integers modulo p a finite field. Let's a assume we have integers Z := {..-3,-2,-1,0,1,2,3..}, if this is modded by p, how does it satisfy the inverse axiom of a field? Assume p is 3
:. p = {0,1,2}
The identity 0,1 and exist for both operations but the field lacks an inverse for both operations, how is this still a field?

A: Note that in mod (3) we have $2+1=0$ thus $2$and $1$ are additive inverse of each other.
Also $2*2=1$
Thus $2$ is its own multiplicative inverse.
Similarly you can check out other elements for field properties.

A: An inverse exists because it's modulo $3$, so going past $2$ takes you back to $0$.
$2+1$mod$3 = 3$mod$3=0$
$2\times2$mod$3 = 4$mod$3=1$
Similarly for $1$ and $0$.

A: " but the field lacks an inverse for both operations"
quite the opposite!
It is because $p $ is prime that we are assured every element does have multiplicative inverses.
You seem to forget that when "modded" the all the $kp+j $ are all consider the same as $j$.  So $2+1=3=3+0\equiv 0$ so $1$ and $2$ are additive inverses.  And $2*2=4=3+1\equiv 1$ so $2$ is its own multiplicative inverse.
In general.  For $k $, the $p-k $ is the additive inverse (because $k +(p-k)=p+0\equiv 0 \mod p$.
And because $p$ is prime, then for any $k\not \equiv 0\mod p$  there exist $a,b $ so that $ak +bp=1$ (Bezout's lemma).  Thus $a $ is the multiplicative inverse of $k $ (because $ka=1-bp\equiv 0\mod p $)
===
Example:  take $p=7$
The $1*1+0*7=1$
$2*4-1*7=1$
$3*5-2*7=1$
$4*2-1*7=1$
$5*3-2*7=1$
$6*6-5*7=1$
So in $\mod 7$ the multiplicative inverses of $1,2,3,4,5,6$ are respectively $1,4,5,2,3,6$.
And the additive inverses are $6,5,4,3,2,1$ respectively.


text:
Q: Update the Value of a Per-Session Custom Dimension Once Set? I'm a writing a proof of concept involving GA Core Reporting API integration and would like to know if it's possible, after creation via:
ga('create', 'UA-XXXXXX-X');
ga('send', 'pageview', {
    'dimension1': '[Uid]'
    'dimension2': ''
});

... to retrieve a page view by its unique identifier (which could be another dimension, as above) and update another of the dimensions. For example, decisioning data obtained at a later date.

A: I don't think so. It 's not possible in realtime because the realtime API does not expose custom dimensions, and it's probably not possible via data imports (at least in the standard version of GA) because data imports do not change data retroactively (I think Premium has now a feature to apply data retroactively, but I'm not at all sure those data sets can be retrieved via the API. I haven't tested that, though, so maybe someone with more experience can weigh in).
Plus you are talking about a session based dimension. A session based dimension cannot identify a single page, since it belongs to a session. You'd need a hit based dimension to uniquely identify a page (actually you have one by default since Urls should be unique).


text:
Q: Is sound relative? Is sound relative?
For example, if I and my friend are having a ride at 1000 mph and I shout towards him (speed of sound 700 mph). What would happen? Will the speed of the sound relative to the ground be 1700 mph? Or will it be something else? Why?

A: The speed of sound is a property of the medium(air). So speed of sound is fixed with respect to the medium. As the medium is at rest with respect to the ground(assuming no wind), the speed of sound w.r.t ground will stay 700 mph.
If there is wind, you vectorialy add velocity of the wind and velocity of sound relative to air to get the velocity of sound w.r.t ground.


text:
Q: How to make linenumber referencing in lstlisting work with autoref This Link provides an answer to the question how to make line-number referencing work with lstlisting. However, if I use \autoref it will only return the number and not something like Line 31.

A: The \autoref command can't 'know' the ref name for each counter, this has to be provided as a separate macro:
I used the listings example by Marco Daniel provided in the Link by the O.P. and found that listings uses lstnumber as counter, so
\newcommand{\lstnumberautorefname}{Line}

is the relevant macro name to be defined (i.e. counter name + autorefname as suffix.
'Only' the standard counters such as chapter, etc, figure, page, table etc. are predefined. For a full list see the hyperref manual. Other packages might define additional \...autorefname macros.
Please have a look on the cleveref package too.
\documentclass{article}

\usepackage{listings}
\usepackage{hyperref}

\newcommand{\lstnumberautorefname}{Line}

\begin{document}

\lstset{escapeinside={(*@}{@*)}}
\begin{lstlisting}
 for i:=maxint to 0 do begin
   { comment }(*@\label{comment}@*)
 end;
\end{lstlisting}
\autoref{comment} shows a comment.

\end{document}


text:
Q: Can't get the token in identity server3 I'm new in identity server3.
I can access to my token in other projects but i just can't get it in my identity project.
Here is my client class
new Client
{
    Enabled = true,
    ClientName = "Web Application1",
    ClientId = "WebApplication1",
    Flow = Flows.Implicit,
    RequireConsent = false,
    AllowRememberConsent = true,
    RedirectUris = new List<string>
    {
        "http://localhost:52249/"
    },
    PostLogoutRedirectUris = new List<string>
    {
        "http://localhost:52249/"
    },
    IdentityTokenLifetime = 360,
    AccessTokenLifetime = 3600,
    AllowedScopes = new List<string>() { "openid", "profile" , "roles", "WebAPI" }
},
new Client
{
    Enabled = true,
    ClientName = "Identity 2",
    ClientId = "Identity",
    Flow = Flows.Implicit,
    RequireConsent = false,
    AllowRememberConsent = true,
    RedirectUris = new List<string>
    {
        "https://localhost:44396/"
    },
    PostLogoutRedirectUris = new List<string>
    {
        "https://localhost:44396/"
    },
    IdentityTokenLifetime = 360,
    AccessTokenLifetime = 3600,
    AllowedScopes = new List<string>() { "openid", "profile" , "roles", "WebAPI" }
},

and my scopes class:
var scopes = new List<Scope>
{
    new Scope
    {
        Enabled = true,
        Name = "roles",
        Type = ScopeType.Identity,
        Claims = new List<ScopeClaim>
        {
            new ScopeClaim("role")
        }
    },
    new Scope
    {
        Enabled = true,
        DisplayName = "WebAPI",
        Name = "WebAPI",
        Description = "Secure WebAPI",
        Type = ScopeType.Resource,
        Claims = new List<ScopeClaim>
        {
            new ScopeClaim(Constants.ClaimTypes.Name),
            new ScopeClaim(Constants.ClaimTypes.Role),
        }
    }};

    scopes.AddRange(StandardScopes.All);
    return scopes;
}}

and user class:
IdentityContext db = new IdentityContext();
var AllUsers = db.Users.ToList();
List<InMemoryUser> UsersList = new List<InMemoryUser>();
foreach (var item in AllUsers)
{
    InMemoryUser UserInMemory = new InMemoryUser();
    UserInMemory.Username = item.UserName;
    UserInMemory.Password = item.Password;
    UserInMemory.Subject = item.Id.ToString();
    UserInMemory.Claims = new Claim[]
    {
        new Claim(Constants.ClaimTypes.PreferredUserName, item.UserName),
    };
}
return UsersList;

and my startup class in my identity project:
public void Configuration(IAppBuilder app)
{
    app.Map("/identity", idsrvApp =>
    {
        var factory =
            new IdentityServerServiceFactory().UseInMemoryClients(Clients.Get())
                                              .UseInMemoryScopes(Scopes.Get())
                                              .UseInMemoryUsers(Users.Get());

        var userService = new UserService();

        factory.UserService = new Registration<IUserService>(reslove => userService);
        var viewOptions = new DefaultViewServiceOptions();
        //viewOptions.Stylesheets.Add("/Content/Site.css");
        viewOptions.Stylesheets.Add("/Content/bootstrap-rtl.css");
        viewOptions.CacheViews = false;
        factory.ConfigureDefaultViewService(viewOptions);
        var options = new IdentityServerOptions
        {
            SiteName = "IdentityServer3 - Configuring DefaultViewService",

            SigningCertificate = LoadCertificate(),
            Factory = factory,

            AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
            {
                //   IdentityProviders = ConfigureAdditionalIdentityProviders,
            }
        };

        idsrvApp.UseIdentityServer(options);
    });

    Serilog.Log.Logger =
        new LoggerConfiguration().MinimumLevel.Debug()
            .WriteTo.RollingFile(pathFormat: @"c:\logs\IdSvrAdmin-{Date}.log")
            .CreateLogger();
    }

    X509Certificate2 LoadCertificate()
    {
        return new X509Certificate2(
            $"{AppDomain.CurrentDomain.BaseDirectory}\\bin\\idsrv3test.pfx", "idsrv3test");
    }

Please help me.
Thanks.!

A: I think this helpful and you can get an idea to solve this problem.
public HttpRequestWrapper TokenizeRequest(User user, string clientid)
{
    var token = GetToken(user, clientid).Result;
    _request.AddHeader("Authorization", $"Bearer {token.AccessToken}");
    return this;
}

private async Task<TokenResponse> GetToken(User user, string clientid)
{
    var client = new TokenClient(Constants.TokenEndpoint, clientid, SecretApi);

    return  client.RequestResourceOwnerPasswordAsync
           (user.UserName, user.Password, "WebAPI").Result;
}

Reference :
https://www.codeproject.com/Articles/1163131/IdentityServer-WebAPI-MVC-ASP-NET-Identity-Specflo


text:
Q: Correct /etc/hosts configuration in ubuntu 18.04 Hello i want to have three virtual severs in my localhost Virtual machine Ubbuntu 18.04.
Id like one localhost -> /var/www/html
one onlyoffice.eduardo.com -> /var/www/onlyoffice ( document server)
another one to nextcloud.eduardo.com -> /usr/share/nginx/nextcloud16
1 - Which etc/hosts would be better:
127.0.0.1 localhost
127.0.0.1 onlyoffice.eduardo.com
127.0.0.1 nextcloud.eduardo.com

or all in the same line
127.0.0.1 localhost onlyoffice.eduardo.com nextcloud.eduardo.com

I suppose that it would look for the name in order when i put http://onlyoffice.eduardo.com for example....
2 - Would it better to have different ips:
127.0.0.1 localhost
127.0.0.2 onlyoffice.eduardo.com
127.0.0.3 nextcloud.eduardo.com

Any other files should i touch ?
The general idea is to have the nextcloud, document server ( onlyoffice) in same place. Id alsolike to connect nextcloud onlyoffice app to http://onlyoffice.eduardo.com
So id have to conf somehow in sites-avalaible and sites-enabled..
Id prefer to use nginx instead of apache.
Thanks
My work so far: https://drive.google.com/open?id=1I2ZiRUKqmm8u5U5TsqyoOKUvfTwY-SPA
Thanks in advance

A: The reason to configure the various hostnames to /etc/hosts is to allow the local web browser (client) to know which IP address to connect to reach the respective hostname, nothing else.
If you configure the web server to bind each virtual host to a different 127.0.0.* IP address, then you must also use associate the hostnames with the respective IP addresses. Otherwise the client won't be able to connect to the right virtual host. This would be IP-based virtual hosting.
But the webserver won't need /etc/hosts at all, since it will be able to look at the headers of the HTTP request and see which hostname was actually used in the request. Even using just one port and one IP address, it will be able to present different content according to the hostname used in the request, if configured to do so. This is known as name-based virtual hosting.
Both Apache and nginx will be able to handle either method; it's just a matter of deciding which one to use. The name-based method will require less IP addresses, which makes it the most widely-used one in public webservers, since static IP addresses are a limited resource.

In /etc/hosts, the "all names in the same line" makes it unambiguous that the first listed name is the primary one and the rest are aliases - sort of similar to using the CNAME records in DNS. If a client does both a forward and a reverse lookup, e.g. for HTTPS certificate verification purposes, this format is the most likely to pass the reverse lookup check without causing security warnings.
If you use "multiple lines with the same IP address" in /etc/hosts, and perform a reverse lookup, only the first line with the matching IP will be returned.
In Linux, the nslookup command will often explicitly query DNS only. To test the complete hostname resolution process just like an application would do, you should use getent hosts <hostname-or-IP-address>. With this command, you can verify the effect of different /etc/hosts configurations for yourself.

In StackExchange, the standard process would be one question per question post. Based on the title and the majority of contents of your post, this question was about /etc/hosts. If you need help on configuring your webserver, you should post another question for that, rather than attempt to stretch this one into an extended discussion.


text:
Q: How to get the word result from audio using Sphinx I try to use the following code to get the word result from the audio using Sphinx, however it can not get the word result, may someone help it?
Here is the wav audio: http://download.wavetlan.com/SVV/Media/HTTP/OtherWAV2.wav
 Configuration configuration = new Configuration();

// Set path to acoustic model.
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
// Set path to dictionary.
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
// Set language model.
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.bin");

StreamSpeechRecognizer recognizer;
try {
    recognizer = new StreamSpeechRecognizer(configuration);

    recognizer.startRecognition(new FileInputStream("1.wav"));
    SpeechResult result = recognizer.getResult();
    recognizer.stopRecognition();

    // Print utterance string without filler words.
    System.out.println(result.getHypothesis());

    System.out.println("================word result=============="+result.getWords().size());
    // Get individual words and their times.
    for (WordResult r : result.getWords()) {
        System.out.println(r);
    }
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Below is the output for the result:
19:12:30.264 INFO lexTreeLinguist      Max CI Units 43
19:12:30.264 INFO lexTreeLinguist      Unit table size 79507
19:12:30.273 INFO speedTracker         # ----------------------------- Timers----------------------------------------
19:12:30.273 INFO speedTracker         # Name               Count   CurTime   MinTime   MaxTime   AvgTime   TotTime
19:12:30.273 INFO speedTracker         Compile              1       1.4020s   1.4020s   1.4020s   1.4020s   1.4020s
19:12:30.273 INFO speedTracker         Load LM              1       0.6420s   0.6420s   0.6420s   0.6420s   0.6420s
19:12:30.273 INFO speedTracker         Load Dictionary      1       0.0880s   0.0880s   0.0880s   0.0880s   0.0880s
19:12:30.273 INFO speedTracker         Load AM              1       1.7740s   1.7740s   1.7740s   1.7740s   1.7740s
19:12:30.294 INFO speedTracker            This  Time Audio: 1.38s  Proc: 0.01s  Speed: 0.00 X real time
19:12:30.295 INFO speedTracker            Total Time Audio: 1.38s  Proc: 0.01s 0.00 X real time
19:12:30.295 INFO memoryTracker           Mem  Total: 840.50 Mb  Free: 584.33 Mb
19:12:30.295 INFO memoryTracker           Used: This: 256.17 Mb  Avg: 256.17 Mb  Max: 256.17 Mb
19:12:30.295 INFO trieNgramModel       LM Cache Size: 0 Hits: 0 Misses: 0
19:12:30.314 INFO speedTracker         # ----------------------------- Timers----------------------------------------
19:12:30.314 INFO speedTracker         # Name               Count   CurTime   MinTime   MaxTime   AvgTime   TotTime
19:12:30.314 INFO speedTracker         Compile              1       1.4020s   1.4020s   1.4020s   1.4020s   1.4020s
19:12:30.314 INFO speedTracker         Load LM              1       0.6420s   0.6420s   0.6420s   0.6420s   0.6420s
19:12:30.314 INFO speedTracker         Load Dictionary      1       0.0880s   0.0880s   0.0880s   0.0880s   0.0880s
19:12:30.314 INFO speedTracker         Score                2       0.0000s   0.0000s   0.0080s   0.0040s   0.0080s
19:12:30.315 INFO speedTracker         Prune                5       0.0000s   0.0000s   0.0000s   0.0000s   0.0000s
19:12:30.315 INFO speedTracker         Grow                 7       0.0000s   0.0000s   0.0040s   0.0007s   0.0050s
19:12:30.315 INFO speedTracker         Frontend             2       0.0000s   0.0000s   0.0080s   0.0040s   0.0080s
19:12:30.315 INFO speedTracker         Load AM              1       1.7740s   1.7740s   1.7740s   1.7740s   1.7740s
19:12:30.315 INFO speedTracker            Total Time Audio: 1.38s  Proc: 0.01s 0.00 X real time
19:12:30.315 INFO memoryTracker           Mem  Total: 840.50 Mb  Free: 584.33 Mb
19:12:30.315 INFO memoryTracker           Used: This: 256.17 Mb  Avg: 256.17 Mb  Max: 256.17 Mb

================word result==============0

A: The audio must have the following format:
RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 16000 Hz

You audio has this format:
RIFF (little-endian) data, WAVE audio, Microsoft PCM, 8 bit, mono 11025 Hz

It can not be decoded with default model. This audio can not be converted to a proper format as well because it has frequency less than 16000 Hz and it is just 8 bits instead of 16 bits. You need to make sure that you convert original audio into proper format before decoding.


text:
Q: How to list branches that contain a given commit? How can I query git to find out which branches contain a given commit? gitk will usually list the branches, unless there are too many, in which case it just says "many (38)" or something like that. I need to know the full list, or at least whether certain branches contain the commit.

A: The answer for git branch -r --contains <commit> works well for normal remote branches, but if the commit is only in the hidden head namespace that GitHub creates for PRs, you'll need a few more steps.
Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r doesn't know about PR #42 because refs like refs/pull/42/head aren't listed as a remote branch by default.
In .git/config for the [remote "origin"] section add a new line:
fetch = +refs/pull/*/head:refs/remotes/origin/pr/*

(This gist has more context.)
Then when you git fetch you'll get all the PR branches, and when you run git branch -r --contains <commit> you'll see origin/pr/42 contains the commit.

A: You may run:
git log <SHA1>..HEAD --ancestry-path --merges

From comment of last commit in the output you may find original branch name
Example:
       c---e---g--- feature
      /         \
-a---b---d---f---h---j--- master

git log e..master --ancestry-path --merges

commit h
Merge: g f
Author: Eugen Konkov <>
Date:   Sat Oct 1 00:54:18 2016 +0300

    Merge branch 'feature' into master

A: From the git-branch manual page:
 git branch --contains <commit>

Only list branches which contain the specified commit (HEAD if not specified). Implies --list.

 git branch -r --contains <commit>

Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".

As noted by Carl Walsh, this applies only to the default refspec
fetch = +refs/heads/*:refs/remotes/origin/*

If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:
git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>

See also this git ready article.

The --contains tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you've got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.

$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <nick@quaran.to>
Date:   Wed Apr 1 20:38:59 2009 -0400

    Green all around, finally.

$ git branch --contains d590f2
  tests
* master

Note: if the commit is on a remote tracking branch, add the -a option.
(as MichielB comments below)
git branch -a --contains <commit>

MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry:

Because git cherry compares the changeset rather than the commit id (sha1), you can use git cherry to find out if a commit you made locally has been applied <upstream> under a different commit id.
For example, this will happen if you're feeding patches <upstream> via email rather than pushing or pulling commits directly.

           __*__*__*__*__> <upstream>
          /
fork-point
          \__+__+__-__+__+__-__+__> <head>

(Here, the commits marked '-' wouldn't show up with git cherry, meaning they are already present in <upstream>.)


text:
Q: Forest plot using risk ratio and confidence intervals How to make forest plot like this using risk ratio and confidence intervals with the comparison labels?
I don't want R to automatically group the comparison, I just want to plot the forest plot with the labels at the left hand side. Thank you.
I use this code:
d=result
df=data.frame(d)

cochrane_from_rmeta <-
  structure(list(
    mean  = df$RiskRatio,
    lower = df$LowerLimit,
    upper = df$UpperLimit),
    .Names = c("RiskRatio", "lower", "upper"),
    row.names = c(NA, -14L),
    class = "data.frame")

tabletext<-cbind(
  c(df$Outcomes),
  c(df$Comparison),
  c(df$...4),
  c(df$RiskRatio))

forestplot(tabletext,
           cochrane_from_rmeta,new_page = TRUE,
           is.summary=c(TRUE,TRUE,rep(FALSE,8),TRUE),
           clip=c(0.1,2.5),
           xlog=TRUE,
           col=fpColors(box="royalblue",line="darkblue", summary="royalblue"))

but it shows error

A: Is this what you're trying to achieve?
#install.packages("forestplot")
library(forestplot)
# Cochrane data from the 'rmeta'-package
cochrane_from_rmeta <-
  structure(list(
    mean  = c(NA, NA, 0.578, 0.165, 0.246, 0.700, 0.348, 0.139, 1.017, NA, 0.531),
    lower = c(NA, NA, 0.372, 0.018, 0.072, 0.333, 0.083, 0.016, 0.365, NA, 0.386),
    upper = c(NA, NA, 0.898, 1.517, 0.833, 1.474, 1.455, 1.209, 2.831, NA, 0.731)),
    .Names = c("mean", "lower", "upper"),
    row.names = c(NA, -11L),
    class = "data.frame")

tabletext<-cbind(
  c("", "Study", "Auckland", "Block",
    "Doran", "Gamsu", "Morrison", "Papageorgiou",
    "Tauesch", NA, "Summary"),
  c("",
    "Comparison",
    "Placebo 1",
    "Placebo 2",
    "Placebo 3",
    "Placebo 4",
    "Placebo 5",
    "Treatment 1",
    "Treatment 2",
    NA,
    ""),
  c("",
    "Relative Risk \n 95% CI",
    "0.88 (0.84-0.92)",
    "0.87 (0.81-0.94)",
    "0.88 (0.84-0.92)",
    "0.87 (0.81-0.94)",
    "0.88 (0.84-0.92)",
    "0.88 (0.84-0.92)",
    "0.87 (0.81-0.94)",
    NA,
    "0.87 (0.81-0.94)"),
  c("", "OR", "0.58", "0.16",
    "0.25", "0.70", "0.35", "0.14",
    "1.02", NA, "0.53"),
  c("", "F", "1.1", "1.3",
    "0.2", "5", "3.1", "0",
    "0.1", NA, "4.1"))

forestplot(tabletext,
           cochrane_from_rmeta,
           graph.pos = 3,
           new_page = TRUE,
           is.summary=c(rep(FALSE,11)),
           clip=c(0.1,2.5),
           xlog=TRUE,
           col=fpColors(box="royalblue",
                        line="darkblue",
                        summary="royalblue"))


text:
Q: segmentation fault with accept() on linux I have a problem with a client/server programm on linux.
I wrote a server programm wich is sending data cyclic to one conneted client.
Now I want to detect, if the client close the connection to the server. When the connection is closed from the client, i want to wait with accept(...) for an new connection.
Here the critical parts of my code:
error = send(client_sock, Zeichen, 1, MSG_NOSIGNAL);
if(error < 0)
{
    connected = 0;
    printf("Error, write on TCP Socket failed!!! Reconnecting... \r\n");
    close(serverSocket);
    initServer();
}

int initServer(void)
{
    int *new_sock;
    socklen_t size;
    struct sockaddr_in server, client;

    serverSocket = socket(AF_INET , SOCK_STREAM , 0);       //Create socket
    if (serverSocket == -1)
    {
      printf("Could not create socket \r\n");
      return 0;
    }else
    {
      printf("Socket created \r\n");
    }

    server.sin_addr.s_addr = inet_addr(IPAdresse);
    server.sin_family = AF_INET;
    server.sin_port = htons(TCPPort);

    if(bind(serverSocket,(struct sockaddr *)&server , sizeof(server)) < 0)
    {
      printf("bind failed. Error \r\n");
      return 0;
    }else
    {
      printf("bind done \r\n");
    }

    listen(serverSocket, 1);
    printf("Waiting for incoming connections... \r\n");
    size = sizeof(sockaddr_in);
    printf("size of sockaddr_in: %i \r\n", size);
    client_sock = accept(serverSocket, (struct sockaddr *)&client, &size);

   if (client_sock < 0)
   {
     printf("accept failed \r\n");
     return 0;
   }else
   {
    connected = 1;
    return 1;
   }
}

The first time it works fine, I can connect and can send data over the socket. When the client close the connection the error is detected, I close the socket an start the server again to wait for a new connection. But than I get a segmentation fault when I do the accept(..) for the second time!!!
Can someone help me please!!! Thanks a lot!

A: It's not clear what you're doing when the client connection closes.  I see no loop in your code, and yet you're suggesting that accept() is called more than once.
Without seeing the rest or the code, I can only speculate that:

*

*you're repeatedly calling initServer(), hence attempting to recreate the same server socket over and over (which, of course, would be bad),

or

*

*you're calling accept() again somewhere else in your code, most likely with corrupt arguments.

At the very least, what your server-side code should do is initialize the server socket once, then loop around accept(), like so:

*

*call socket() once

*call bind() once

*call listen() once

*then in a loop:

*

*call accept(), this call will block until a client connects, and then return a connected socket,

*do whatever you need to do with that (connected client) socket

*resume with the loop


text:
Q: what is the difference between the keywords default and new below is a  sample class,
public class Loan
{
}

now, what is difference between these below 2 line and what is difference between them?
Loan loan = default(Loan);
Loan loan = new Loan();

Is there preference to use one over other?

A: For value types (i.e. structs), default(T) and new T() are effectively the same: they both return an uninitialized instance of T. For reference types, however, default(T) returns null, while new T() returns a new instance of T, initialized with the default constructor.
In your code, Loan is a class, so default(Loan) returns null.

A: default would return the default value for value types and null for reference type.
If your Load is a class, first line would return null, whereas second line would return a new instance of Loan
Loan loan = default(Loan); // null if Loan is a reference type
Loan loan = new Loan(); // new instance of Loan - Not Null

If Loan is a struct (or a value type) then both of the above (default and new) would be same.

A: default is used for zeroing out values. For reference types, thats null. For value types, that is effectively the same as using new without any arguments. default is great for generics.
new creates an instance of that type, invoking the constructor.
In your example, if I do:
Loan loan = default(Loan);

or in newer versions of C#:
Loan loan = default;

which is logically equivalent to
Loan loan = null;

you will get a null reference exception if you don't construct it:
loan.MakePayment(100); // Throws

A: In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance:
Whether T will be a reference type or a value type.

If T is a value type, whether it will be a numeric value or a struct.

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable, which is initialized like any struct.
In C#, the new keyword can be used as an operator, a modifier, or a constraint.
new Operator
Used to create objects and invoke constructors.

new Modifier
Used to hide an inherited member from a base class member.

new Constraint
Used to restrict types that might be used as arguments for a type parameter in a generic declaration.


text:
Q: How to scale down a responsive website? This might be an odd question, considering our website is fully responsive and shouldn't need to be scaled down.
Although, the client consider that since his main website is stuck on a 980px max-width, his other websites should be too.
In short, want should I do to scale down the website if the screen is bigger than 980px right to that resolution ?
To add further details, we used media-queries to make the website responsive on mobile, tablet and desktop. The thing is that 980px falls in the tablet res, and the client wants it in desktop res.

A: You may need to nigotiate with the client but you can add a div with the class wrapper or content wrap all the page content & set that to max-width:980px; but for bigger devices make it max-width:1180px; then give the body background either a complimentary color or image with slight blur effect possibly. Once the screen size is less then 980px make the width 100%.


text:
Q: A weird problem with command printf I am using Simple Scalar toolset to run some simulations on cache associativity. And I am seeing some strangest behavior with printf function. Here is the code snippet:
printf(" Name: %s %d %d %d \n", name, nsets, cp->set_shift, cp->set_mask);
printf(" Name: %s %d %d %d \n", name, cp->set_mask, nsets, cp->set_shift);

The printf lines are one after another, no other code in between. And here is the output:
 Name: dl1 128 5 127
 Name: dl1 127 0 128

The output of second printf is wrong. The output of the second printf should be :
Name: dl1 127 128 5

Changing the relative order of printf statements does not change the output. What part of printf I am missing to understand??
With regards
Newbie

A: Go look at the variable declarations. My guess is somebody is a short or long, not an int. Since printf can't check what you pass for validity, it decides how many bites to grab from the stack based on the % signs. If your args don't agree with the format, not a compile error, but garbage can come out.

A: I'd guess you have a mis-match between the type you're passing and the type you're telling print that you're passing. Specifically, it looks like cp->set_mask is some type larger than int. Since you've told printf that it's an int, it's taking the first sizeof(int) bytes as the first int, and then the next sizeof(int) bytes as if it were nsets (and since you're apparently on a little-endian machine, those bytes all contain 0). Note, in particular, that after the 0 comes the 128 that the first prints says is the value of nsets.


text:
Q: Pass a list from a view to a controller, MVC 5 So, I'm using MVC, and I'm trying to create a new employee using entity.  Along with creating the employee, I am trying to create a list of items that are tied to the employee (one to many).
So my issue is, I am calling a javascript function in the onclick event of the submit button.
This javascript function creates a list of IDs, I need these to create the items.
How can I get this list of IDs to my controller, so I can create them?

            <input type="submit" value="Create" class="btn btn-default" onclick="getResult()"/>

A: Add an empty hidden input to the form element in your view, let's call it idslist
@Html.Hidden("idslist")

put your ids in that input using javascript JSON.stringify or simply an id list separated by a separator.
And now you can read that list on your controller, when the user submits the form :
public ActionResult Create(myModel x, string idslist)
{
    // now you have to deserialize your idslist
    // using JsonConvert.DeserializeObject or just split for the second case.
}


text:
Q: Launch notepad.exe from a PHP file In an attempt to simplify a problem I am having running a batch file from within PHP on a WAMP windows XP system I am trying to launch notepad.exe from a PHP file.  I have a PHP file containing....
<?php
exec('c:\windows\notepad.exe');
?>

When I run the PHP file I can see the notepad.exe process start in the task manager but notepad itself does not open.  What am I doing wrong?

A: What you are trying to do is not the correct way, a notepad application is not a process to perform operations in background. But if you want to execute a command which will take time than by following way you can run external program in background. Means PHP will not wait for the external program termination.
$cmd = "somecommand";
if (substr(php_uname(), 0, 7) == "Windows"){
    pclose(popen("start /B ". $cmd, "r"));
}
else {
    exec($cmd . " > /dev/null &");
}

Hope this will help you.

A: If you want notepad to run interactively you can use PSEXEC.
You can run a batch file from PHP with the exec command and psexec has the ability to run application interactively from within your batch file.


text:
Q: How to parse "let there be light," "may grace and peace be multiplied to you," etc Working on a natural language parser and I realized I don't have much a firm handle on how to come at sentences such as the following:
"And God said, Let there be light: and there was light" (Genesis 1:3 KJV).
"May grace and peace be multiplied to you" (1 Peter 1:2 HCSB).
These both seem to convey some sense of desiring something to be [done], so I don't think "let" or "may" can quite qualify as auxiliaries.  Any thoughts?

A: To let in "Let there be light." is used to make a third party imperative sentence. It can be rephrased to

I command (order) that there should be light.

It doesn't convey a sense of desiring something, rather ordering something to happen. In other words, it is not desired that there should be light, but there must be light because God says so.
If you contrast "Ask him to carry the bag." with "Let him carry the bag", the former indicates a request, but the latter a command that he should carry the bag.
May is one of the modal verbs in English and it could be used in a optative sentence with which you can express a wish. Your example is in the optative mood which is:

a grammatical mood that indicates a wish or hope. It is similar to
  the cohortative mood, and is closely related to the subjunctive mood... One uses the modal verb may, e.g. May you have a long life! Another uses the phrase if only with a verb in the past or past subjunctive, e.g. If only I were rich! Another uses the present subjunctive, e.g. God save the Queen!

[Wikipedia]

A: Those are imperative statements. The popular way to describe them is that there is an implied "You" or "You shall" at the front of it (but that doesn't really work for the second sentence).
To be a little more specific, they are both third-person imperative, as the entity being ordered around in this case isn't necessarily a direct part of the conversation.
Note that the King James Bible, while it has many fine qualities, isn't written in what I would call modern conversational English. So you might not want to use it as a source for a "natural language" parser.


text:
Q: Is a cylinder a differentiable manifold? First of all! I mean a cylinder with a circle at the top and a circle at the bottom. Not the volume but its surface.
Intuition tells me YES. But...
How can charts be defined for the points on the edge?
What I thought first is that since a sphere is a differentiable manifold and I could find a bijection projecting the cylinder on a sphere placed in its center (of symmetry) I could extend the properties of the sphere to the cylinder.
Now some doubts arise since the metric that I would define on the cylinder would be spherical, while I would expect to get standard euclidean geometry on the flat surfaces.
Anyway, no metric is yet defined on differentiable manifolds and I can imagine to define the metric that best fits after. So

*

*Wthout a metric, does the differential manifold structure allows me to distinguish between a cylinder and a sphere?

*With a metric can I be sure whether my manifold is a cylinder or a sphere or anything else?

*Where can I get a handy summary on the structure information given by topology, manifold, and metric when I only know some of the three?
thank you in advance

A: If you want your cylinder to have an "edge" then intuitively, it should not be a differentiable manifold. If you take a point in a differentiable manifold, then there is a regularly parametrized curve through the point in each direction. (Just take a straight line in a chart in transport it onto the manifold.) This means that you can "pass through that point" in each direction on a smooth curve with non-zero velocity. If you apply this to a point on the edge, this means that you can get from the side of cylinder to the top of the cylinder by a smooth curve whose speed is non-vanishing at each point. But obviously this should not be possible at the edge, since the speed would have to jump from having non-zero vertical component to being horizontal. (What I am trying to explain in a non-technical way here is that the cylinder has no well defined tangent plane at points of the edge.)
The problem with a formal answer to your question is that in order to get a formal answer, you would first have to specify what it means to "make the cylinder into a manifold". As you said, you can choose a bijection to a sphere (which even is a homeomorphism) and use this to carry the manifold structure over to the cylinder. But in this way, you have "removed" or "flattened out" the edge. Certainly, the cylinder is not a submanifold in $\mathbb R^3$, which can be seen by making the above argument with tangent spaces precise.

A: Assume the cylinder is not solid and does not have a top or a bottom then yes. Its a differentiable manifold. This cylinder in $\mathbb{R}^3$ could be defined by $\{x \in \mathbb{R}^3 \mid x_1^2 + x_2^2 = R^2 \text{ and } |x_3|\leq C\}$.
Now this cylinder is different from a sphere by the curvature: the curvature on a sphere is everywhere and in every direction the same. The curvature on the cylinder differs. Its $1$ if you go parallel to the $xy$-plane, its $0$ parallel to the $z$-axis. In general curvature is a good way to differentiate manifolds "by themselves".
Edit/Added:
Finding a bijection between two manifolds does not make them equivalent, the sphere is not equivalent to the cylinder just because you can relate them 1-to-1.
The problem with a top/bottom is that you will have a kink on the edges. At those kinks the manifold is not differentiable, just like $|x|$ is not differentiable at $0$.


text:
Q: MYSQL "Got an error reading communication packets" The setup is a Windows 2003 Server with MySQL 5.0.45 (it is an old-ish box!)
We've recently started getting warnings in the Application Event Log that say: Aborted connection xxxxx ti db: 'dbname' user: 'dbuser' host: localhost' (Got an error reading communication packets)
How do I go about identifying the cause of this? This is a live system - are the users getting an error message and if so what would it be?
Any help greatly appreciated!

A: Would you believe I addressed this kind of question back on Jun 12, 2012 ?
See my post in the DBA StackExchange on why.
WHAT YOU CAN DO NOW
Try raising the max_allowed_packet to a much larger number, since the default is 1M. I would suggest about 10 times the largest TEXT or BLOB field you have in your current dataset.
To set the max_allowed_packet to 256M, you can add it to /etc/my.cnf or my.ini
[mysqld]
max_allowed_packet=256M

to cover future restarts of mysqld. To install the value now on the server, please run this:
SET GLOBAL max_allowed_packet = 1024 * 1024 * 256;

Give it a Try !!!


text:
Q: Does the Akka autopilot respond to messages that have already been sent When using the Akka AutoPilot, will it handle messages that were already sent to the test probe?
In particular, should I expect this code to pass?
new JavaTestKitDsl(...) {{
  TestProbe probe = new TestProbe(...);
  probe.testActor().tell("Hello", getRef());
  // Be certain that the message has been queued
  Thread.sleep(1000);
  probe.setAutoPilot(new TestActor.AutoPilot() {
    public TestActor.AutoPilot run(ActorRef sender, Object msg) {
      sender.tell(msg, null);
      return noAutoPilot();
    }
  });
  expectMsg("Hello");
}};

It seems that it fails as written, but passes if I move the setAutoPilot to before I send the message.
In the real system, the test is much more complicated, and I get to a point where three actors send different messages to the probe at the roughly the same time.  I had intended to set the auto pilot at that point, so that it was clear where I was expecting the messages to arrive, but it appears that I need to set up the autopilot before I send the messages that trigger the other actors.
The documentation does not say anything about this that I could find.
This is running with Akka 2.5.18 and Java 10 if that matters.


text:
Q: stsadm -o. What does the -o mean? I am working on a large SharePoint farm, mainly with the backend SQL Servers. We have always used stsadm -o for all stsadm functions, but no one seems to know why. I can't seem to find the info specific for stsadm, would it be general Windows command-line sytax?

A: The -o is short for -operation.  It basically specifies the operation of the command.
http://technet.microsoft.com/en-us/library/cc261956.aspx

A: actually -o[peration] operationname distinguishes actual commands from -help operationname requests


text:
Q: Difference between two dates not working properly? I am trying to find if selected date and today's date difference is equal to or greater than 18 years or not.
For getting today's date following is my code
private val simpleDateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault())
    private val date = Date()
    private val todayDate = simpleDateFormat.parse(simpleDateFormat.format(date)).time
private val cal = Calendar.getInstance()

 cal.time = date
 val date = simpleDateFormat.parse("12-11-2001").time
val years = (todayDate - date) / (1000L * 60 * 60 * 24 * cal.getActualMaximum(Calendar.DAY_OF_YEAR))

Now my selected date is 12-11-2001 and todays date is 11-11-2019 so it should show 17 years but it show 18 years. Even if I select 13,14 or 15th November 2001, it shows 18 years instead of 17 years but if I select 16th Novemeber 2001 then it shows 17 years. I am not able to understand why this behaviour happen.

A: Better to use java.time API for this kind of tasks:
import java.time.*
import java.time.format.*
import java.time.temporal.ChronoUnit

fun main() {
    val today = LocalDate.now()
    val date = LocalDate.parse("12-11-2001", DateTimeFormatter.ofPattern("dd-MM-yyyy"))

    val diff = ChronoUnit.YEARS.between(date, today)

    println("Diff between $date and $today is $diff years")
}

If you can't use java.time yet due to minSdkVersion restriction, you can use ThreeTen Backport project and its Android adaptation ThreeTenABP.

A: *

*Try this might help you .
context  = YourActivity.this;
btn_datePicker = findViewById(R.id.btn_datePicker);

Calendar calendar = Calendar.getInstance();
final int day = calendar.get(Calendar.DAY_OF_MONTH);
final int month = calendar.get(Calendar.MONTH);
final int year = calendar.get(Calendar.YEAR);

btn_datePicker.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        datePicker = new DatePickerDialog(context, new   DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {

                if (i > year - 18 && i1 + 1 > month - (12 * 18)) {

                    Toast.makeText(context, "Select Proper birth date", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(context, ""+i2 + "/" + (i1 + 1) + "/" + i, Toast.LENGTH_SHORT).show();
                }

            }
        }, year, month, day);
        datePicker.show();
    }
});

A: Here is the Proper Solution to get number of years between two dates (Difference between Two dates).
Add this code in onCreate Method.
var d1: Date? = null
var d2: Date? = null
val dateStart = "12-11-2001"
val dateStop = "11-11-2019"
val format = SimpleDateFormat("dd-MM-yyyy")
d1 = format.parse(dateStart)
d2 = format.parse(dateStop)
Log.d("Year_Difference", getDiffYears(d1, d2).toString())

Add this two method in your activity.
fun getDiffYears(first: Date, last: Date): Int {
        val a = getCalendar(first)
        val b = getCalendar(last)
        var diff = b.get(YEAR) - a.get(YEAR)
        if (a.get(MONTH) > b.get(MONTH) || a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE)) {
            diff--
        }
        return diff
    }

fun getCalendar(date: Date): Calendar {
        val cal = Calendar.getInstance(Locale.US)
        cal.time = date
        return cal
    }

A: public int GetDifference(long start,long end){
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(start);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int min = cal.get(Calendar.MINUTE);
    long t=(23-hour)*3600000+(59-min)*60000;

    t=start+t;

    int diff=0;
    if(end>t){
        diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
    }

    int leapYear = (diff/365)/4;

    return  (diff-leapYear)/365;
}

you need to define leap years, this code returns 17


text:
Q: Why do some relationship merge queries fail in Neo4j? I set up a Neo4j instance (3.2) both on my local machine (with brew) and on a remote machine (with Docker). I'm trying to run a query, for which I use py2neo functions (merge on the relationship) which create the Cypher automatically.
I define two Node objects, one each for subject and object labels with entity as the property for both. I create a Relationship object with the relationship type (is cheaper according to in the query below) and add a property called confidence to this relationship type. This is the query I'm trying to run:
MERGE (a0:subject {entity:"VSS"})
SET a0:subject
MERGE (a1:object {entity:"Vanguard"})
SET a1:object
MERGE (a0)-[r0:`is cheaper according to`]->(a1)
SET r0.confidence="1.0"
RETURN a1, a0, r0 LIMIT 1

This query works fine on my local Neo4j, but on the remote, I get the following error:
bolt.fetch S: FAILURE {u'message': u'Could not create token', u'code': u'Neo.DatabaseError.General.UnknownError'}

I tried running the above query directly in the browser client too, and had the same response, viz. it works on my local Neo4j but not my remote.
Further, if I replace the relationship type is cheaper according to with just is cheaper, the query fails both in my local and my remote Neo4j.
My setup for Neo4j on both is identical and pretty vanilla. I do have two indexes on each though, on the subject and object nodes.
I couldn't find anything to support differing behavior on the local v/s the remote, and I certainly couldn't see any reason why changing the relationship type would fail. Is there something I'm missing here?
Would really appreciate the help, thanks!