text:
Q: Node.js Chat Room on Heroku Application Error I'm getting an Application Error when loading my heroku page. I followed the instructions here https://devcenter.heroku.com/articles/deploying-nodejs.
My code is a tweaked version of this build https://enlight.ml/nodejs-chat.
Part of my node server.js file.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var people = {};
var heads = [];
app.get('/', function(req, res, next) {
    res.sendFile(__dirname + '/public/index.html')
});

server.listen(process.env.PORT || 5000);

heroku log.
2017-03-27T05:40:05.790068+00:00 heroku[web.1]: State changed from crashed to starting
2017-03-27T05:40:07.296635+00:00 heroku[web.1]: Starting process with command `node server.js`
2017-03-27T05:40:09.867374+00:00 app[web.1]: module.js:471
2017-03-27T05:40:09.867387+00:00 app[web.1]:     throw err;
2017-03-27T05:40:09.867387+00:00 app[web.1]:     ^
2017-03-27T05:40:09.867388+00:00 app[web.1]:
2017-03-27T05:40:09.867389+00:00 app[web.1]: Error: Cannot find module 'socket.io'
2017-03-27T05:40:09.867390+00:00 app[web.1]:     at Function.Module._resolveFilename (module.js:469:15)
2017-03-27T05:40:09.867390+00:00 app[web.1]:     at Function.Module._load (module.js:417:25)
2017-03-27T05:40:09.867391+00:00 app[web.1]:     at Module.require (module.js:497:17)
2017-03-27T05:40:09.867392+00:00 app[web.1]:     at require (internal/module.js:20:19)
2017-03-27T05:40:09.867392+00:00 app[web.1]:     at Object.<anonymous> (/app/server.js:4:30)
2017-03-27T05:40:09.867393+00:00 app[web.1]:     at Module._compile (module.js:570:32)
2017-03-27T05:40:09.867393+00:00 app[web.1]:     at Object.Module._extensions..js (module.js:579:10)
2017-03-27T05:40:09.867395+00:00 app[web.1]:     at Function.Module._load (module.js:438:3)
2017-03-27T05:40:09.867394+00:00 app[web.1]:     at tryModuleLoad (module.js:446:12)
2017-03-27T05:40:09.867394+00:00 app[web.1]:     at Module.load (module.js:487:32)
2017-03-27T05:40:09.947727+00:00 heroku[web.1]: State changed from starting to crashed
2017-03-27T05:40:09.928089+00:00 heroku[web.1]: Process exited with status 1

package.json.
{
  "name": "im",
  "version": "1.0.0",
  "description": "Messaging App",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/username/im.git"
  },
  "author": "me",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/username/im/issues"
  },
  "homepage": "https://github.com/username/im#readme",
  "dependencies": {
    "express": "4.15.2"
  },
  "engines": {
    "node": "6.10.0"
   },
  "devDependencies": {},
  "keywords": [
    "chat",
    "app"
  ]

}

.gitignore file.
    /node_modules
    npm-debug.log
   .DS_Store
   /*.env

A: This solved it.
npm install socket.io --save
git add .
git push heroku master

A: you need to install socket.io package and save it in package.json
npm install socket.io --save

OR reference where you have saved.
var io = require('../lib/socket.io');

And then use it .


text:
Q: I can access my samba server via hostname, but not via ip There is a SAMBA server with a very basic configuration:
[share]
   path = /srv/samba
   force group = users
   create mask = 0660
   directory mask = 0771
   browsable =yes
   writable = yes
   guest ok = no

Its very creative hostname is "server".
I can access it fine via \\server\share, get asked my credentials and am on my way.
If I access via \\192.168.0.24\share my credentials are rejected.
My client is Windows 10.
I double checked the ip address.
Any pointers what is going on?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to select data using like with out consider after character in laravel or sql I have a table call labels_table.

id
label

1
A_1_1

2
A_1_2

3
A_2_1

4
A_4_1

5
A_10_1

6
A_11_1

I need to select all the labels for A_1 group. A_1_1 and  A_1_2 should be the correct labels.
I used the following query.
sql
SELECT * from `label_table` where `label` LIKE `A_1_%`;

Larval
$identifier = "A_1";

$this->model->where('label', 'LIKE',$identifier.'_%')->get();

But both SQL and laravel queries returns all A_1_1, A_1_2, A_10_1 and A_11_1. But I need to get only A_1_1 and  A_1_2.
Please explain what's the issue here and give me a solution. thank you.

A: LIKE allows you to escape the wildcard characters.  The default is backslash:
where `label` LIKE 'A\_1\_%';

However, you can also set your own:
where `label` LIKE 'A$_1$_%' ESCAPE '$';

Or use regular expressions:
where label REGEXP '^A_1_'

A: Underscore symbol in a LIKE predicate means any single symbol. Escape it to use as a literal "_".
SELECT *
FROM label_table
WEHRE label LIKE 'A\_1\_%'

db<>fiddle


text:
Q: Whenever I launch the app for the first time the app crashes and then it asks me the user permission My Android application crashes the first time launching and it asks me about the user call permission. When I launch my app again then it works normally. I have tried the following code.
public void loadContactList() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
    } else {.....}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,int[] grantResults) {
    if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            loadContactList();
        } else {
            Toast.makeText(this, "Until you grant the permission, we canot display the list", Toast.LENGTH_SHORT).show();
        }
    }
}

A: Your code is right but you set the codes on wrong places lets try this it will definitely help you....
In Your Main Activity...

private int STORAGE_PERMISSION_CODE = 1;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ContextCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
  PackageManager.PERMISSION_GRANTED) {
        filter();
        Toast.makeText(this, ""+arrayList, Toast.LENGTH_SHORT).show();
    } else {
        Permission.requestStoragePermission(MainActivity.this,
                  STORAGE_PERMISSION_CODE);
    }

}//on create closed

Permission method.....
//---------------------------------RuntimePermission-----------------------------//
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
    permissions, @NonNull int[] grantResults) {
    if (requestCode == STORAGE_PERMISSION_CODE)  {
        if (grantResults.length > 0 && grantResults[0] ==
     PackageManager.PERMISSION_GRANTED) {
            filter();
        } else {
            Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();

Permission.requestStoragePermission(MainActivity.this,STORAGE_PERMISSION_CODE);
        }
    }
}

after that make java class for getting permission....
public class Permission {
public static void requestStoragePermission(final Activity activity, final int
       STORAGE_PERMISSION_CODE) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        new AlertDialog.Builder(activity)
                .setTitle("Permission needed")
                .setMessage("This permission is needed because of this and that")
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(activity,
                                new String[]
        {Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
                    }
                })
                .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create().show();
    } else {
        ActivityCompat.requestPermissions(activity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
   STORAGE_PERMISSION_CODE);
    }
}

}
The main thing you have to remember is to put your working method at the right place like my is filter();
It will work for you because it work for me when i stuck in the same situation

A: Add the following code
String[] appPermissions =
            {Manifest.permission.READ_CONTACTS,
                    Manifest.permission.WRITE_CONTACTS};
    int PERMISSIONS_REQUEST_CODE = 234;

Call this Method from your on create
checkAndRequestPermissions();

Add the following method to your Main Activity
public boolean checkAndRequestPermissions() {
        List<String> listPermissionsNeeded = new ArrayList<>();
        for (String perm : appPermissions) {
            if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(perm);
            }
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), PERMISSIONS_REQUEST_CODE);
            return false;
        }
        return true;
    }

A: I just solved an exception. I did two things. Firstly, I removed the initialization of Contacts by
Contacts = new ArrayList<ContactModel> from the loadContactList() and added it into the onCreate() and Secondly I just changed the return datatype of loadContactList() from void to list. Then I returned the contacts in loadContacts() so that loadListView() can fetch this list and display it into the list view.


text:
Q: Grails mapping to solve exception when saving instance I have the following domain classes:
class Team{
    static hasMany = [localMatches: Match, visitingMatches: Match]
    static mappedBy = [localMatches: 'localTeam', visitingMatches: 'visitingTeam']

    List<Match> localMatches = new ArrayList<Match>()
    List<Match> visitingMatches = new ArrayList<Match>()
}

class Match{
    Team localTeam
    Team visitingTeam
}

When I run the following:
Match match = new Match(localTeam: aLocalTeam, visitingTeam: aVisitingTeam)
match.save(flush: true, failOnError: true)

I get the exception "Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "LOCAL_TEAM_ID"; SQL statement:"
So I need to set the match in each team before saving the match to avoid the exception:
Match match = new Match(localTeam: aLocalTeam, visitingTeam: aVisitingTeam)
aLocalTeam.localMatches.add(match)
aVisitingTeam.localMatches.add(match)
match.save(flush: true, failOnError: true)

Is there any way of mapping the classes so I wouldn't need to do add the match to each team before saving?

A: The hasMany block defines that a Match has many localMatches, but then below redefines localMatches as a relationship to a single Match. What I believe you actually mean is:
class Team {
    static hasMany = [localMatches: Match, visitingMatches: Match]
    static mappedBy = [localMatches: 'localTeam', visitingMatches: 'visitingTeam']
}

class Match {
    Team localTeam
    Team visitingTeam
}

Mapped this way, Team will have two collections of Matches and each Match will have a local and visiting Team.


text:
Q: how to use and update panels in ncursesw I'm currently coding in C++ in Ubuntu WSL2, using the <panel.h> header to create panels in ncursesw, as I need Unicode characters.
I've done a couple tests already, where the results are shown in the table below:

This is the code and result when creating a window with a WINDOW* and -lncursesw.
Code:
#include <panel.h>

int main() {
    setlocale(LC_ALL, "");
    initscr();
    noecho();
    cbreak();
    refresh();

    WINDOW *window {newwin(0, 0, 0, 0)};

    box(window, 0, 0);
    mvwaddstr(window, 1, 1, "\U0001F600");
    wrefresh(window);

    getch();
    endwin();
}

Result:

This is the code and result when creating a window with a PANEL* and -lncursesw.
Code:
int main() {
    setlocale(LC_ALL, "");
    initscr();
    noecho();
    cbreak();

    PANEL *panel {new_panel(newwin(0, 0, 0, 0))};

    box(panel_window(panel), 0, 0);
    mvwaddstr(panel_window(panel), 1, 1, "\U0001F600");
    // wrefresh(panel_window(panel));
    update_panels();
    doupdate();

    getch();
    endwin();
}

Result:

However if I uncomment the wrefresh() line, I get the same desired result when using WINDOW *. Why is this happening?

A: doupdate doesn't do a wrefresh (it's generally used after one more more windows is prepared using wnoutrefresh).
Without an explicit wrefresh, your program is getting the wrefresh done as a side-effect of getch — which refreshes stdscr, but that in turn has only the pending werase from initscr followed by the box call: it seems you'll get an empty box.

A: I mistakenly used -lpanel -lncursesw, when I should've been using -lpanelw -lncursesw instead. That fixed it for me.


text:
Q: Path integral of $1/z$ along $e^{it}$ I tried to calculate the (complex) path integral of $1/z$ along $y: [0, \pi] \rightarrow \mathbb{C}, y(t) = e^{it}$, and got the result $i\pi$.
Is this correct?

A: Yes, it is correct, because
$$\int \limits _y \frac 1 z \ \Bbb d z= \int \limits _0 ^\pi \frac 1 {\Bbb e ^{\Bbb i t}} (\Bbb d \Bbb e ^{\Bbb i t}) = \int \limits _0 ^\pi \frac 1 {\Bbb e ^{\Bbb i t}} \Bbb i \ \Bbb e ^{\Bbb i t} \Bbb d t = \int \limits _0 ^\pi \Bbb i \ \Bbb d t = \Bbb i \pi .$$


text:
Q: Having two vectors is there a nicer way to test if one is included in another? Given two vectors:
x = c('a','b')
lookup = c('a','c','d','e','f')

test if each element in x is present in lookup. One way of doing it:
all(!is.na(match(x, lookup)))

I find this solution a bit verbose for R and wonder if there is better/shorter version.

A: %in% does this:
all(x %in% lookup)
## [1] FALSE

A: Can also use setdiff. See the associated help page for other set operations.
setdiff(x,lookup)
[1] "b"
> as.logical(length( setdiff(x,lookup) ) )
[1] TRUE


text:
Q: QooXDoo example for config.json from manual produce error pretty-print I take the example from the doc 1.4 for "pretty-print" job key in my config.json.
"jobs" :   {
    "pretty-print" :    {
        "general" :     { ..... },
        "comments" :    {  ...... },
        "blocks" :    { ....... }
    },

python Generate.py produce this:

Warning: ! Unknown job config key "blocks" - ignored.
    Warning: ! Unknown job config key "comments" - ignored.
    Warning: ! Unknown job config key "general" - ignored.

I looked everywere, doc & source and not understand why
EDITED
I am using QooXdoo 1.4 whit Python 2.6
I am working whit source javascript generated from another system
I need to reformat the source .js and need to modify the standard setting QooXdoo use
From http://manual.qooxdoo.org/1.4.x/pages/tool/generator_config_ref.html i take the example:
"pretty-print" :
{
  "general" :
  {
    "indent-string"        : "    "
  },
  "comments" :
  {
    "trailing" :
    {
      "keep-column"        : false,
      "comment-cols"       : [50, 70, 90],
      "padding"            : "    "
    }
  },
  "blocks" :
  {
    "align-with-curlies"   : false,
    "open-curly" :
    {
      "newline-before"     : "N",
      "indent-before"      : false
    }
  }
}

and put into the config.json of my app
the job "pretty-print" is executed but ignoring  the setting
RE-EDITED
i have problem only whit this key "pretty-print", other variation on config.json is ok

A: You got it nearly right, you just missed one level of nesting.
The overall structure of the jobs map is as follows (which is also documented here):
"jobs" : {
     "job-name" : {
          "pretty-print" : { ... }
          ...
     }
     ...
}

So you just need to insert a job name between "jobs" and "pretty-print"; a job name is just a freely selectable string. (You can think of the "jobs" map as being a container, the [job-name]'s as individual objects in this container, and "pretty-print", and all the other keys you saw documented on the generator_config_ref.html, as properties of the specific individual).
Now, you can define a job object from scratch, e.g. by giving it a unique name such as my-pretty-print. But this requires you to put together all the necessary job properties, for the job to run successfully (This is hinted at with the peer-keys note given with many key descriptions).
I rather recommend using a pre-defined job, and refining it. In your case, use the default job pretty, and refine that. By naming the job in your own config pretty you automatically inherit all the properties from the pre-defined job. So just adding
"jobs" : {
    "pretty" : {}
}

to your config map will create a custom job pretty that does the exact same thing as the default job of the same name (as you have nothing changed). Now you are in the position to just provide the things you want differently from the default job, e.g.
"jobs" : {
    "pretty" : { "general" : { "indent-string" : "    " }}
}

will use all the default settings except the indent string will have 4 spaces instead of 2. This should get you going.


text:
Q: How to return a value into an asynchronous method? When I call this method, nothing happens and the application crashes. I think it's due the ExecuteAsync method.can someone help me?.This is my code.
CODE1:
public Task<Connection> Connect(string userId, string password)
    {
        var client = new RestClient(_baseUrl)
            {
                Authenticator = new SimpleAuthenticator("user", userId,
                     "password", password)
            };
        var tcs = new TaskCompletionSource<Connection>();
        var request = new RestRequest(AppResources.Authenticating);
        client.ExecuteAsync<Connection>(request, response => tcs.SetResult(new
               JsonDeserializer().Deserialize<Connection>(response)));
        return tcs.Task;
    }

I tried this code also but still the same problem exists.
CODE2:
public async Task<Connection> Connect(string userId, string password)
    {
        var client = new RestClient(_baseUrl)
            {
                Authenticator = new SimpleAuthenticator("user", userId,
                      "password", password)
            };
        var tcs = new TaskCompletionSource<Connection>();
        var request = new RestRequest(AppResources.Authenticating);
        client.ExecuteAsync<Connection>(request, response => tcs.SetResult(new
                JsonDeserializer().Deserialize<Connection>(response)));
        Debug.WriteLine(tcs.Task.Result.Data);
        return await tcs.Task;
    }

A: You don't want to use Task.Result or Task.Wait in asynchronous code. Those members are only used when you use Task as part of the Task Parallel Library (writing parallel code). They should almost never be used in asynchronous code.
In your case, I suspect that you're calling Result on the Task returned by Connect (or possibly further up the call stack). This can cause a deadlock, as I explain on my blog.
I disagree with @LasseVKarlsen regarding asynchronous code for beginners. I think it is absolutely something you should learn now that the new async/await language features are out.
I recommend you start with my introduction and follow up with the MSDN docs and the TAP pattern. Then review my best practices article to avoid the most common pitfalls.


text:
Q: Get non-repeated characters in string and count them I need to process a string like abclkjabc and return only 3 which counts characters l, k, and j.
I've tried this.
$stringArr = [];
foreach(str_split($string) as $pwd) {
   if(!in_array($pwd, $stringArr)) {
      $stringArr[] = $pwd;
   }
}
$uniqChar = count($stringArr);

A: Try the following instead:
function getNonRepeatingCharacters($str) {
    $counter = [];
    $spllitted = str_split($str);
    foreach($spllitted as $s) {
        if(!isset($counter[$s])) $counter[$s] = 0;
        $counter[$s]++;
    }
    $non_repeating = array_keys(array_filter($counter, function($c) {
        return $c == 1;
    }));

    return $non_repeating;
}

$string = "abclkjabc";
$handle = getNonRepeatingCharacters($string);

A: Functional programming and no temporary variable declarations:

*

*Create an array of characters

*Count the occurrences of each character

*Retain only characters that occurred once (array_filter() also works but is more verbose)

*Re-join the qualifying characters

Code: (Demo) (or just the count)
echo implode(
         array_keys(
             array_intersect(
                 array_count_values(
                     str_split('abclkjabc'),
                 ),
                 [1]
             )
         )
     );

Or with semi-functional with a loop: (Demo) (or just the count)
$unique = '';
foreach (array_count_values(str_split('abclkjabc')) as $char => $count) {
    if ($count === 1) {
        $unique .= $char;
    }
}
echo $unique;

Output:
lkj

Getting the length of the output string can be done with strlen().

Instead of splitting the string and count array values, you can count character values with count_chars(). (Demo)
$string = 'abclkjabc';
$notRepeated = [];
foreach (count_chars($string, 1) as $char => $count) {
    if ($count === 1) {
        $notRepeated[] = chr($char);
    }
}
var_export($notRepeated);
echo "\nCount = " . count($notRepeated);

Ultimately, if you only need the count of non-repeated characters, this one-liner will get you there. (Demo)
echo count(array_filter(count_chars($string, 1), fn($count) => $count === 1));

A: Try this:
function getNonRepeatingChars($str) {
    $uniqueLetters = '';
    $multipleLetters = '';
    $arrayStr = str_split($str);

    foreach ($arrayStr as $index => $letter) {
        if (strpos($multipleLetters, $value) !== false || strpos($str, $value, $index + 1) !== false) {
            $multipleLetters .= $value;
            continue;
        }

        $uniqueLetters .= $value;
    }

    return $uniqueLetters;
}

echo getNonRepeatingChars('abclkjabc'); // lkj


text:
Q: Payroll program in C++ I have been working on this program for a class, however I cannot get my output correct.
My instructions from the assignment are:

Expand the Employee Payroll program to include hourly based and salary based employees. This phase uses an array of employee objects, inheritance for different classes of employees, and polymorphism for salary computation. The 52 week yearly salary as well as number of overtime hours worked by a salary based employee is given).
For salary based employees, to find the regular (gross) pay for a week, divide the salary by 52. To compute the overtime pay for a salary based employee, first find the hourly rate by dividing the gross pay by 40, and then compute overtime pay. For every employee, overtime pay, tax amount, and net pay must also be computed.
In addition, the program should find the minimum and maximum net pay of all employees as well as sort the employees based on their net pay (ascending order)

And this is what I have so far:
#include<fstream>
#include<iostream>
#include<iomanip>
using namespace std;
int totalEmployeeCount,hrs,employeeCounter,stat,empID;
double rate,regPay;
string fName;
string lName;

class employee{
public:
double salary,hourlyRate,taxRate,taxAmount,grossPay,netPay,otPay;
int hours,otHours;

public: void setVariables(int empID,string fName,string lName, int stat,
double rate, double hrs){
    int employeeID = empID;
    string firstName = fName;
    string lastName = lName;
    int payStat = stat;
    if(payStat ==1){hourlyRate = rate;}
    else{salary = rate;}
    hours = hrs;
}
//DECLARE FUNCTION TO CALCULATE GROSS PAY
public: virtual double calculateGrossPay()=0;

double calculateTaxAmount(){ taxRate = .30; // tax rate is a flat rate of 30%
taxAmount = grossPay*taxRate;  // CALCULATE TAX AMOUNT
return taxAmount;
}       // END CALCULATE TAXAMOUNT() FUNCTION.

double calculateNetPay(){
    netPay = grossPay - taxAmount;
    return netPay;
}       // END CALCULATENETPAY() FUNCTION.
void printData(){
    cout<<setprecision(2)<<setiosflags(ios::fixed | ios::showpoint);
    cout<<fName<<setw(6)<<lName<<setw(6)<<empID<<setw(10)<<hrs<<setw(3)
    <<otHours<<setw(8)<<grossPay<<setw(8)<<netPay<<setw(8)<<otPay<<endl;}
// END PRINTDATA() FUNCTION
}; // END EMPLOYEE CLASS

class employeeSalary : public employee{
    public: double calculateGrossPay() {
    double regPay = hours*hourlyRate;
    double hourlyRate = ((salary/52)/40);
    if (hours > 40) {otHours = (hours - 40); //calculate OT hours
     otPay = (otHours * hourlyRate); //calculate OT pay
     grossPay = (regPay + otPay); }
    else if (hours <= 40) {otHours = 0; otPay = 0; grossPay = regPay;}
    return grossPay;    }
}; //end EmployeeSalary class

class employeeHourly : public employee{
  public: double calculateGrossPay(){
   regPay = (40 * hourlyRate); //calculate regular hours
  if (hours > 40){   otHours = (hours - 40); //calculate OT hours
     otPay = (otHours * hourlyRate * 1.5); //calculate OT pay
     grossPay = (regPay + otPay); //calculate gross pay
  } //enf if clause for gross pay with overtime
  else { otHours = 0;   otPay = 0; grossPay = regPay;
  } //end else clause for four hours
  return grossPay;  } //end calculateGrossPay() function
}; //end EmployeeHourly class

int main(){
int employeeCounter;
cout<< "enter # of employees you want to process:  ";
cin>>totalEmployeeCount;
employee*employee[100];
while(employeeCounter < totalEmployeeCount){
    cout<<"Is employee "<<employeeCounter+1<< " hourly or salary? (enter 1
for hourly / 2 for salary):";
    cin>>stat;
    if (stat == 1){cout<< "Instantiating and HOURLY employee object
inherited from base class employee"
    <<endl<<endl;
        cout<<"Enter employee's ID: ";
        cin>>empID;
        cout<<"Enter employee's first name: ";
         cin>>fName;
        cout<<"Enter employee's last name: ";
         cin>>lName;
        cout<<"Enter employee's hourly wage: ";
         cin>>rate;
        cout<<"Enter employee's hours for this week: ";
         cin>>hrs;
        employee[employeeCounter] = new employeeHourly();
        employee[employeeCounter]->setVariables(empID, fName, lName, stat,
rate, hrs);
        employee[employeeCounter]->calculateGrossPay();
        employee[employeeCounter]->calculateTaxAmount();
        employee[employeeCounter]->calculateNetPay();
        cout<<endl<<endl;
            employeeCounter++; } //end if

    else{cout<<"instantialting a SALARY employee object in herited from base class employee"
    <<endl<<endl;
    cout<<"Enter employee's ID: ";
        cin>>empID;
        cout<<"Enter employee's first name: ";
         cin>>fName;
        cout<<"Enter employee's last name: ";
         cin>>lName;
        cout<<"Enter employee's hourly wage: ";
         cin>>rate;
        cout<<"Enter employee's hours for this week: ";
         cin>>hrs;
        employee[employeeCounter] = new employeeHourly();
        employee[employeeCounter]->setVariables(empID, fName, lName, stat,
    rate, hrs);
        employee[employeeCounter]->calculateGrossPay();
        employee[employeeCounter]->calculateTaxAmount();
        employee[employeeCounter]->calculateNetPay();
        cout<<endl<<endl;
        employeeCounter++;}
}
    /*employeeCounter = 0;
    while (employeeCounter < totalEmployeeCount){
        employee[employeeCounter]->printData();
        employeeCounter++;
    }*/
system("pause");
}

When I run my program in CMD, and input for 2 employees the second employee will overwrite the first one.  I am not sure what is wrong and any help or guidance would be very appreciated (I could not find this asked earlier but I assume it has been, I am a new student and not familiar with Stack Overflow).

A: Initialize employeeCounter and it'll work:
int employeeCounter = 0;

Frankly, this code simply is not presentable at all. You need to at least indent it consistently. There are a lot of things that you need to look at.
You should go through the C++ Core Guidelines.
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md
Edited -- Updated Code
Here's your cleaned up and functional code:
#include<fstream>
#include<iostream>
#include<iomanip>
using namespace std;

class employee
{
public:
    double salary, hourlyRate, taxRate, taxAmount, grossPay, netPay, otPay;
    int hours, otHours;

    int payStat;
    int employeeID;
    string firstName;
    string lastName;

public:
    void setVariables( int empID, string fName, string lName, int stat, int rate, int hrs )
    {
        employeeID = empID;
        firstName = fName;
        lastName = lName;
        payStat = stat;

        if( payStat == 1 )
        {
            hourlyRate = rate;
        }
        else
        {
            salary = rate;
        }

        hours = hrs;
    }

public:
    virtual double calculateGrossPay() = 0;

    double calculateTaxAmount()
    {
        taxRate = .30;
        taxAmount = grossPay*taxRate;
        return taxAmount;
    }

    double calculateNetPay()
    {
        netPay = grossPay - taxAmount;
        return netPay;
    }

    void printData()
    {
        cout << setprecision(2) << setiosflags(ios::fixed | ios::showpoint);
        cout << firstName << setw(6) << lastName << setw(6) << employeeID << setw(10) << hours << setw(3)
             << otHours << setw(8) << grossPay << setw(8) << netPay << setw(8) << otPay << endl;
    }
};

class employeeSalary : public employee
{
public:
    double calculateGrossPay()
    {
        double regPay = hours*hourlyRate;
        double hourlyRate = ((salary/52)/40);
        if (hours > 40)
        {
            otHours = (hours - 40);
            otPay = (otHours * hourlyRate);
            grossPay = (regPay + otPay);
        }
        else if (hours <= 40)
        {
            otHours = 0; otPay = 0; grossPay = regPay;
        }

        return grossPay;
    }
};

class employeeHourly : public employee
{
public:
    double calculateGrossPay()
    {
        const double regPay = (40 * hourlyRate);

        if ( hours > 40 )
        {
            otHours = (hours - 40);
            otPay = (otHours * hourlyRate * 1.5);
            grossPay = (regPay + otPay);
        }
        else
        {
            otHours = 0;
            otPay = 0;
            grossPay = regPay;
        }

        return grossPay;
    }
};

int main()
{
    int employeeCounter = 0;
    int totalEmployeeCount = 0;

    string fName, lName;
    int empID = 0, stat = 0, rate = 0, hrs = 0;

    cout << "enter # of employees you want to process:  ";
    cin >> totalEmployeeCount;

    employee* employee[100];

    while( employeeCounter < totalEmployeeCount )
    {
        cout<<"Is employee "<< employeeCounter+1 << " hourly or salary? (enter 1 for hourly / 2 for salary):";
        cin>>stat;

        if (stat == 1)
        {
            cout << "Instantiating and HOURLY employee object inherited from base class employee" << endl << endl;

            cout<<"Enter employee's ID: ";
            cin>>empID;
            cout<<"Enter employee's first name: ";
            cin>>fName;
            cout<<"Enter employee's last name: ";
            cin>>lName;
            cout<<"Enter employee's hourly wage: ";
            cin>>rate;
            cout<<"Enter employee's hours for this week: ";
            cin>>hrs;

            employee[employeeCounter] = new employeeHourly();
            employee[employeeCounter]->setVariables( empID, fName, lName, stat, rate, hrs );
            employee[employeeCounter]->calculateGrossPay();
            employee[employeeCounter]->calculateTaxAmount();
            employee[employeeCounter]->calculateNetPay();
            cout<<endl<<endl;
            employeeCounter++;
        }
        else
        {
            cout<<"instantialting a SALARY employee object in herited from base class employee"<<endl<<endl;
            cout<<"Enter employee's ID: ";
            cin>>empID;
            cout<<"Enter employee's first name: ";
            cin>>fName;
            cout<<"Enter employee's last name: ";
            cin>>lName;
            cout<<"Enter employee's hourly wage: ";
            cin>>rate;
            cout<<"Enter employee's hours for this week: ";
            cin>>hrs;
            employee[employeeCounter] = new employeeHourly();
            employee[employeeCounter]->setVariables(empID, fName, lName, stat,
                                                    rate, hrs);
            employee[employeeCounter]->calculateGrossPay();
            employee[employeeCounter]->calculateTaxAmount();
            employee[employeeCounter]->calculateNetPay();
            cout<<endl<<endl;
            employeeCounter++;
        }
    }

    cout << "-----------------------------------------\n";

    for ( int i = 0; i < employeeCounter; ++i )
    {
        employee[ i ]->printData();
    }

    cout << "-----------------------------------------\n";

    return 0;
}

You had global variables to store the data and in your print function you were printing those globals. That means you'd only get the latest stored values.
You really need to go through the fundamentals of OOP to get those things right.
Always indent your code.
Initialize your variables.
And, don't comment each line of code.


text:
Q: Configuring SQL Server database transaction logs truncation regularly? How can I configure SQL Server 2014, to allow truncating the logs by itself so that it doesn't fill up my database drive?
I need some help as I'm not a DBA myself and this SQL Server is installed within Azure VM backed up with Azure backup which does not truncate log files.
Thanks in advance.


text:
Q: MongoDB log file shows connection accepted & end connection constantly I'm trying to install MongoDb server in Redhat 7 GCE
After starting Mongod process with replication, the mongolog shows an error log..
`2017-12-29T20:51:12.853+0530 I NETWORK  [initandlisten] connection accepted
 from 10.142.0.2:38130 #53 (1 connection now open)
 2017-12-29T20:51:42.861+0530 I NETWORK  [conn53] end connection
 10.142.0.2:38130 (0 connections now open)
 2017-12-29T20:51:42.862+0530 I NETWORK  [initandlisten] connection accepted
 from 10.142.0.2:38136 #54 (1 connection now open)
 2017-12-29T20:52:12.868+0530 I NETWORK  [conn54] end connection
 10.142.0.2:38136 (0 connections now open)
 2017-12-29T20:52:12.869+0530 I NETWORK  [initandlisten] connection accepted
 from 10.142.0.2:38144 #55 (1 connection now open)
 2017-12-29T20:52:42.877+0530 I NETWORK  [conn55] end connection
 10.142.0.2:38144 (0 connections now open)
 2017-12-29T20:52:42.877+0530 I NETWORK  [initandlisten] connection accepted
 from 10.142.0.2:38150 #56 (1 connection now open)
 2017-12-29T20:53:12.883+0530 I NETWORK  [conn56] end connection
 10.142.0.2:38150 (0 connections now open)
 2017-12-29T20:53:12.883+0530 I NETWORK  [initandlisten] connection accepted
 from 10.142.0.2:38156 #57 (1 connection now open)
 2017-12-29T20:53:42.891+0530 I NETWORK  [conn57] end connection
 10.142.0.2:38156 (0 connections now open)
 2017-12-29T20:53:42.892+0530 I NETWORK  [initandlisten] connection accepted
 from 10.142.0.2:38162 #58 (1 connection now open)
 2017-12-29T20:54:12.900+0530 I NETWORK  [conn58] end connection
 10.142.0.2:38162 (0 connections now open)
 2017-12-29T20:54:12.900+0530 I NETWORK  [initandlisten] connection accepted
 from 10.142.0.2:38170 #59 (1 connection now open)
 2017-12-29T20:54:42.908+0530 I NETWORK  [conn59] end connection
 10.142.0.2:38170 (0 connections now open)
 2017-12-29T20:54:42.908+0530 I NETWORK  [initandlisten] connection accepted
 from 10.142.0.2:38174 #60 (1 connection now open)
 2017-12-29T20:55:12.917+0530 I NETWORK  [conn60] end connection
 10.142.0.2:38174 (0 connections now open)

`
I can connect from the redhat shell as

mongo --port 34672

but when i try to connect from an external ip it fails.
i was not able to find the reason for this error after checking all the error logs and searching in the web.

A: These log entries to not indicate an error. It is simply reporting connections. As for the reason for the connections, there could be several:

*

*If you have an application using MongoDB, these connections are likely coming from that application.

*If you have monitoring such as Stackdriver Monitoring installed, these could be connections from the monitoring to fetch statistics from MongoDB.

*If you are using a cluster of MongoDB servers, this could be connections or health-checking between them.

I think (2) or (3) are especially likely, given that they are coming from internal IP addresses are are spaced exactly 30 seconds apart.
I believe your issue connecting externally is unrelated to these messages. If that is what you are really concerned about, I suggest you open a new question about that.


text:
Q: Pretty URL with $_GET method I am new to coding, so additional explanation would be greatly appreciated. So far I was able to remove the file extensions with my htaccess file.
Options -MultiViews
RewriteEngine on

# Does not apply to existing directories, if directory exist then don't run the rule

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME}\.php -f

RewriteRule ^(.*)$ $1.php [NC,L]

In the "dashboard" directory I have another index.php (displayed only to users logged in). In the index I have a $_GET method to retrieve the status of the user. So when I access localhost/project/dashboard/ I am able to view the index.php.
When I want to use the GET method my url would be something like localhost/project/dashboard/?status=active, which I am trying to change to localhost/project/dashboard/active or localhost/project/dashboard/status/active.
I am working in a localhost environment and my directories are broken down like this.
MAIN
- includes
- dashboard
|
-- subfolder
|-- somefile.php
|
-- index.php
- css
index.php
login.php
logout.php
.htaccess ** (this is the file im working with)

I am using the URL: http://localhost/project/dashboard/active
I have tried adding the following lines to my .htaccess
1.
RewriteRule ^([a-zA-Z]+)/?$ /?status=$1 [NC,L,QSA] - doesn't work

Object not found! Error 404
2.
RewriteRule ^dashboard/([a-zA-Z]+)/?$ /?status=$1 [NC,L,QSA] - doesn't work

Redirects to localhost/dashboard
3.
IF I create ANOTHER .htaccess inside the "dashboard" directory and use write 1 line
RewriteRule ^([a-zA-Z]+)/?$ index.php?status=$1 [NC,L,QSA] - WORKS

However, when using the 3rd method I CANNOT access the subfolder or its files in the dashboard.
So if I try to access localhost/project/dashboard/subfolder/somefile it returns
"Object not found!" Error 404
If I try to access localhost/project/dashboard/subfolder/somefile.php it redirects to localhost/project/dashboard/
There are going to be more folders and subfolders later.

A: Try
RewriteRule ^project/dashboard/(.*)$ project/dashboard/?status=$1 [L]

A: After reading Hanna's suggestion I tweaked the file path.
RewriteRule ^dashboard/([a-zA-Z]+)/?$ dashboard/?status=$1 [NC,L,QSA]

This seems to do the trick!


text:
Q: User with full control unable to see this options (New,actions,Settings) which are present in peoples and groups SharePoint 2013
Person with full control unable to see options like New, Actions, Settings which are present inside this people and groups. and idea whats wrong with it ?

A: There is no "New" operation in "All People" (User Information List). And only site admins can use "Settings"(List Settings) in "All People" (User Information List). For these operations, you need to open a particular group.


text:
Q: How to convert a list of objects into a JSON object using a property as key? I have a List of objects from a specific class which have a name field. I'm trying to convert this list into a JSON object where the property key will be the name of this field and the value is always set to null.
My final JSON should look like this:
{
  "Java": null,
  "React": null,
  "Spring": null
}

My class looks like this:
public class Tag {
    private Long id;
    private String name; // Java, Spring, React

    // setters and getters omited
}

I tried to convert it using the below code:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(tagList);

But this just returns a JSON array of objects.
How can I convert my list into the above mentioned structure?

A: Either use json library and create the JSON by hand or use a higher-level library such as Jackson or Gson.
Based on the updated question, here is the code based on json library that produces the desired output:
{"Java":null,"Spring":null}

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class TagConverter {
    public static void main(String[] args) {
        List<Tag> tags = new ArrayList<>();
        Tag t1 = new Tag("Java");
        Tag t2 = new Tag("Spring");
        tags.add(t1);
        tags.add(t2);
        JSONObject json = new JSONObject();
        for(Tag t : tags){
            json.put(t.name, JSONObject.NULL);
        }

        System.out.println(json);
    }

    private static class Tag{
        public Long id;
        public String name;

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

Either add a maven dependency or get the library from maven:
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

A: In that case, you should convert your object to a key-value Map first while the key is the value of the name field (This can't be duplicated, duplication resulting in overriding the previous value), and value could be NULL for your case and then convert the map to JSON.


text:
Q: Working with "object sender, EventArgs e" inside an Event Handler When I manually cast the object sender and Eventargs e to a class like below what is it I am exactly doing? I know that it allows me to access all the arguments that have been passed and also to manipulate the object sender (as below):
private void Button1_Click(object sender, EventArgs e)
{
    / /casting the arguments
    MouseEventArgs eventargs = e as MouseEventArgs;
    Button button1 = sender as Button;
    // displays which mouse button I used
    MessageBox.Show(eventargs.Button.ToString());
    // displays the name of the button I clicked
    MessageBox.Show(button1.Name.ToString());
    // changes the text of the button
    button1.Text = "Ive changed";
}

I feel like I don't understand how this works, only that it works.
Also, it seems quite easy to write an event handler that serves several objects of the same type, but not one that can handle different types of event or different types of object ie:
private void Generic_Event_Handler(object sender, EventArgs e)
{
    // displays what object and event triggered the handler
    MessageBox.Show(sender.ToString());
    MessageBox.Show(e.ToString());
}

Is this ever used? Is there a decent explanation of eventhandlers out there?

A: The following signature
private or protected void EventHandlersName (object sender, EventArgs e)

is the signature that they have all the event handlers in .NET. The parameter called sender is associated with the object on which the event called e was raised.

Why the type of sender is object?

Because all types in .NET has as their base type the type System.Object. So this way it doesn't make any difference if we have a click event on button on a win form, or in a WPF applciation or in an ASP.NET web form button.

Why we should manually cast the object sender?

We should do so, in order we have access to the properties and the methods of the specific type we have in each case.
For instance, all controls may not have a property called Name. Furthermore the base type called System.Object doesn't have. So if you don't cast the object sender to a Button class, then you can't read it's property called Name.

A: The signature of an event handler in .Net is (or at least should be):
(object sender, XXArgs e) where XXArgs is a class that inherits from EventArgs.
sender is, well, the sender of the event. In your example, if you click on a button, the button will fire the event using its own instance reference (this) for the sender parameter (so sender is a reference to your button). This is useful because you don't need to store references to the sender of the event ; it's available right here in the event handler.
For the XXArgs part, it contains information about the event. You shouldn't cast it actually, but write your handler with the right signature.
Basically, for a mouse click on a button, the right signature of the event handler would be:
private void Control_MouseClick(Object sender, MouseEventArgs e)
{
}

A: sender is a reference to type object. The actual object that it refers to could be anything; (in the specific case of an event handler, if everything is working as intended it should refer to the control that generated the event). When you say:
Button button1 = sender as Button;

you are trying to use a Button reference to refer to the same underlying object. If the underlying object is compatible (ie: is a Button), then the button1 reference will enable you to utilize the Button members of the underlying object. Otherwise, with the sender reference, you would only have been able to utilize the object members of the underlying object.
Note that it could still be something more "concrete" or specific than a Button, and then you would need a different cast to get at the more derived members.

A: Also you can cast page in case of protected void Page_Load(object sender, EventArgs e)
var senderInfo = (Page)sender;


text:
Q: curl fails with timeout on gitlab-ci runner I have a simple ci which is supposed to build a docker image and trigger the deployment via a stage url.
Therefore i use a simple curl request  curl -X POST $STAGE_URL
The pipeline works on shared runners but on my own runner it fails with after 2:45 min with curl: (28) Failed to connect to www.someurl.com port 443: Operation timed out
My config.toml looks like this
concurrent = 4
check_interval = 0

[session_server]
  session_timeout = 1800

[[runners]]
  name = "scalangular-runner"
  url = "https://gitlab.com/"
  token = "abcdefghijklm"
  executor = "docker"
  [runners.custom_build_dir]
  [runners.cache]
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]
  [runners.docker]
    tls_verify = false
    image = "docker:stable"
    privileged = true
    disable_entrypoint_overwrite = false
    oom_kill_disable = false
    disable_cache = false
    cach_dir = "cache"
    volumes = ["/cache"]
    shm_size = 0

Any idea?


text:
Q: Hartshorne's definition of structure sheaf Hartshorne at page $70$ defines the structure sheaf on Spec $A$. The elements of $\mathcal O_{\textrm{Spec}A}(U)$ are particular functions $s:U\longrightarrow\coprod_{p\in U}A_p$. With the symbol  $\coprod_{p\in U}$ I think he means the coproduct in the category of commutative rings, but in can't figure out what precisely is $\coprod_{p\in U}A_p$ in this case. It is the direct sum of the rings $A_p$? Does the coproduct always exist in the category of commutative rings?

A: It is just the disjoint union of the underlying sets. The elements of $\mathcal{O}_{\text{Spec}A}(U)$ are functions on $U$ whose value at the point $\mathfrak{p}$ is an element of the local ring $A_{\mathfrak{p}}$


text:
Q: "minikube start" failed on mac When I attempt to run minikube on locally, I got this error:
minikube start
Starting local Kubernetes v1.8.0 cluster...
Starting VM...
Getting VM IP address...
Moving files into cluster...
E1229 09:52:55.432296    8935 start.go:223] Error updating cluster:  Error updating localkube from uri: Error creating localkube asset from url: Error opening file asset: /Users/user007/.minikube/cache/localkube/localkube-v1.8.0: open /Users/user007/.minikube/cache/localkube/localkube-v1.8.0: no such file or directory

How can I fix this problem? I tried many ways, but no one worked.
My system is macOS Sierra.

A: Looks like this is a recurring issue. Check out the github issues here: https://github.com/kubernetes/minikube/issues/2468

A: I was having this issue and followed Chris Darby link (https://github.com/kubernetes/minikube/issues/2468).
I managed to fix it with the following workaround (considering the new version 1.9.0):

*

*Download localkube

*Rename it to localkube-v1.9.0

*Copy the file
in ~/.minikube/cache/localkube/localkube-v1.9.0


text:
Q: Plot Mean Speed On a Histogram What I'm trying to do is pretty simple in theory:
dataset <- data.frame(angle = c(10.1,-10.1,20.5,83.2),
                     speed = c(20,40,10,30))

a <- ggplot(data = dataset, aes( x = angle))+
  geom_histogram( stat ="bin", bins =100, aes(color = mean(speed))) +
  coord_polar( start =3.14,  direction = 1 ,theta = "x")+
  theme_pander(lp = 'top')+
  xlim(-150,150)+
  scale_colour_pander()#starts at Pi

What I'm currently getting:

I'd like to apply the mean speed for each bin as the color for every bin. Any help would be appreciated.
Thank you!

A: Just wondering, on your graph the count is 0-1 by .25, I am a nub R user but here is my attempt at your question:
ggplot(data = dataset, aes( x = angle))+
geom_histogram( stat ="bin", bins =100, aes(color = mean(speed))) +
coord_polar( start =3.14,  direction = 1 ,theta = "x")+
xlim(-150,150)+
geom_line(data = dataset, aes(x=angle, mean(speed)/100), lwd = 2, col = "blue")

the lines I took out were because they weren't found. This plots a curve at 0.25 which is you mean/100, when you take this out it doesn't show your other plot. Hope it helps.


text:
Q: Apache2 redirect with wildcard subdomain I placed the following config in apache site conf file:
<VirtualHost *:80>
        ServerName domain.com
        ServerAlias *.domain.com
        ServerAdmin webmaster@localhost
        Redirect permanent / https://domain.com/
</VirtualHost>

How can I have subdomains redirect without going to the main domain?
If I type http://subdomain.domain.com/ it redirects to https://domain.com/ but I want it to redirect to https://subdomain.domain.com/. I also want it to be a wildcard so that it works for all subdomains.
Is it possible without engaging the mod_rewrite module?

A: I don't think it's possible without mod_rewrite, but I'm not sure. With rewrite is very simple though:
RewriteEngine On

RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


text:
Q: Perspective control in MATLAB 3D figures How to change the vanishing points (P1,P2,P3) in the perspective in MATLAB 3D figures?
Below there is a scheme of explanation what I mean:

Thanks in advance for your help.

A: If you want to control the perspective appearance in a plot, you'll want to first change the Projection property of the axes to perspective. Then you can change the various camera properties of the axes to get the view you want. The important ones for adjusting how the perspective looks are the CameraViewAngle and CameraPosition.
I have found that a "realistic" perspective view can be achieved using a CameraViewAngle of about 30 degrees, mimicking the preferred viewing area of the human eye:

The default CameraViewAngle is about 6.6, so setting it to 30 will cause the view to appear zoomed-out. You will then want to change the CameraPosition so that it is closer to the CameraTarget, thus zooming the view back in. You can use a larger CameraViewAngle if you want a more exaggerated perspective (like a fisheye lens).


text:
Q: Building a dictionary from a tab delimited file in a pythonic way I've written the following function that takes a tab delimited file (as a string) and turns it into a dictionary with an integer as a key and a list of two floats and the value:
def parseResults(self, results):
    """
    Build a dictionary of the SKU (as key), current UK price and current Euro price
    """
    lines = results.split('\n')
    individual_results = []
    for i in range(1,len(lines)-1):
        individual_results.append(lines[i].split('\t'))
    results_dictionary = {}
    for i in range(len(individual_results)):
        results_dictionary[int(individual_results[i][0])] = [float(individual_results[i][1]), float(individual_results[i][2])]
    return results_dictionary

I've been reading about using list comprehension and also dictionary comprehension but I don't really know what the best way to build this is.
I think I can simplify the first list build using:
individual_results = [results.split('\t') for results in lines[1:]]

but I don't then know the best way to create the dictionary. I've got the feeling this might be possible in a neat way without even creating the intermediate list.
Thanks,
Matt

A: Like this:
import csv
import StringIO
results = "sku\tdelivered-price-gbp\tdelivered-price-euro\tid\n32850238\t15.53\t35.38\t258505\n"

data = list(csv.DictReader(StringIO.StringIO(results), delimiter='\t'))
print(data)

Output:
[{'sku': '32850238', 'delivered-price-euro': '35.38', 'delivered-price-gbp': '15.53', 'id': '258505'}]

Of course, if you can read from an actual file, you can skip the stringIO part.
To build the type of dictionary you want, you would do this:
data = {}
for entry in csv.DictReader(StringIO.StringIO(results), delimiter='\t'):
    data[entry['sku']] = [entry['delivered-price-gbp'], entry['delivered-price-euro']]

Or even as a dictionary comprehension:
import csv
import StringIO
results = "sku\tdelivered-price-gbp\tdelivered-price-euro\tid\n32850238\t15.53\t35.38\t258505\n10395850\t35.21\t46.32\t3240582\n"

data = {entry['sku']: [entry['delivered-price-gbp'], entry['delivered-price-euro']]
        for entry in csv.DictReader(StringIO.StringIO(results), delimiter='\t')}
print(data)

But that's now getting highly difficult to read.
The output would in those two last cases be:
{'32850238': ['15.53', '35.38'], '10395850': ['35.21', '46.32']}

A: Use the CSV module from the standard library it has a method for reading straight to a dictionary
csv.DictReader

A: Try something like this:
In [8]: from collections import defaultdict

In [9]: with open("filename") as f:
   ...:     dic=defaultdict(list)
   ...:     next(f)                #skip the first line
   ...:     for line in f:
   ...:         k,v=line.split(None,1)
   ...:         dic[int(k)].extend( map(float,v.split()[:2]) )
   ...:

In [10]: dic
Out[10]: defaultdict(<type 'list'>, {32850238: [15.53, 35.38]})

A: Your code can simply be:
def parseResults(self, results):
    lines = results.split('\n')
    li_results = [x.split('\t') for x in lines]
    results_dict = {int(x[0]):map(float,[x[1],x[2]]) for x in li_results[1:]} # skip the header
    return results_dict

or if you want it shorter(not recommended):
def parseResults(self, results):
    return {int(x[0]):map(float,[x[1],x[2]]) for x in [i.split('\t') for i in results.split('\n')][1:]}

Output(from the string you have given):
{32850238: [15.53, 35.38]}


text:
Q: Get Output of system("insmod mmodule.ko") I want to run shell command in C program and get stdout output.
I did it in this function:
int run_shell_cmd_nout(const char* cmd)
{
    FILE *fp;
    char out[4096]     = {0};
    char str[256]       = {0};
    char full_cmd[1024] = {0};
    int result = 0;

    // Compose full shell command
    if (!sprintf(full_cmd, "/system/bin/%s", cmd))
    {
        printf("Failed to compose full shell command\n");
        return -1;
    }

    // Open the command for reading.
    fp = popen(full_cmd, "r");
    if (fp == NULL)
    {
        printf("Failed to run command\n");
        return -1;
    }

    // Read the output a line at a time - output it.
    while(!feof(fp))
    {
         if(fgets(str, 256, fp) != NULL)
         {
             result = -1;
             strcat(out, str);
         }
    }

    pclose(fp);

    if (result != 0)
    {
        printf("%s\n", out);
        return -1;
    }

    return 0;
}

But it doesn't work with insmod.
Is there any way to intercept all outputs when invoke insmod?


text:
Q: Restrain inferred type of Object.fromEntries The inferred return type of the following function is {[k: string]: number}:
export const dateParts = (
  date: Date,
  timeZone?: string
) => {
  const options = {
    day: "numeric",
    month: "numeric",
    timeZone,
    year: "numeric",
  } as const;
  const formatter = new Intl.DateTimeFormat("en", options);
  const parts = formatter.formatToParts(date);
  return Object.fromEntries(
    parts
      .filter(({ type }) => ["year", "month", "day"].includes(type))
      .map(({ type, value }) => [type, Number(value)])
  );
};

But for the keys of the returned object the only posible options are year, month, and day.
Is there a way to restrain the keys of the returned object to be only those?
I tried explicitly adding the return type as {'year': number, 'month': number, 'day': number} or Record<'year' | 'month' | 'day', number>:
export const dateParts = (
  date: Date,
  timeZone?: string
): { year: number; month: number; day: number } => {

But then it conflicts with what Object.fromEntries is returning:
Type '{ [k: string]: number; }' is missing the following properties from type '{ year: number; month: number; day: number; }': 'year', 'month', 'day' ts(2739)

I haven't been able to figure out how to modify the return type of Object.fromEntries so it matches {'year': number, 'month': number, 'day': number} instead of {[k: string]: number}.

A: Unfortunately, the compiler cannot follow your logic at the type-level strongly enough to give you the types you're looking for.  At each step along the way: filter(), map(), and Object.fromEntries(), the compiler produces a correct but too-wide-to-be-useful type.
Ultimately you're going to want to use a type assertion like this:
  return Object.fromEntries(
    parts
      .filter(({ type }) => ["year", "month", "day"].includes(type))
      .map(({ type, value }) => [type, Number(value)])
  ) as Record<'year' | 'month' | 'day', number>;

This is a reasonable approach for situations, like this one, where you know more than the compiler about the type of a value.

The alternative is to provide your own more specific typings for/to filter(), map(), and Object.fromEntries(), which are likely to be useful only for this specific line of code, and have their own caveats.
For example, the compiler does not realize that ({type} => ["year", "month", "day"].includes(type)) acts as a type guard on its input.  Type guard functions are not inferred automatically; you would have to annotate it yourself as a user-defined type guard function, like this:
const filteredParts = parts
  .filter((part): part is { type: "year" | "month" | "day", value: string } =>
    ["year", "month", "day"].includes(part.type))
/* const filteredParts: {
type: "year" | "month" | "day";
value: string;
}[] */

Now the output of filter() will be narrow enough.  The caveat here is that the compiler just believes you that a user-defined type guard does what it says it's doing, so it's like a type assertion.  Had you written ["foo", "bar", "baz"].includes(part.type), instead, the compiler wouldn't notice or warn you.
Then, when you return an array literal inside map() like [key, val], the compiler will widen it to an unordered array type like Array<typeof key | typeof val>, whereas you specifically need a tuple type like [typeof key, typeof val].  So you'll need to change that behavior, possibly by using a const assertion:
const mappedParts = filteredParts.map(
  ({ type, value }) => [type, Number(value)] as const
);
// const mappedParts: (readonly ["year" | "month" | "day", number])[]

Great, now you have something to pass to Object.fromEntries().  Unfortunately, the TypeScript standard library's type definitions for Object.fromEntries() just returns either any, or something with a string index signature.
If you want, you could merge in your own type signature that returns a key-remapped type which more accurately represents things (and it will have to be a global augmentation if you are using modules), like this:
interface ObjectConstructor {
  fromEntries<T extends readonly [PropertyKey, any]>(
    entries: Iterable<T>
  ): { [K in T as T[0]]: T[1] };
}

And then, finally, your return value will be strongly typed the way you want:
const ret = Object.fromEntries(mappedParts);
/* const ret: {
  year: number;
  month: number;
  day: number;
} */

Is it worth all that?  I doubt it.  It's up to you though.
Playground link to code


text:
Q: ¿Cómo puedo graficar un intervalo de inecuaciones en python? Trato de graficar un intervalo de inecuaciones con matplotlib, quiero imprimir algo así:

Pero no he podido ni siquiera acercarme a lo que intento hacer, pero he hecho un esfuerzo, de la siguiente manera obtengo la gráfica a partir de la inecuación:
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10, 10, 100)
y = abs(-2*x-3>=13)
fig = plt.figure(figsize= (10,5))
plt.plot(x,y)
plt.show()

Y este es el resultado:

He buscado en stackoverflow en inglés y no he encontrado tampoco nada que se asemeje a lo que estoy buscando en concreto. ¿Existe algún método o forma de realizar lo que intento hacer? De antemano muchas gracias. Saludos.

A: Para hacer una gráfica como la que pides tendrías que comenzar por "despejar la x" de tu desigualdad, de modo que puedas decir dónde comienza y dónde termina la flecha roja que quieres pintar en los ejes. Este trabajo deberías hacerlo tú, pues dejar que lo haga Python puede ser muy complejo. Por ejemplo, en la desigualdad que tú planteas (-2x-3>=13) si despejas te queda x<=-8. Con esta información sabemos que queremos pintar una flecha que empiece en -8 y señale a la izquierda.
Pero aún sabiendo esto, para lograr el plot todavía hay que saber muchos trucos de matplotlib como los siguientes:

*

*Cómo eliminar todos los ejes que matplotlib pinta por defecto alrededor del plot

*Cómo colocar un eje X horizontal que pase por cero

*Cómo poner ticks en el eje X a intervalos de 1 unidad y que las marquitas de los ticks sean más largas de lo normal.

*Cómo dibujar una línea roja (o de otro color) entre dos puntos cualesquiera del espacio de coordenadas

*Cómo añadir una punta de flecha (o un triángulo que mire a izquierda o a derecha) en cualquier punto del eje x

*Cómo añadir un círculo rojo (o de otro color) en cualquier punto del eje X para marcar el extremo del intervalo, y cómo rellenar ese círculo de blanco o no según queramos marcar que el intervalo es abierto o cerrado en ese punto.

*Cómo hacer que estas cosas que hemos pintado en rojo (líneas, triángulos, círculos) aparezcan encima de los ejes (es decir, "tapándolos") y no debajo que es donde matplotlib las pintaría por defecto.

Todo esto es muy largo de explicar, por lo que me voy a limitar a darte el código de la función que lo hace todo (con comentarios para que no sea tan misterioso). La función recibe muchos parámetros pero todos ellos tienen valores por defecto. Más adelante daré ejemplos de cómo usarla para mostrar diferentes intervalos.
def plot_interval(title="Intervalo", start=float("-inf"), end=float("+inf"), start_open=False, end_open=False, x_axis=(-10, 10), color="red"):
  """Parámetros:
   - title: Lo que aparecerá encima de la gráfica
   - start: punto de la izquierda del intervalo a mostrar. Si no se especifica
       se usará -infinito
   - end: punto de la derecha del intervalo a mostrar. Si no se espeficica
       se usará +infinito
   - start_open, end_open: booleanos que indican si esos extremos son abiertos
       (por defecto son cerrados). Eso afecta al círculo que los representa
   - x_axis: valores a mostrar en el eje x, sobre los que se pintará el
       intervalo (por defecto el eje x va de -10 a +10)
   - color: color de la línea, flecha y círculo que representa el intervalo
  """

  # Crear la figura
  fig = plt.figure(figsize= (10,1))
  ax = fig.add_subplot(aspect=1)

  # Eliminar todos los bordes y preparar el eje x
  for borde in ["left", "top", "right"]:
    ax.spines[borde].set_visible(False)
  ax.spines["bottom"].set_position(("data", 0))
  ax.set_xticks(range(x_axis[0], x_axis[1]+1))
  ax.set_xlim(*x_axis)
  ax.tick_params(which="major", axis="x", direction="inout", length=8)

  # Dimensionar eje Y y quitarle los ticks
  ax.set_yticks([])
  ax.set_ylim(-1, 1)

  # Preparar algunas variables según los extremos de los intervalos
  # sean infinito o no. Las variables que se preparan son:
  # x0, x1 (puntos de inicio y fin de la línea roja)
  # x0shape, x1shape (si hay que poner un triángulo o círculo en cada extremo)
  if start==float("-inf"):
    x0 = x_axis[0]      # Punto en que comienza la linea roja
    x0shape = "arrow"
  else:
    x0 = start
    x0shape = "circle"
  if end==float("+inf"):
    x1 = x_axis[1]
    x1shape = "arrow"
  else:
    x1 = end
    x1shape = "circle"

  # Pintar la línea roja. El zorder=3 hará que se pinte encima del eje
  ax.plot((x0, x1), (0,0), color=color, clip_on=False, zorder=3)

  # Pintar los extremos del intervalo
  if x0shape == "arrow":
    # Si hay que pintar flecha, se pinta un triángulo ("<k")
    # El zorder=4 hará que se pinte encima de la línea roja
    ax.plot(x0, 0, "<k", color=color, markersize=10, clip_on=False, zorder=4)
  else:
    # Si no hay que pintar flecha, se pinta un círculo
    # facecolor es el color de relleno, que depende de si el extremo es abierto o cerrado
    c = plt.Circle((x0, 0), 0.2, edgecolor=color, facecolor="white" if start_open else color, clip_on=False, zorder=4)
    ax.add_patch(c)
  if x1shape == "arrow":
    ax.plot(x1, 0, "k>", color=color, markersize=10, clip_on=False, zorder=4)
  else:
    c = plt.Circle((x1, 0), 0.2, edgecolor=color, facecolor="white" if end_open else color, clip_on=False, zorder=4)
    ax.add_patch(c)

  # Finalmente añadimos el título
  ax.set_title(title)
  return ax

Ejemplos de uso
Nota, siempre paso un título a todos los casos y uso fórmulas TeX en el título, de ahí los signos de dólar. Observa también que no es necesario especificar todos los parámetros. Los que no se ponen toman su valor por defecto.
plot_interval(r"$(-\infty, \infty)$")

plot_interval(r"$(-\infty, -5)$", end=-5, end_open=True)

plot_interval(r"$[3, \infty)$", start=3)

plot_interval(r"$[3, 6)$", start=3, end=6, end_open=True, x_axis=(0,10))

Y finalmente, el caso de tu ejemplo:
plot_interval(r"$-2x-3\geq13$", end=-8, x_axis=(-12,2))

Bonus. Dejando que Sympy resuelva la desigualdad
Si te parece muy complicado despejar tú mismo la x de la desigualdad, puedes instalar Sympy, que es un procesador simbólico matemático de capacidades similares en cierta forma a las de Wolfram-Alpha.
Además, es muy sencillo integrar la solución que te da Sympy con la función que he mostrado antes. He aquí un ejemplo (fíjate que he usado > en vez de >= para que veas que se pinta correctamente el intervalo abierto):
from sympy.parsing.sympy_parser import parse_expr
from sympy import solveset, S, latex

ineq = parse_expr("-2*x-3 > 13")
interval = solveset(ineq, domain=S.Reals)

plot_interval(title=latex(ineq, mode="inline"),
              start=interval.start, end=interval.end,
              start_open=interval.left_open, end_open=interval.right_open,
              x_axis=(-12, 5),
              color="coral")

Resultado:

A: Buen día,
Lo que podrías hacer es generar un arreglo donde todos los valores de 'Y' sean cero así podrás tener una gráfica sobre el eje 'X'
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10, 10, 100)
val = 0
fig = plt.figure(figsize= (10,5))
plt.plot(x, np.zeros_like(x) + val, '->')
plt.show()

El código es simple, val = 0 es la posición sobre el eje 'Y' donde deseas que se muestre la gráfica
np.zeros_like(x) define un arreglo donde todos los valores para 'Y' son cero. funciona de forma similar a np.zeros pero la ventaja de zeros_like es que puedes indicar la "forma" o el caracter que mostrará la gráfica en este caso -> mostrará una flecha apuntando a la derecha (Que podrías utilizar para indicar la dirección)


text:
Q: AngularJS: Hide button after click New to Angular and struggling with how to do things the "Angular Way". All I want to do is click a button to show a hidden element inside a view then hide the button that was clicked. Any help would be awesome.
HTML:
<button class="btn btn-primary" ng-click="showDiv=true; hideMe()">
  Show Div
</button>
<div ng-show="showDiv">
  I was hidden now you see me, but how do I hide the button?
</div>

Controller:
  $scope.hideMe = function(){
    console.log('hide the button');
    $scope.hide();
  }

Code sample: Plunker
Ideally would like to incorporate ng-hide on the button and not have a function run inside of the controller.

A: <button ng-hide="showDiv"...

Should work also

A: Just add ng-show="!showDiv" to your button, this will hide it if showDiv = true
Just to be clear new html should look:
<button class="btn btn-primary" ng-click="showDiv=true" ng-show="!showDiv">Show Div</button>


text:
Q: How to setup nginx with opencart 1.5.5? It is possible to use nginx with OpenCart? I am using following nginx zone:
server {
        listen 80;
        listen [::]:80;

        root /home/username/Development/shop.local;
        index index.php;

        server_name shop.local;

        location /image/data {
                autoindex on;
        }

        location /admin {
                index index.php;
        }

        location / {
                try_files $uri @opencart;
        }

        location @opencart {
                rewrite ^/(.+)$ /index.php?_route_=$1 last;
        }

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }

        # Make sure files with the following extensions do not get loaded by nginx because nginx would display the source code, and these files can contain PASSWORDS!
        location ~* \.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|\.php_ {
                deny all;
        }

        # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
        location ~ /\. {
                deny all;
                access_log off;
                log_not_found off;
        }

        location ~*  \.(jpg|jpeg|png|gif|css|js|ico)$ {
                expires max;
                log_not_found off;
        }

        location ~ \.php$ {
                try_files $uri =404;
                include fastcgi_params;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
}

But when i visit shop.local i am getting redirecto to shop.local/install/index.php and nginx throws me an error 404. What's wrong with my config?

A: Try this one:
# FORCE WWW
server {
    server_name  site.com;
    rewrite ^(.*) http://www.domain.com$1 permanent;
}
# MAIN SERVER
server {
    server_name  www.domain.com;
    listen 80;
    root /var/www/www.domain.com/public;
    index index.php index.html;
    location /image/data {
        autoindex on;
    }
    location /admin {
        index index.php;
    }
    location / {
        try_files $uri @opencart;
    }
    location @opencart {
        rewrite ^/(.+)$ /index.php?_route_=$1 last;
    }
    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }
    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }
    # Make sure files with the following extensions do not get loaded by nginx because nginx would display the source code, and these files can contain PASSWORDS!
    location ~* \.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|\.php_ {
        deny all;
    }
    # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
    location ~*  \.(jpg|jpeg|png|gif|css|js|ico)$ {
        expires max;
        log_not_found off;
    }
    location ~ \.php$ {
        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}


text:
Q: JSF sample project managed beans error, unable to print managed beans message to html I started to implement a very basic JSF application but i am unable to print the JSF Managed Beans message to html..
Here is my code :
HelloWorld.java :
package com.project.managedbeans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean(name="helloWorld", eager=true)
@RequestScoped
public class HelloWorld {

private String message;

public HelloWorld(){
    System.out.println("Hello World Managed Bean is created");
}

public String getMessage(){
    return "Hello World ! ";
}

public void setMessage(String message){
    this.message = message;
}

index.html :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<body>
#{helloWorld.message}

</body>
</html>

faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>

<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"
version="2.1">

</faces-config>

and web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-  app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>jsfSampleProject</display-name>
<welcome-file-list>
 <welcome-file>index.html</welcome-file>
 <welcome-file>index.htm</welcome-file>
 <welcome-file>index.jsp</welcome-file>
 <welcome-file>default.html</welcome-file>
 <welcome-file>default.htm</welcome-file>
 <welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
 <servlet-name>Faces Servlet</servlet-name>
 <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
 <servlet-name>Faces Servlet</servlet-name>
 <url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<context-param>
 <description>State saving method: 'client' or 'server' (=default). See JSF   Specification 2.5.2</description>
 <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
 <param-value>client</param-value>
</context-param>
<context-param>
 <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
 <param-value>resources.application</param-value>
</context-param>
<listener>
 <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>

and when i run the application on apache server, the page i see under
localhost:8080/jsfSampleProject/   is :
#{helloWorld.message}
I have JSF 2.1 Mojorra under Libraries tab. What do you think the problem is ?
Thanks.

A: The problem is that welcome file list accepts file names that are physically present in your web app, and that is index.xhtml. Note that none of your welcome files match that condition.
Next, your file is not handled by the FacesServlet. That is, requested URL does not correspond to the servlet URL mapping in your web.xml. Note that your mapping *.jsf doesn't match your requested files as well.
All in all, the following excerpt from web.xml will solve your problem:
<welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

Of course, you'll need the file index.xhtml at the root of your web application.


text:
Q: Attempting to add external CSS to npm live server   <link rel="stylesheet" type="text/css" href="Downloads/folder/css/default.css">

When trying to run a live server, no external CSS elements appear in the HTML file. The elements are visible when running index.html directly, and clicking on it directed me to the proper location.
Tried:
-Global and relative location
-Backslashes
-live-server dist, returned "Cannot get /"


text:
Q: Как сделать вертикальную стопку карт (UserControls) в WPF C# Нужно сделать стопку карт как на картинке посредством технологии WPF. посоветуйте какой лучше использовать инструмент для наложения карт друг на друга как на картинке. Буду благодарен, за ваши идеи!

A: Ну, это весьма простая задачка, но есть свои тонкости.
AlternationCount
В WPF, у ItemsControl и его аналогов, есть такой механизм, как AlternationCount, который позволяет нам задать определенный вид элементам, чередуя это значение.
Сделаем простой пример:
<ListBox AlternationCount="2" ItemsSource="{Binding Items}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                    <Setter Property="Background" Value="Green"/>
                </Trigger>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Как видите, тут стоит AlternationCount="2", это означает, что при добавлении объекта, ListBox будет вести отсчет (0, 1, 0, 1, 0, 1), вот 2, это после какого числа, отсчет пойдет по новой. В стиле как видите есть триггер, который и проверяет AlternationIndex, задавая нужный стиль объектам. Этот простой пример, даст нам следующий результат:

Поворот объектов
Всякие изменения (растягивание, масштабирование, повороты и др.) в WPF делаются через RenderTransform, а конкретно за повороты отвечает RotateTransform со свойством Angle.
Простой пример:
<Rectangle Width="100" Height="100" Fill="Black">
    <Rectangle.RenderTransform>
        <RotateTransform Angle="10"/>
    </Rectangle.RenderTransform>
</Rectangle>

Даст нам такой результат:

Я не просто так оставил выделение, тут наглядно показывает цент, от которого и будут происходить все изменения. Конкретно в этом случае он 0 0, то есть верхний левый угол. Не забывайте про этот момент, его стоит учитывать при вращение! В качестве подсказки дам ссылку на документацию.
Реализация задачи
Поняв эти две вещи, мы теперь смело можем пытаться решить поставленную задачу.

*

*Для удобства сделаем UserControl, который будет имет нужный нам вид.

*

*Правой кнопкой по проекту, добавить, UserControl.

*Обзываем его как нужно (я назвал SomePanel).

*В XAML пишем нужный нам вид. Я тут лично просто взял рамку с вашего скрина, получил следующее:
 <UserControl.Template>
     <ControlTemplate TargetType="UserControl">
         <Grid>
             <Border CornerRadius="10" Background="White" Margin="10" BorderThickness="1">
                 <Border.Effect>
                     <DropShadowEffect BlurRadius="5" ShadowDepth="0" Opacity=".4"/>
                 </Border.Effect>
             </Border>
             <Border CornerRadius="10" ClipToBounds="True" Margin="10" BorderThickness=".5" BorderBrush="#FFCDCDCD">
                 <Border.Background>
                     <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                         <GradientStop Color="#fae81b"/>
                         <GradientStop Color="#f9e918" Offset="1"/>
                     </LinearGradientBrush>
                 </Border.Background>
                 <Grid>
                     <Grid.RowDefinitions>
                         <RowDefinition Height="30"/>
                         <RowDefinition/>
                         <RowDefinition Height="20"/>
                     </Grid.RowDefinitions>
                     <StackPanel Grid.Row="0">
                         <!-- Верх -->
                     </StackPanel>
                     <Border Grid.Row="1" Background="White" BorderThickness="0 1" BorderBrush="#FFE2E2E2">
                         <!-- Тело -->
                         <ContentPresenter />
                     </Border>
                     <StackPanel Grid.Row="2">
                         <!-- Низ -->
                     </StackPanel>
                 </Grid>
             </Border>
         </Grid>
     </ControlTemplate>
 </UserControl.Template>

*Если надо, делайте свойства, привязывайте и улучшайте его вид.

*Начинаем работать с ListBox или ItemsControl:

*

*Переписываем ItemTemplate. Цель проста, указать контролу, какой вид ему использовать (наш контрол):
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <local:SomePanel Width="250" Height="300" Content="{Binding}"/>
    </DataTemplate>
</ItemsControl.ItemTemplate>

*Перепишем ItemsPanel. Цель этого действия, переопределения того, как объекты будут размещаться (друг под другом, в одну строку, друг за другом и др.). Конкретно в нашем случае нам надо чтоб они размещались все в одной точке, накладываясь друг на друга слоями, а это делает Grid.
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <Grid />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

*Теперь самое интересное ItemContainerStyle, нам нужно в нем указать триггеры, которые и будут наклонять объекты.
<ItemsControl.ItemContainerStyle>
    <Style TargetType="ContentPresenter">
        <Style.Triggers>
            <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                <Setter Property="LayoutTransform">
                    <Setter.Value>
                        <RotateTransform CenterX=".5" CenterY=".5" Angle="5"/>
                    </Setter.Value>
                </Setter>
            </Trigger>
            <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                <Setter Property="LayoutTransform">
                    <Setter.Value>
                        <RotateTransform CenterX=".5" CenterY=".5" Angle="-5"/>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
</ItemsControl.ItemContainerStyle>

*А, ну и не забываем задать AlternationCount, у меня он сейчас 3
Собственно, уже у нас должен получиться нужный (почти) нам результат

Как видите, наши карточки успешно отображаются и поворачиваются. Но есть одно "но", думаю заметили, первый объект тоже крутится, что, по-вашему, скрину не так, ну и задние у вас более бледные (прозрачность). Тут, честно, я без понятия как грамотно отследить какой объект на переднем плане, сделал следующее:

*

*Нам нужен IMultiValueConverter, который сравнит текущий объект с тем, что последний в коллекции. На просторах нашел следующую реализацию:
 public class EqualityConverter : IMultiValueConverter
 {
     public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
     {
         int count = (int)values[2];

         if (values != null && values.Length == 3 && count > 0)
         {
             ItemsControl itemsControl = values[0] as ItemsControl;
             var itemContext = (values[1] as ContentPresenter).DataContext;

             var lastItem = itemsControl.Items[count - 1];
             return Equals(lastItem, itemContext);
         }

         return DependencyProperty.UnsetValue;
     }

     public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
     {
         throw new NotImplementedException();
     }
 }

*Подключаем его (ну либо делаем расширением):
 <Window.Resources>
     <local:EqualityConverter x:Key="EqualityConverter" />
 </Window.Resources>

*На основе этого конвертора, делаем новый триггер:
 <DataTrigger Value="True" >
     <DataTrigger.Binding>
         <MultiBinding Converter="{StaticResource EqualityConverter}">
             <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}" />
             <Binding RelativeSource="{RelativeSource Self}"/>
             <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}" Path="Items.Count"/>
         </MultiBinding>
     </DataTrigger.Binding>
     <Setter Property="LayoutTransform">
         <Setter.Value>
             <RotateTransform CenterX=".5" CenterY=".5" Angle="0"/>
         </Setter.Value>
     </Setter>
     <Setter Property="Opacity" Value="1"/>
 </DataTrigger>

*В ранее созданных триггерах прописываем изменение Opacity, чтоб задние объекты были более блеклыми (<Setter Property="Opacity" Value=".5"/>). Хотя, изменение прозрачности тут не лучший вариант, ибо, наложив друг на друга полупрозрачные объекты, мы получим опять нормальный цвет. Так что, тут лучше поиграйтесь с цветами, стилями.
В итоге мы получаем следующее:

Вот теперь мы получили +- то, что вам нужно. Но тут есть несколько но:

*

*Цвет задних объектов. Как я уже говорил, прозрачность, это не лучший вариант!

*Логика в IMultiValueConverter. Она не самая лучшая, если у вас будет, к примеру подряд несколько одинаковых объектов, то они будут стоять ровно, хотя должны повернутся.

В любом случае, один из вариантов того, как подобное реализовать я вам показал, остальное за вами.


text:
Q: A way to get the IP address of a user in Firebase Authentication? Does Firebase log the IP address that the user last signed in from?
The reason that I need it is that I want to try to broadly segment my users by location, and IP address will usually help with this.
But I'm not sure if the data exists in Firebase or is query-able.

A: Nope. Firebase Authentication does not make the IP address of the user available. See Firebase JavaScript SDK - Retrieve Users IP Address
But what you describe sounds like a use-case better suited to Firebase Analytics/Google Analytics for Firebase, which does expose the user's location (based on a lookup from their IP address).


text:
Q: Change jquery slider background-color on the left side of the first handle I have a jquery range-slider, but now I want to add an extra function to it.
I want the left side of the handle to be another color than the right side.
I made a little mock-up so it's clear what I mean.

I already found a way to get the minimum value:
$(".sleep").slider("option", "min");

and I found the code for getting the value from the first slider
$(".sleep").slider("values", 0)

But now I'm kinda stuck how to continue. Hope someone can help me!
Edit:
created a jsfiddle page to make it a little bit easier: http://jsfiddle.net/BxY99/12/

A: Got it Kim,
http://jsfiddle.net/BxY99/14/
Wondering how I got 8.6? I have not the remotest clue, pure trial and error. I'd recommend using a percentage width of some kind, but I can't seem to figure out a formula that might work.
Here's an explanation,
CSS for the left end of the slider, emulating the jQuery slider,
.customMarker {
    display: block;
    font-size: 0.7em;
    position: absolute;
    z-index: 1;
    background-color:#ff0000;
    top:0;
    left:0;
    height:100%;
}

We append the marker to the slider and handle the slide event to set its width.
var slideVal = 0;
$(".sleep").slider({
          range: true,
          min: 0,
          max: 2879,
          values: [540, 1020],
          step:5,
          animate: true,
          slide: function(event, ui) {
            slideVal = $(".sleep").slider("values", 0) / 8.6;

    $('#values').text(slideVal);
    $('.customMarker').css('width', slideVal + 'px');
}
});

$('.sleep').prepend("

");

A: If you are using http://docs.jquery.com/UI/API/1.8/Slider then I do not think that is possible without changing the actual implementation. That one is made up of a single Div element from left to right


text:
Q: All UI elements in apps ugly and grey (14.04) I did a clean install of Ubuntu 14.04 LTS.
I'm having a weird problem that I can't find any mention of online. Basically, all UI elements in apps look grey, Windows 98-style.
 (Gparted)
 (Geany IDE)
 (Firefox file upload)
Functionally everything is fine, but it just looks ugly. Unity,the desktop and the login screen look completely normal. Logging out and back in fixes the issue, but it comes back after rebooting.

A: This right here is an easy fix.
All you have to do is go to the software center and install Ubuntu tweak.

*

*Open that up and go to "Tweaks"

*Go to "Theme"

*In there, change the Gtk theme to whatever you like.

That should fix it up no problem

A: There might be many reasons for this problem, but it can typically be fixed by re-configuring your themes. You can start by tweaking the theme in unity-control-center and making sure it is set to Ambience. If it is, try switching the theme to a different one and back. You can also try reinstalling the themes as suggested in this answer: https://askubuntu.com/a/141375/341801 for 12.04.

A: Have you tryed use software-center and install tweak tool, and you run tweak tool and set the window and icons to something else, and it should look better then grey, and you should install gnome system settings, and there you can also set settings, and it might work fine this way.

A: You can have a theme misconfiguration. Try this:

*

*Go to the gear cog that is on the top-right corner on the screen.

*Select System Settings from the menu.

*On the system settings, click on Appearance

*In the bottom-right of this window, you have a theme selector. If Ambiance is selected, select another theme. You may need to wait a few seconds until the new theme applies.

*Select Ambiance theme again.

A: I had this same problem (It didn't always happen) and found that it's somehow related to my graphics driver. The way to solve it was to, at startup time, stay at the login screen for about 45 seconds to a minute. Something "clicks" in X.org that allows it to go into the high graphics mode and load the nice looking theme.
I posted the related question over here: https://askubuntu.com/questions/628141/multiple-monitor-configuration-is-delayed-for-40-seconds-on-ubuntu-14-04-lts


text:
Q: Recentering \bar over to account for integral alignment I'm trying to write an integral with upper and lower bounds denoted with over- and under-bars respectively. The issue is that because the integral is slanted, it makes it hard to line up the symbols correctly. \underaccent works beautifully (maybe accidentally) to line up the letter and the bar, but \bar puts the accent too far to the left. See below
    \documentclass{beamer}
    \usepackage{amsmath}
    \usepackage{accents}
    \begin{document}
    \begin{frame}{My Integral}
    \[
    \int_{\underaccent{\bar}{c}}^{\bar{ c}} x(c_j) dF(c_j)
    \]
    \end{frame}
    \end{document}

It seems like there should be a way to move the bar over... but my attempts to recenter the bar using added white space were foiled by math mode's removal of spaces. I'd love to hear your thoughts.

A: I'm not sure what the notation should mean.
Anyway, there are much simpler examples to see that this does not depend on the integral sign.
\documentclass{beamer}
\usepackage{amsmath}
\usepackage{accents}

\begin{document}

\begin{frame}
\[
\bar{c}+\underaccent{\bar}{c}
\]
\end{frame}

\end{document}

Compare with
\documentclass{article}
\usepackage{amsmath}
\usepackage{accents}

\begin{document}

\[
\bar{c}+\underaccent{\bar}{c}
\]

\end{document}

The fact is that the font used for letters in math mode is not tailored for being used in math, so the internal mechanism fails to properly move the \bar over the characters.
You get better results with arev:
\documentclass{beamer}
\usepackage{amsmath}
\usepackage{accents}
\usepackage{arev,arevmath}

\begin{document}

\begin{frame}
\[
\bar{c}+\underaccent{\bar}{c}
\]
\end{frame}

\end{document}

If you're very fussy about the placement, you can use, also in your code, \skew:
\documentclass{beamer}
\usepackage{amsmath}
\usepackage{accents}
\usepackage{arev,arevmath}

\begin{document}

\begin{frame}
\[
\skew{2}\bar{c}+\underaccent{\bar}{c}
\]
\end{frame}

\end{document}

Your original example:
\documentclass{beamer}
\usepackage{amsmath}
\usepackage{accents}

\begin{document}

\begin{frame}
\[
\int_{\underaccent{\bar}{c}}^{\skew{3}\bar{c}}x(c_j)\,dF(c_j)
\]
\end{frame}

\end{document}

(don't forget the thin space in front of the differential).

A: The sansmathaccent package (which in a modern distribution is already loaded by default by beamer) corrects the default bad placement of math accents for sans-serif letters, see Bad positioning of math accents for the beamer standard font. However, the accents package re-implements the math accents, thus destroying the effect of sansmathaccent; in order to avoid this, the accents package can be loaded with the single option. To try and correct the effect of \underaccent one may insert some kerning, such that accents does not try to shift the \bar in the "correct" (from its point of view) position:
\documentclass{beamer}

\usepackage{amsmath}
\usepackage[single]{accents}
\newcommand*{\ubar}[2][0.5]{\underaccent{\bar}{\mkern-#1mu #2 \mkern#1mu}} % optional argument for fine tuning
% \usepackage{sansmathaccent} % shouldn't be necessary nowadays

\begin{document}
\begin{frame}{Accents}
\[
\bar{c} \quad \ubar{c} \quad \int_{\ubar{c}}^{\bar{c}} x(c_j)\,dF(c_j)
\]
\end{frame}
\end{document}

A: Quick and dirty:
\documentclass{beamer}
\usepackage{amsmath}
\usepackage{accents}
\newcommand{\mybar}[1]{\bar{#1\hphantom{\:}}\mkern-4mu}
\begin{document}
\begin{frame}{Accents}
\[
\int_{\underaccent{\bar}{c}}^{\mybar{c}} x(c_j)\,dF(c_j)
\]
\end{frame}
\end{document}


text:
Q: How to find lines with certain numbers So I have this file that I want to find only the lines that contain a certain phrase followed by a nonzero number. I'm thinking using grep, but I'm not sure how to format it to ignore zeroes. A line would be like this:
2009-12-05 : Reindexing 100: [result]
2009-12-07 : Reindexing 0: [result]

And I only want the first line.
Thank you in advance.

A: To get the first match of the phrase Reindexing followed by a non-zero number, use (GNU grep):
grep -m1 'Reindexing [1-9]' < input

A: If you really mean any "nonzero number", i.e. want to handle:

*

*negative numbers,

*fractions - including 0 < n < 1 (with leading '0')

you need something more powerful than grep. E.g.:
echo '2009-12-05 : Reindexing -0.7: [result]' | perl -ne 'print if /Reindexing -?(\d+(\.\d+)?+)(?!\w)/ and $1!=0'

This solution would also exclude strings like "100abc", which are not numbers: the "(?!\w)" part is negative lookahead meaning "not followed by word character". Altering the condition at the end you can make any filtering you like.


text:
Q: Calculating the total of numbers input in a field UPDATE
Hi again,
Unfortunately it doesn't work.
Here's what I've done:
1 - I've created 1 column called "Nr of hours" as Number column with no other settings. This column is included in my Edit Form where I go to put how many hours I worked on something.
2 - I've created another column called "TotHours" as Number column with defalut value 0.
3 - In SPD, I've created a variable called "VarTotHours" as String
4 - Also in SPD, I made a workflow that goes like

Calculate "Nr of hours" plus "TotHours"(output var "VarTotHours")
then Set "TotHours" to "VarTotHours"

Set it up to be activated when an item is changed.
Either it doesn't work at all or it multiplies or keeps on adding without sense.
Any idea why?
Thanks in advance.

I have a question:
In a list that we use as ticketing tool, I have a field where I have to input my working hours every time.
Right now we just change the number in the working hours field everytime, but is there a way in which I can just input a number in that field and having another one where all the numbers that I input are being added to?
Thanks in advance!
Laura

A: This is not possible using Calculated columns as calculated columns does not allow circular reference(reference to same column itself).
Solution:
However you can achieve this easily using Workflow.
You can implement one workflow on item created and changed events and calculate the Total working hours each time you edit the list item.
Update:
You can create a SharePoint designer 2013 list workflow on your list.

*

*Create two number fields NoOfHoursWorked and TotalHoursWorked. Set default value of this column to 0.

*Create SharePoint designer 2013 List workflow on On create and edit events.

*In your workflow use Calculate action to perform addition of NoOfHoursWorked and TotalHoursWorked.

*Update TotalHoursWorked field with the result of the addition.

For Reference:
In below example they have used calculate action for multiplication, similary you can use for addition.
How to perform Calculations in workflow


text:
Q: SQL Get lowest level child and root node I have database schema: [Id], [ParrentId], [some more tables]
I have hierarchy like:
1. a
 2. aa
  3. aaa_1
  3. aaa_2
1. b
 2. bb
1. c
 2. cc
  3. ccc_1
   4. cccc
  3. ccc_2

I want a (select * where X) => [X, lowest leve child] like:
[a, aaa_1] [a, aaa_2]; [cc, cccc] etc.
I can get lowest child with
SELECT t1.name FROM
category AS t1 LEFT JOIN category as t2
ON t1.category_id = t2.parent
WHERE t2.category_id IS NULL;

but I don't know how to join it with root node.

A: Given:

*

*The DBMS is SQL Server;

*The highest level nodes of the tree have parent = NULL;

*You want all the lowest leaves for all levels of the trees, not just the roots;

*You want to have all the nodes at a lowest level, not just one;

This query would do it:
WITH r ( category_id, name, root, depth )
-- finds the root relationship
AS (
    SELECT category_id, name, category_id, 0
        FROM category
        -- WHERE parent IS NULL -- this would only look at root nodes
    UNION ALL
    SELECT c.category_id, c.name, r.root, r.depth + 1
        FROM r
        JOIN category c
            ON c.parent = r.category_id
), s ( category_id, name, root, window_id )
-- finds the lowest leaves
AS (
    SELECT category_id, name, root, RANK() OVER(partition by root order by depth DESC)
        FROM r
)
SELECT c.name AS NodeName, s.Name AS DeepLeafName
    FROM category c
    JOIN s
        ON c.category_id = s.root
        WHERE s.window_id = 1;

Here is the result set:

A: With SQL Server, you can try this :
With CTE as
(
Select ID as Child, lev = 1
from category
where ID = X
UNION ALL
Select category.ID, CTE.lev + 1
from category
    inner join CTE ON category.ParentID = CTE.Child
)

select CTE_1.Child, CTE_2.Child
from CTE as CTE_1
    inner join CTE as CTE_2
where CTE_1.lev  = 1 AND CTE_2.lev = (select MAX(CTE.lev) from CTE)