text:
Q: which user runs my asp.net user? i've always read that the user you set in the IIS website/virtual directory is the user that runs the app (anonymous user identity)
But in the application pool, i can also set a user (process model, identity)
what is the difference between the two, and which one will need access if i do a file read?
EDIT:
the bounty is for this quesyion ' but if i use 'anonymous authentication', is the user i choose in the 'anonymous user identity' ever used? – ' posted as comment

A: Checkout this post. Quote:

The two accounts are different things.
  Think of the website identity
  representing the user of the site. If
  you create a new website this account
  is the anonymous IIS account. If you
  disable "Anonymous Authentication",
  your users will have to authenticate
  against the website (in a
  intranet/Windows domain site this
  could be implicite using the network
  credentials.)
The application pool identity is the
  Windows account needed for running
  your assemblies. Normally it is the
  "Network Service" account which is a
  least privileged account with limited
  user rights and permissions. It does
  have network credentials. This means
  that you can use it to authenticate
  against network resources in a domain.
  You can also use it to access a SQL
  Server database with integrated
  security.
For example, if your ASP.NET
  application has to write to a folder,
  you have to grant the permission to
  the application pool account, not to
  the website account. For more
  information on application pool
  identities, read here.

A: Think of the website identity as a rule that defines who can access the site. If you specify an anonymous account to use, that account must have access to the site. If anonymous access is disabled, then the user's credentials must have access to the folder.
The app pool identity defines what the application can do. The app pool's worker process will run using the app pool identity; that account must be granted access to any resources (SQL Server, file shares, etc) that the app will need to access.
To answer your question: yes, the anonymous account is used. Think of the scenario where you're hosting a hundred web sites, and you don't want one customer's files to be able to access another's. You would assign separate anonymous access to each customer. Each site's anonymous account allows IIS to access only the files relevant to that particular site (provided you've configured that account's access correctly).

A: @Michel
if you have an Anon Access Account setup on your site (virtual dir)
AND you have
<system.web>
   <identity impersonate="true" />
</system.web>

in your web.config, this will use that identity.
if you have a part of code where you can set the credentials
CredentialCache.DefaultCredentials
this will point to the Anon Account,if you want to test what user you are using try
Thread.CurrentPrincipal.Identity.Name.ToString()

have a look at this post for more information
http://blogs.iis.net/sakyad/archive/2008/11/19/process-and-thread-identity-in-asp-net-a-practical-approach.aspx


text:
Q: how to combine date and time in c# I have 2 values:
var dt1 = dtFromDate.Value;
var tm1 = tmFromTime.Value;

dt1 = 12/5/2013 12:00:00 AM

tm1 = 11/5/2013 9:00:00 AM

i want to make datetime as  : 12/5/2013 9:00:00 AM
how can it be possible?

A: You can take the date part of dt1 by accessing Date, the time part of tm1 by accessing TimeOfDay and then combine them using +:
dt1.Date + tm1.TimeOfDay

A: You can create a new DateTime using overloaded constructor:
DateTime dt = new DateTime(
                    dt1.Year,
                    dt1.Month,
                    dt1.Day,
                    tm1.Hour,
                    tm2.Minute,
                    tm2.Second,
                    tm2.Millisecond);

A: You can use that code, using Date property to get just date part and Time property to get just time part:
var dt1 = DateTime.Parse("12/5/2013 12:00:00 AM"); // this is just a sample date
var tm1 = DateTime.Parse("11/5/2013 9:00:00 AM"); // this is just a sample date

var newDate = dt1.Date.Add(tm1.TimeOfDay); // the code to use

A: DateTime object is immutable so in order to get the date from one DateTime object, but the time from another - you must create new DateTime object.
There is two ways for doing it:
Create new DateTime with constructor overload:
DateTime date1 =
    new DateTime(dt1.Year, dt1.Month, dt1.Day, tm1.Hour, tm1.Minute, tm1.Second);

Parse string to DateTime:
var dateToParse =
      String.Concat(dt1.ToString("yyyy.MM.dd ", CultureInfo.InvariantCulture),
                    tm1.ToString("HH:mm:ss", CultureInfo.InvariantCulture));
var date1 =
      DateTime.ParseExact(dateToParse, "yyyy.MM.dd HH:mm:ss", CultureInfo.InvariantCulture);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Executing batch file on remote system using Java How to execute a batch file located on Windows remote system? Batch file should run on remote system.

A: Abhinav,
        For your problem I see RMI is the quickest possible solution

*

*Check out the basics from these links (1,2)

*Start the server from where you want to run the batch

*In the Remote object on the server side Use Runtime.getRuntime().exec() to run your batch.

*From the client machine give call to this remote object and method.

A: Another approach is to use SSH like sshj. This only requires the remote system to have SSH installed and is more secure than RMI.

A: You can use Jsch and Expect4j for executing commands on remote machine(window/Linux). Further more, if your system allows, transfer the batch file on remote machine using some FTP utility like Apache Commons Net and then execute commands that executes the script.


text:
Q: NodeJS server failed to load JavaScript modules SO citizens. I'm using Node.js with Express.js for the server side of web application. And I often encounter problem when webserver is trying to bind references from the source code.
The structure of my app is:
src/
  - static/
     - calendar.js
     - client.js
     - planner.js
     - index.html
  - utils/
     - planListItem.js
     - selectedDates.js
  - index.js
  - server.js

In index.js
import app from "./server.js"
In server.js
I register an endpoint "/" with callback function that sends back an html file via res.sendFile() function passing in absolute path to index.html.
Inside index.html
<html>
  <head>...</head>
  <body>
     ...
     <script type="module" src="./client.js"></script>
  </body>
</html>

Server successfully load scripts so far. But then
client.js
import { initCalendar } from "./calendar.js"

calendar.js
import Planner from "./planner.js";
import selectedDays from "../utils/selectedDates"

planner.js
import {PlanListItem} from "./../utils/planListItem.js";

Enough with the structure:)
The problem is, I suppose, in how Express is routing static files, because source code reference were checked 1000 times and are correct.
To defend myself from sully suggestions, I added the following script inside server.js beforehand app.use(express.static("src/static")). Which was supposed to help serving scripts. But unfortunately browser responds
It's obvious that Node can't find selectedDates.js and planListItem.js in utils/. What should I do to make Node find this files???

A: You need to serve utils, too. You can add
app.use('/utils', express.static("src/utils"))

after
app.use(express.static("src/static"))

All paths inside the HTML document are evaluated on the browser. The browser sends a request for each import. You server has to handle these requests.


text:
Q: Angular:.Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema I just startred programing and in my first project on Angular i tried to use ng serve an then this error come out:
initialized using a configuration object that does not match the API schema.
 - configuration.cache.cacheDirectory: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba
proyecto\\Prueba\\.angular\\cache\\13.3.5\\angular-webpack" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
   -> Base directory for the cache (defaults to node_modules/.cache/webpack).
 - configuration.context: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
   -> The base directory (absolute path!) for resolving the `entry` option. If `output.pathinfo` is set, the included pathinfo is shortened to this directory.
 - configuration.module.rules[9] should be one of these:
   ["..." | object { assert?, compiler?, dependency?, descriptionData?, enforce?, exclude?, generator?, include?, issuer?, issuerLayer?, layer?, loader?, mimetype?, oneOf?, options?, parser?, realResource?, resolve?, resource?, resourceFragment?, resourceQuery?, rules?, scheme?, sideEffects?, test?, type?, use? }, ...]
   -> A rule.
   Details:
    * configuration.module.rules[5].rules[0].oneOf[0].include[0]: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba\\src\\styles.css" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
    * configuration.module.rules[5].rules[0].oneOf[0].include[0]: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba\\src\\styles.css" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
    * configuration.module.rules[6].rules[0].oneOf[0].include[0]: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba\\src\\styles.css" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
    * configuration.module.rules[6].rules[0].oneOf[0].include[0]: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba\\src\\styles.css" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
    * configuration.module.rules[7].rules[0].oneOf[0].include[0]: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba\\src\\styles.css" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
    * configuration.module.rules[7].rules[0].oneOf[0].include[0]: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba\\src\\styles.css" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
    * configuration.module.rules[8].rules[0].oneOf[0].include[0]: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba\\src\\styles.css" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
    * configuration.module.rules[8].rules[0].oneOf[0].include[0]: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba\\src\\styles.css" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
    * configuration.module.rules[9].rules[0].oneOf[0].include[0]: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba\\src\\styles.css" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
    * configuration.module.rules[9].rules[0].oneOf[0].include[0]: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba\\src\\styles.css" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
 - configuration.output.path: The provided value "D:\\!!!!YoProgramo2\\!!!! Trabajos Argentina programa\\Pruebas Angular\\Prueba proyecto\\Prueba\\dist\\prueba" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
   -> The output directory as **absolute path** (required).
See "C:\Users\esteban\AppData\Local\Temp\ng-jt7xXe\angular-errors.log" for further details.

i dont really undestand whats happening, i checked the styles confing at the angular.json and it this:
            "styles": [
              "src/styles.css"
            ],

and both the styles.css and app.component.css are empty, i don't have any code there.
I looked at the webpack.config.js and the code in there is this one:

const path = require('path');

module.exports = {
    entry: path.resolve(__dirname, 'src/index.js'),
    output: {
        path: path.resolve(__dirname, 'assets'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                }
            }
        ]
    }
};

A: The issue is with your path. Exclamation marks (!) are not tolerated at the moment. Move the project folder to path without exclamation marks is your solution.
Wrong:
D:\!!!!YoProgramo2\!!!
Correct:
D:\YoProgramo2\yourProject


text:
Q: Best away to distinct a list of objects by two fields equals with sqlalchemy I have some duplicated records in my database with different Ids, like:
id      | title         | date              |flag |
--------+---------------+-------------------+-----+
    2099|Test           |2022-11-29 00:00:00| 1   |
    2100|Test           |2022-11-29 00:00:00| 1   |
    2101|Test           |2022-11-29 00:00:00| 1   |
    2102|Test           |2022-11-29 00:00:00| 1   |

and this is the code to get all records from my database:
event_get = Event.query.filter(Event.flag == 1)
result = events_schema.dump(event_get)
data = dict(event=result)

I wanna distinct the results by title and date, so as the example with four records, I would have all of them with the same title and date, returning only one record
I did not find a way of do this with sqlalchemy, is It possible or I would need to use a alternative code in the returned list?

A: Pass the columns to distinct() to generate distinct on like this:
events = session.query(Event).distinct(Event.title, Event.date).filter(Event.flag == 1).all()

This uses a subquery that finds the smallest id for each group of title/date.  The main query then only returns events with ids in that subquery.  I guess check and see if this works in mysql.  My small test seems to work.
from sqlalchemy.sql import select, func
subq = select(func.min(Event.id)).group_by(Event.title, Event.date)
events = session.query(Event).where(Event.id.in_(subq)).all()

Also if you just need those exact values you can probably just use regular DISTINCT like this:
for (title, date) in session.query(Event.title, Event.date).distinct().all():
    print (title, date)


text:
Q: How to set Visual Studio Code terminal to UTF-8 on windows I'm trying to use a bunch of box drawing characters from UTF-8 to make a grid, and I can't seem to get them to display properly in my terminal. The characters in the text editor vs the output
I've got my text editor encoding set to UTF-8 so I can see the right characters in the editor, but the terminal sets them all to '?'. I'm using gradle to build, and passing -encoding UTF-8 as an argument to the compiler, and I've also run chcp 65001 in the terminal before compiling and running.
Update: By removing -encoding UTF-8 from the compile args it now works for all characters except ━ (\u2501) for some reason, which displays as �?�?�?


text:
Q: Automatic Multiple Image switch with different links on each IMG Background:
Finding improved ways to use CSS, I came across the proposition of using image transitions for good effects.
After a few stumbles, I managed to do this with the help of some references to make a smooth transition in hover.
Now I want it automatic and with links in each picture, but I'm at a loss at the code.
Current JSFiddle:
None, JSFIDDLE doesn't accept IMG and I can't show there.

.container
{
  position:relative;
  height:500px;
  width:500px;
  margin:0 auto;
}

.container img
{
  position:absolute;
  transition: opacity 1s ease-in-out;
}

.container img.front:hover
{
  opacity:0;
}

Problem:
This HTML-CSS works but for a single image switch (2 images) on hover, not for multiple ones automatically.
Need:
A change in the code which allows multiple switches using CSS and HTML only, with different links on each image.
I know there are possibilities with JQUERY and JAVACRIPT, I wish for a solution without these two.
Solution Code restrictions and parameters:

*

*No JQUERY nor JAVASCRIPT

*Multiple browser compatibility (doesn't need to be very old ones)

*Possibility of multiple links in each image switch

Many Thanks for all help provided.

A: Try this you have to move your cursor a slight (shake it a bit) to see the change in the link notice the change in the link http://jsfiddle.net/fc3nb5rL/1/
i used z-index instead of opacity
.back {
z-index:1;
 }
@-webkit-keyframes anim {
from {
    z-index:1;
}
to {
    z-index:-2;
}
}
.back:hover {
-webkit-animation:anim 5s;
-webkit-animation-iteration-count:infinite;
-webkit-animation-timing-function: ease-in-out;
}

@-webkit-keyframes anim2 {
from {
    z-index:1;
}
to {
    z-index:-2;
}
 }

.front:hover{
-webkit-animation:anim2 5s;
-webkit-animation-iteration-count:infinite;
-webkit-animation-timing-function: ease-in-out;
}


text:
Q: why TAILQ_FOREACH_SAFE implementation contains ((tvar) = TAILQ_NEXT((var), field), 1)? While using queue.h MACRO for safe traversal, I have a doubt
#define TAILQ_FOREACH_SAFE(var, head, field, tvar)       \
    for ((var) = TAILQ_FIRST((head));                    \
        (var) && ((tvar) = TAILQ_NEXT((var), field), 1); \
        (var) = (tvar))

Why tailing 1 is added in ((tvar) = TAILQ_NEXT((var), field), 1) statement ?

A: ((tvar) = TAILQ_NEXT((var), field), 1);

This uses the comma operator. The expression on the left side of the comma is evaluated and its result discarded, and then the expression on the right side is evaluated and its result returned - the literal 1 in this case, so if var is true, the entire (var) && ((tvar) = TAILQ_NEXT((var), field), 1) expression is true no matter what tvar gets set to, so the for loop it's part of continues. It stops when var is not true (By being a NULL pointer).


text:
Q: How do I fix this small memory leak for my program? So I made a program that simulates a Tic-Tac-Toe game and ran it with valgrind and it says that I have a memory leak. What is causing this leak and how do I fix it?
Here is the output from valgrind:
==15253==
==15253== HEAP SUMMARY:
==15253==     in use at exit: 72,704 bytes in 1 blocks
==15253==   total heap usage: 37 allocs, 36 frees, 76,864 bytes allocated
==15253==
==15253== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==15253==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==15253==    by 0x4EC5B1F: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.22)
==15253==    by 0x40104E9: call_init.part.0 (dl-init.c:72)
==15253==    by 0x40105FA: call_init (dl-init.c:30)
==15253==    by 0x40105FA: _dl_init (dl-init.c:120)
==15253==    by 0x4000CF9: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
==15253==
==15253== LEAK SUMMARY:
==15253==    definitely lost: 0 bytes in 0 blocks
==15253==    indirectly lost: 0 bytes in 0 blocks
==15253==      possibly lost: 0 bytes in 0 blocks
==15253==    still reachable: 72,704 bytes in 1 blocks
==15253==         suppressed: 0 bytes in 0 blocks
==15253==
==15253== For counts of detected and suppressed errors, rerun with: -v
==15253== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

And here is the code:
main.cpp:
#include <iostream>
#include "../include/Board.h"

using namespace std;

/**
 * Main function that is run.
 * @return: 0 on exit success
 */
int main() {
    Board b;
    int r, c;
    int moveCount = 0;

    cout << "* * * * * Welcome to the Tic-Tac-Toe game! * * * * *" << endl;
    cout << "Enter numbers 1, 2, or 3 when prompted for coordinates of your move." << endl;
    cout << b.toString() << endl;

    // Loops until there are no more possible moves.
    while(moveCount < 9) {
        // Prompts for coordinates to make a move.
        do {
            if(moveCount % 2 == 0) {
                cout << "Player X's turn, enter the row and column of your move.\nRow #:";
            }
            else {
                cout << "Player O's turn, enter the row and column of your move.\nRow #:";
            }
            cin >> r;
            cout << "Column #:";
            cin >> c;

            // Checks if the move is valid.
            if(b.canPut((r - 1), (c - 1)) != 1) {
                cout << "\nInvalid move, re-enter the desired coordinates.\n" << endl;
            }
        }while(b.canPut((r - 1), (c - 1)) != 1);

        // Makes the move.
        if(moveCount % 2 == 0) {
            b.makeMove((r - 1), (c - 1), X);
        }
        else {
            b.makeMove((r - 1), (c - 1), O);
        }

        cout << b.toString() << endl;

        // Checks if there is a winner and breaks the loop if there is.
        if(b.checkWinner() != 0)
            break;
        moveCount++;
    }

    // Prints the appropriate statement base on the winning status, if any.
    if(moveCount == 9) {
        cout << "\nGame over, stalemate." << endl;
    }
    else {
        if(b.checkWinner() == X) {
            cout << "\nPlayer X has won!!!" << endl;
        }
        else if(b.checkWinner() == O) {
            cout << "\nPlayer O has won!!!" << endl;
        }
    }

    return 0;
}

Board.h:
#ifndef BOARD_H
#define BOARD_H

#include <string>
#define X 1
#define O 5
#define SIZE 3

/**
 * Board class for tic-tac-toe project.
 */
class Board {
    private:
        int **grid;
    public:
        Board();
        ~Board();
        int checkWinner();
        int canPut(int r, int c);
        void makeMove(int r, int c, int val);
        std::string toString();
};

#endif

Board.cpp:
#include "../include/Board.h"
#include <string>

using namespace std;

/**
 * Constructor for a Board object.
 */
Board::Board() {
    grid = new int*[SIZE];

    // Creates all the 1D arrays to make the 2D array.
    for(int ctr = 0; ctr < SIZE; ctr++) {
        grid[ctr] = new int[SIZE];
        for(int i = 0; i < SIZE; i++) {
            grid[ctr][i] = 0;
        }
    }
}

/**
 * Destructor for a Board object.
 */
Board::~Board() {
    for(int ctr = 0; ctr < SIZE; ctr++) {
        delete[] grid[ctr];
    }
    delete[] grid;
}

/**
 * Checks if there is a winner for the current game.
 * @return: 0 if no winner, X if X player wins or O if O player wins
 */
int Board::checkWinner() {
    int sum;

    // Checks all the rows for a winner.
    for(int i = 0; i < SIZE; i++) {
        sum = 0;
        for(int ctr = 0; ctr < SIZE; ctr++) {
            sum += grid[i][ctr];
        }
        if(sum == 3) {
            return X;
        }
        else if(sum == 15) {
            return O;
        }
    }

    // Checks all the columns for a winner.
    for(int a = 0; a < SIZE; a++) {
        sum = 0;
        for(int b = 0; b < SIZE; b++) {
            sum += grid[b][a];
        }
        if(sum == 3) {
            return X;
        }
        else if(sum == 15) {
            return O;
        }
    }

    // Checks the top-left to bottom-right diagonal for a winner.
    sum = 0;
    for(int i = 0; i < SIZE; i++) {
        sum += grid[i][i];
    }
    if(sum == 3) {
        return X;
    }
    else if(sum == 15) {
        return O;
    }

    // Checks the top-right to bottom-left diagonal for a winner.
    sum = 0;
    for(int r = 0, c = SIZE - 1; r < SIZE && c > 0; r++, c--) {
        sum += grid[r][c];
    }
    if(sum == 3) {
        return X;
    }
    else if(sum == 15) {
        return O;
    }

    // Returns zero because after checking all the possibilities, a winner has not been found.
    return 0;
}

/**
 * Determines if there is an open spot on the board at the given coordinates.
 * @param r: the row to be checked
 * @param c: the column to be checked
 * @return: 1 if there is an open spot, 0 if not
 */
int Board::canPut(int r, int c) {
    if(grid[r][c] == 0)
        return 1;
    return 0;
}

/**
 * Simulates making a move for a player.
 * @param r: the row to set the value
 * @param c: the column to set the value
 * @param val: the value to be set at the given coordinates
 */
void Board::makeMove(int r, int c, int val) {
    grid[r][c] = val;
}

/**
 * Creates a representation of the board as a string.
 * @return: string of the board
 */
string Board::toString() {
    char a, b, c;
    string output = "Board:\n";

    // Loops through every line for the 2D array.
    for(int ctr = 0; ctr < SIZE; ctr++) {

        // Loops through every value of the 1D array being checked.
        for(int i = 0; i < SIZE; i++) {
            output += ' ';
            if(grid[ctr][i] == X) {
                output += 'X';
            }
            else if(grid[ctr][i] == O) {
                output += 'O';
            }
            else {
                output += ' ';
            }
            if(i != (SIZE - 1)) {
                output.append(" |");
            }
            else {
                output += '\n';
            }
        }

        // Pads each line with a line of '-' characters.
        if(ctr != (SIZE - 1)) {
            for(int i = 0; i < (SIZE * 4) - 1; i++) {
                output += '-';
            }
            output += '\n';
        }
    }
    return output;
}

A: So, that memory leak isn't your problem. It's a memory leak incurred when the program is doing initialization, before any of your code is even executed.
Valgrind typically ignores these. It has a file that has a list of things it needs to ignore in various libraries on various platforms. Perhaps you used a Valgrind option that told it to not ignore them, or perhaps it just hasn't been set up correctly for that exact version of libstdc++ on that platform.
As an unrelated C++ style note, I will say that I don't really like that you used #define in Board.h. You should be declaring things const.

A: Your code looks good but I would suggest not using the pointer of pointer for grid, which is a bit tricky to handle.
Instead of int **grid,
have int grid[SIZE][SIZE].
Then you don't need any new and delete calls - no source of memory leak!
This works unless the SIZE is very big and you try to allocate Board on stack. If the SIZE is big, just allocate Board on heap by b = new Board(). (Don't forget to delete it!)


text:
Q: googleapi.discovery iam create service account Hi I want to use the google api service to create service accounts.
Here is my current code:
base_url = f"https://iam.googleapis.com/v1/projects/{project}/serviceAccounts"
auth = f"?access_token={access_token}"
data = {"accountId": name,
        "serviceAccount": {
            "displayName": name
        }}
Create a service Account
r = requests.post(base_url + auth, json=data)
try:
    r.raise_for_status()
except requests.HTTPError:
    if r.status_code != 409:
        raise

This works, but it uses the requests package.
I want to use googleapiclient
from googleapiclient.discovery import build

credentials = GoogleCredentials.get_application_default()
api = build(service, version, credentials=credentials)

Then, where do I find information on how to use this api object?
I've tried:
api.projects().serviceAccounts.create(name=name).execute()

But this does not work, and I don't know how to find what arguments are expected or required.

A: You can find the GCP IAM API documentation here.
The arguments required and values are documented there.

A: For anyone else who is struggling.
Check out api explorer to get the format of the request.
For example, If the endpoint is iam.projects.serviceAccounts.get
and you need to provide name = "projects/project/serviceAccounts/sa@gsc.googleserviceaccounts.com"
Then your call will look like:
from googleapiclient.discovery import build

credentials = GoogleCredentials.get_application_default()
api = build(service, version, credentials=credentials)

sa = api.projects().serviceAccounts().get(name="projects/project/serviceAccounts/sa@gsc.googleserviceaccounts.com")

Hope this helps someone.


text:
Q: CSS align chat boxes to bottom of screen I have several chat boxes and other div elements that need to be positioned at the bottom of the screen, aligned to the right.
Problem #1: Elements do not have the same height, and the smaller ones are vertically aligned with the top of the highest element. Fiddle: http://jsfiddle.net/sd69jdxp/
#container { position: fixed; bottom:0; left:0; right:0; }
.chat { border: 1px solid #999; float: right; position: relative; margin: 0 5px; }

Problem #2: Using the approach of

display: inline-block; vertical-align: bottom;

to align divs to the bottom of the page, the links (anchors) over the first (smallest) chat box are not clickable, as the parent container overlaps the links. And it's not possible to set a lower z-index to the chat container than to the content behind, since the chat boxes are children of the chat container and they MUST have a higher z-index than the page content. How can this issue be solved?
Fiddle showing this issue: http://jsfiddle.net/xw689yv8/
Summary
How can I force all divs to be aligned with the bottom right of the screen, without having the chat container (parent div of chat boxes) overlap the content in the page behind the chat boxes, thus making it unclickable?

A: *

*Use pointer-events: none on the container; elements underneath it will now be clickable.

*Arrange the chat boxes inside the fixed container with display: inline-block and vertical-align: bottom.

*The chat boxes get pointer-events: auto so they and their children can be clicked.
For IE10 and below, check out this answer to an older question to transfer click events.
Example
See it full screen and select the text input sitting underneath the invisible container.

.under {
  position: absolute;
  bottom: 200px;
  right: 200px;
}
#container {
  position: fixed;
  bottom: 0;
  right: 0;
  pointer-events: none;
}
.chat {
  border: 1px solid #999;
  display: inline-block;
  vertical-align: bottom;
  position: relative;
  margin: 0 5px;
  pointer-events: auto;
}
.title {
  padding: 0.5em;
  background-color: blue;
  color: white;
}
.text {
  padding: 10px;
}

  <input type="text" value="select me!" />

This is the chat title

Text 1

Text 2

Text 3

      <input type="text" />

This is the chat title

Text 1

Text 2

Text 3

      <input type="text" />

A: I am not sure how you want to align them so I put them over each other.
http://jsfiddle.net/ouu94tfv/
#container { position: fixed; bottom:0; left:0; right:0; }
.chat { border: 1px solid #999; right:0; position: absolute; bottom: 0; margin: 0 5px; display:inline-block; float:right;}
.title { padding: 0.5em; background-color: blue; color: white; }
.text { padding: 10px; }


text:
Q: Linking multiple objects to HttpEntity My rest api uses POST request with 2 object parameters: custom type and long

I can link one parameter to body like this:
private void createCaseParticipant(long caseId, CaseParticipantDTO caseParticipantDTO)
    {
        HttpHeaders headers = new HttpHeaders();
        headers.add(AUTHORIZATION_HEADER_NAME, BASIC_AUTHORIZATION_HEADER_PREFIX + cmsRestApiCreds);

        HttpEntity<CaseParticipantDTO> postRequest = new HttpEntity<CaseParticipantDTO>(caseParticipantDTO, headers);
    }

How can I add second parameter to my request?
Thank you

A: you can simply add it to the HttpHeadersobjects something like this :

private void createCaseParticipant(long caseId, CaseParticipantDTO caseParticipantDTO)
    {
        HttpHeaders headers = new HttpHeaders();
        headers.add(AUTHORIZATION_HEADER_NAME, BASIC_AUTHORIZATION_HEADER_PREFIX + cmsRestApiCreds);
        headers.add("caseId",caseId.toString());
        headers.add("caseParticipantDTO", caseParticipantDTO.toString());
        HttpEntity<CaseParticipantDTO> postRequest = new HttpEntity<CaseParticipantDTO>(caseParticipantDTO, headers);
    }


text:
Q: Function that returns a list consisting of 40 random letters from (A-F) I need to create a function called random_grades that returns a list consisting of 40 random letters from (A-F).
This is the code so far.. but i dont know how to make the output letters and not numbers...
import random
random_grades = [random.randint(5,10) for i in range (40)]

A = 10

B = 9

C = 8

D = 7

E = 6

F = 5

print(random_grades)

A: random.choices does it directly:
random.seed(0)  # make it reproducible
random.choices('ABCDEF', k=40)

give:
['F', 'E', 'C', 'B', 'D', 'C', 'E', 'B', 'C', 'D', 'F', 'D', 'B', 'E', 'D', 'B', 'F', 'F', 'E', 'F', 'B', 'E', 'F', 'E', 'C', 'A', 'C', 'D', 'F', 'F', 'C', 'F', 'B', 'E', 'D', 'A', 'E', 'C', 'E', 'E']

This works because a string is an iterable of characters...

A: You can use a map index -> grade aka an array, and the random variable is the index.
import random

grades = ['A','B','C','D','E','F']

random_grades_indexes = [random.randint(0,len(grades)-1) for i in range (40)]
random_grades = [ grades[i] for i in random_grades_indexes]

print(random_grades)

Which prints
['D', 'A', 'A', 'B', 'D', 'E', 'A', 'E', 'D', 'E', 'B', 'A', 'A', 'B', 'D', 'B', 'E', 'A', 'F', 'B', 'B', 'D', 'C', 'F', 'E', 'B', 'A', 'B', 'C', 'E', 'E', 'C', 'F', 'D', 'A', 'F', 'B', 'C', 'B', 'E']

As a proof that you will get a uniform distribution, we can create an histogram of the grades running 1000 grades.
import random

def count_elements(seq) -> dict:
    hist = {}
    for i in seq:
        hist[i] = hist.get(i, 0) + 1
    return hist

grades = ['A','B','C','D','E','F']

random_grades_indexes = [random.randint(0,len(grades)-1) for i in range (1000)]
random_grades = [ grades[i] for i in random_grades_indexes]

dist = count_elements(random_grades)
print(dist)

Which gives
{'C': 175, 'F': 153, 'A': 153, 'E': 174, 'D': 174, 'B': 171}


text:
Q: SQLite JDBC Class Not Found Exception I've been trying to make use of the SQLite jdbc class from Xerial. Every time I try to run what I have, it fails, giving me the following error:
java.lang.ClassNotFoundException: org.sqlite.Driver

I'm using Ivy, and have the following in my ivy.xml file.
<dependency org="org.xerial" name="sqlite-jdbc" rev="3.7.2"/>

This includes the sqlite-jdbc-3.7.2.jar file in my class path. I've also tried manually adding it, to no avail.
The command that runs this also contains the jar on the command line:
java -cp ... sqlite-jdbc-3.7.2.jar ...

I still get the class not found exception on the following line:
Class.forName("org.sqlite.Driver");

I've tried searching around for this particular issue, but it seems most of the time it's resolved simply by including the jar in the class path, which shouldn't be the issue here, as Eclipse lists the jar in the class path.

A: Can you confirm that the jar version sqlite-jdbc-3.7.2 has class org.sqlite.Driver?
You can check it by unzipping the jar file and check if unzippied folder has directory structure org\sqlite\Driver.class?
I think the sqlLite Driver name is org.sqlite.JDBC and not org.sqlite.Driver . Source.


text:
Q: Import XML into a Grails Domain Class I am reading an XML file with a schema based on a Domain Class.
Here is a simple example for illustration (my current situation concerns a lot of fields from a lot of classes) :
class Player {
  String name
  Date birthDate
}

The XML file to read is :
<players>
<player name='P1' birthDate='12-09-1983'/>
</players>

So my question is:
When parsing the XML file, I create Player instances with the following Groovy code:
def players = new XmlSlurper().parse(xmlFile)
players.player.each() {p ->
  new Player(name: p.@name, birthDate: p.@birthDate).save()
}

Is there another simpler way to do it ?
Like params binding when creating/updating a domain object using code like new Player(params) or player.properties = params ?

A: Actually, you can give directly the list of attributes to your domain class constructor with attributes().
def players = new XmlSlurper().parse(xmlFile)
players.player.each() {p ->
    new Player(p.attributes()).save()
}


text:
Q: How to Make Two Flex Columns Behave like a Table in CSS? I don't believe that what I'm asking for is yet achievable in pure CSS but I'm going to ask anyway in hopes there is another approach or something I'm missing.
Here is an illustration of my current layout, achieved with flexbox:

This works perfectly. But what if I add more content to column 1, below the "column within column" div. And then I want to also add content to Column 2, but I want it to occupy the same vertical space as the item I've just added to column 1? In other words, as if everything was a table and those items where in the same row in adjacent table cells?
This is a common issue when laying out forms for example, where you want to group items (city, state, zip) in columns and you want to track things side by side down the form.
(I've just got the gray borders around the columns to help delineate the markup, but typically their would not be borders between the columns on a multi-column form layout)
So, the end result would appear as in the second image below:

Here is the structural HTML for the demo:

.container {
  display: flex;
}

.column {
  flex-grow: 1;
  /* fill parent space based on child content */
  flex: 1 1 0;
  /* fill parent space equally regardless of child content*/
}

.column.row {
  display: flex;
  flex-wrap: wrap;
}

.column.row div {
  flex-grow: 1;
}

.column.row h2 {
  width: 100%;
}

Column 1 Layout Goes here

Form Field

Form Field

Form Field

Column within column

Form Field

Form Field

Form Field

Form Field "Y" Added

Column 2 layout goes here

Form Field

Form Field

Form Field

Form Field Should Track with Form Field "Y" but How?

A: You can make the .column elements flex-containers (i.e. apply display: flex also to the .column elements) which have flex-direction: column; and apply margin-top: auto; to the last div of the second column to move it to the bottom of its container:

.container {
  display: flex;
}

.column {
  flex-grow: 1; /* fill parent space based on child content */
  flex: 1 1 0; /* fill parent space equally regardless of child content*/
  display: flex;
  flex-direction: column;
}

.column.row {
  display: flex;
  flex-wrap: wrap;
}

.column.row div {
  flex-grow: 1;
}

.column.row h2 {
  width: 100%;
}
.column > div:last-child {
margin-top: auto;
}

Column 1 Layout Goes here

Form Field

Form Field

Form Field

Column within column

Form Field

Form Field

Form Field

Form Field "Y" Added

Column 2 layout goes here

Form Field

Form Field

Form Field

Form Field Should Track with Form Field "Y" but How?


text:
Q: Mode-local keybindings in ViM? I've recently return to ViM, after several years in Emacs, and something I'm missing is the ability to set filetype-local keybindings:  e.g. I want to make _ underline the current word in Markdown-type files, but do something completely different in, say, Python.  Is there a way to do this other than just autocmds that override each other?

A: You can use map <buffer> ... to make a mapping local to a buffer rather than global.  Then set up an autocommand to load that mapping only for certain filetypes, or put the mapping into a ftplugin file for that filetype.  Luckily, local mappings aren't cleared when a buffer is hidden, only when a buffer is destroyed, so the mappings will stick around as you switch between buffers.
See :h :map-local.


text:
Q: is there anything i can do to make this while loop stop? I am trying to check if a certain list item is present in a given string?!
str = '[{()'
listt = ['()','{}', '[]']
replace = True

while replace:
  for i in listt:
    if i in str:
      print('y')
      replace == False

A: Try doing this:
str = '[{()'
listt = ['()','{}', '[]']
replace = True

while replace:
  for i in listt:
    if i in str:
      print('y')
      replace = False


text:
Q: How do I export JIRA issues to xls? As title says. I'm trying to export JIRA issues to a xls file through my command line.
this is what I'm entering:
wget -O export.xls https://myjiraurl.com/sr/jira.issueviews:searchrequest-excel-all-fields/10300/SearchRequest-10300.xls?tempMax=1000

But I keep getting this error
Resolving myjiraurl.com (myjiraurl.com)... 10.64.80.92
Connecting to myjiraurl.com (myjiraurl.com)|10.64.80.92|:443... connected.
ERROR: cannot verify myjiraurl.com's certificate, issued by '/C=US/O=MyCorporation/CN=Intel Intranet Basic Issuing CA 2B':
Self-signed certificate encountered.
To connect to myjiraurl.com insecurely, use `--no-check-certificate'.

I've also tried adding
 &os_username=<myuserid>&os_password=<mypassword>

how it still gives me the same thing. I've tried directly plugging the url into the address bar and it exports a xls file back to be just fine. tips?

A: Try:
wget --user=userid --password=secret --no-check-certificate -O export.xls "https://myjiraurl.com/sr/jira.issueviews:searchrequest-excel-all-fields/10300/SearchRequest-10300.xls?tempMax=1000"


text:
Q: Macbook Pro OSX El Capitan 10.11.3 and Technicolor TC8717T Router The Wifi disconnects every few minutes and only comes back online if Wifi is toggled off and on from the laptop. This only happens with this router. And the MB Pro is the only device in the home that has this issue.
I've already set a static location in Wifi settings (not automatic mode). I've read dozens of posts of similar sounding issues and tried every step they suggested. I'm starting to feel like there is a bug somewhere in either Apple's software or the Router's firmware. This has been happening for months now.


text:
Q: Missing something in "Delete" post method in MVC (EF 4.1) Following this example .. http://msdn.microsoft.com/en-us/data/gg685489
I am running into issues with Delete functionality.
[HttpPost]
public ActionResult Delete(int id, Blog blog)
{
    try
    {
        using (var db = new BlogDataEntities())
        {
            //Having issue here.. as soon as the next line is run in debug
            //mode .. it goes to catch.. and returns a view with null values.

            db.Entry(blog).State = System.Data.EntityState.Deleted;
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

In the parameters I checked 'blog' does not get the actual blog model that needs to be deleted. All the other methods work fine (Edit, Delete (get)..etc..
but Delete post fails. Am I missing something? thanks in advance for the help.
EDIT:
view code
@model DBFirstMVC.Models.Blog

@{
 ViewBag.Title = "Delete";
 }

Delete

Are you sure you want to delete this?

<fieldset>
<legend>Blog</legend>

Title

@Model.Title

BloggerName

@Model.BloggerName

 </fieldset>
@using (Html.BeginForm()) {

    <input type="submit" value="Delete" /> |
    @Html.ActionLink("Back to List", "Index")

 }

EDIT 2:
Non Razor Code in view:
<% using (Html.BeginForm()) { %>

    <input type="submit" value="Delete" /> |
    <%: Html.ActionLink("Back to List", "Index") %>

<% } %>

EDIT 3: (I tried in aspx)
<% using (Html.BeginForm()) { %>

    <%=Html.DisplayForModel();%> //Tried Html.EditorForModel also..
    <input type="submit" value="Delete" /> |
    <%: Html.ActionLink("Back to List", "Index") %>

<% } %>

FINAL EDIT (Corrected Solution)
@model DBFirstMVC.Models.Blog

@{
 ViewBag.Title = "Delete";
}

Delete

Are you sure you want to delete this?

@using (Html.BeginForm()) {

<fieldset>
<legend>Blog</legend>

Title

@Model.Title

BloggerName

@Model.BloggerName

  <input type="submit" value="Delete" /> |
@Html.ActionLink("Back to List", "Index")
</fieldset>

}

A: The context probably doesn't have an Entry for your Blog because it isn't attached to the Context.
You probably need to retrieve the Blog first and then mark it as deleted using the Entry method:
[HttpPost]
public ActionResult Delete(int id, Blog blog)
{
    try
    {
        using (var db = new BlogDataEntities())
        {
            // retrieve the blog from the database
            var realBlog = db.Blogs.Find(blog.Id);

           // nothing to do here, just redirect
           if( realBlog == null )
                return RedirectToAction("Index");

          // since you have the entity just do this instead:
          db.Blogs.Remove(realBlog);
          db.SaveChanges();
        }

        return RedirectToAction("Index");
    }
    catch( Exception )
    {
        return View();
    }
}

I don't really agree with the idea of using your entities as your models though. You should use View Models instead.
EDIT
Since you now are saying that Blog isn't being passed, try this:
@model Blog

@using ( Html.BeginForm() )
{
    @Html.EditorForModel()

    <input type="submit" value="Delete" />
}

You weren't actually giving the model binder any of the details it needed to construct your model.

A: is it possible to try the following:
[HttpPost]
public ActionResult Delete(Blog deletedBlog)
{
    try
    {
        using (var db = new BlogDataEntities())
        {
            // get blog entry from db context!!
            Blog blog = db.Blogs.Find(deletedBlog.Id);
            //Having issue here.. as soon as the next line is run in debug
            //mode .. it goes to catch.. and returns a view with null values.

            db.Entry(blog).State = System.Data.EntityState.Deleted;
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    catch(Exception e)
    {
        // should catch more specific exception
        // but catching 'e' should be a start
        return View();
    }
}

[Update] - pass in your Blog model from the view, tho as Dismissile says, you should really use a viewmodel, rather than the entity model for this purpose.
Also, you should catch the inner exception message and examine that for further clues.

A: The blog parameter in your Delete Action is null most likely because you are only posting the blog's id, not the entire blog object. I would either modify the Delete Action to accept just the id (per Dismissile's answer), or modify the Delete View to post the entire blog object and remove the id from the Action (since it belongs to the blog object):
[HttpPost]
public ActionResult Delete(Blog blog)
{
    try
    {
        using (var db = new BlogDataEntities())
        {
            db.Entry(blog).State = System.Data.EntityState.Deleted;
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

A: I posted this in a few comments, but I felt it merited a separate answer for an "alternative".
Your controllers should be slim and adhere as best as possible to the single responsibility principle.
BlogController
public class BlogController : Controller
{
    private BlogService blogService;

    public BlogService()
    {
        blogService = new BlogService();
    }

    [HttpPost]
    public ActionResult Delete(int id)
    {

        // make sure the user has permission to delete before actually deleting

        // now that we know the user has permission
        if (blogService.Delete(id))
        {
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }
}

Now you'll have a reusable service layer that adheres to the single responsibility principle.
BlogService
public class BlogService
{

    private BlogDataEntities dc;

    public BlogService()
    {
        dc = new BlogDataEntities();
    }

    public bool Delete(int Id)
    {
        try
        {
            var blog= (from b in dc.Blogs where Blog.ID == Id select b).First();

           // blog doesn't exist, exit and return false.
           if( blog == null )
                return false;

          // blog exists, remove it
          dc.Blogs.Remove(blog);

          // push the delete to the database
          SaveChanges();

          // it worked, return true.
          return true;
        }
        catch(System.Exception ex)
        {
            // an error happened, handle it and return false.
            return false;
        }
    }

    // I like to keep my `SubmitChanges()` Separate in case I need to
    // stack up a few processes before hitting the database.
    public void SaveChanges()
    {
        dc.SaveChanges();
    }
}


text:
Q: ReactJS can not disable a dynamically created button Using ReactJS I create a form dynamically using custom JSON data.
render() {
    return (
        <div>
            <ShowForm src={this.state.data} />
        </div>
    );
}

With componentDidUpdate I would like to disable all submit buttons. While the label of the buttons is changed successfully, I constantly fail to disable the button.
componentDidUpdate() {
    var submitButtons = document.querySelectorAll('button[type=submit]');
    submitButtons.forEach(btn => {
        btn.innerText = 'PREVIEW';
        btn.disabled = true;
    });
}

The chrome inspector returns the following HTML code for the buttons. Also, the form objects are using Bootstrap for the CSS styling.
<button lang="en" class="btn btn-warning btn-md" type="submit" name="data[Draft]" ref="button">PREVIEW</button>

What prevents JS to apply the disable action?

A: Web components is the preferred solutions
https://reactjs.org/docs/web-components.html
Alternatively, you can manipulate the JSON data before they are rendered from react-dom.
Another solution I found is simply set pointer-events: none; style.
componentDidUpdate() {
    var submitButtons = document.querySelectorAll('button[type=submit]');
    submitButtons.forEach(btn => {
        btn.setAttribute('style', 'pointer-events: none;');
    });
}


text:
Q: How to get rid of "The disk you inserted was not readable" and auto ignore it? (without installing apps) whenever I plug in an ext4 partition type external USB drive, this message will pop up. and then I need to press "Ignore" to ignore it. This is very annoying. How can I auto ignore it?
I did google this for hours and can not find a proper solution. I don't want to install any non open source apps for doing such a simple task. I think it should be doable by changing some config files.
PS: If you are curious why I want to plug in ext4 drive, because I will later use it with a linux VM (virtualbox+vagrant).
Thanks a lot for your help.
Edited: I don't want to disable automount for all types of drives. I just want to ignore ext4 popup or that specific drive. Cheers.

A: Due to no answer yet, I did find a workaround and want to share here.
(1) Resize the external drive and create a small 100MB Apple_HFS typed partition on it. (label the partition with the name dummy).
Explanation: Since there is a recognized readable partition in the external drive now, there will be no warning popup at all and will auto mount it as /Volumes/dummy/.
(2) Create a shell script in the PATH with the name vagrant-up.sh which has the following content:

diskutil umount /Volumes/dummy/ && cd ~/vagrant/myVM/ && vagrant up

So to run my vm, simply execute vagrant-up.sh.
That's all. It works well so far.


text:
Q: A new window called twice after the mainForm, but first Form not being closed i have a problem:
Here is my case:
i already command a NewForm to be called everytime the user select that. The MainForm is being called when i run the program, and when i click "NewForm", the FirstNewForm being called and the MainForm is closed. But, when i click "NewForm" again in the FirstNewForm that i had created, it called the SecondNewForm, but the FirstNewForm is not being closed.
Here is my question:
How do i close the FirstNewForm? i mean, how do i close a CurrentForm whenever i called a NewForm?
Here is the image when i command a "NewForm" when the MainForm still in there, and MainForm is closed when FirstNewForm being called: (if you see in the taskbar, just one Selling System Program in there): (The first image is MainForm, and the second image is FirstNewForm, it looked the same, because the MainForm already closed when i called a FirstNewForm):

Here is the image when i command a "NewForm" when the FirstNewForm still in there, and FirstNewForm is not being closed when SecondNewForm being called: (if you see in the taskbar,there are two Selling System Programs in there, so the FirstNewForm is not being closed)

How do i hide and close the FirstNewForm?
Here is the code:
private void AddNewForm(object sender, EventArgs e)
    {
        //this.Hide();
        Form newForm = new Form();
        AddObjects(sender, e, newForm);
        UpdateTextPosition(sender, e, newForm);

        newForm.Size = new Size(1360, 735);
        newForm.Text = "Selling System";
        newForm.FormBorderStyle = FormBorderStyle.Fixed3D;
        newForm.AutoScaleMode = AutoScaleMode.Font;
        newForm.AutoScroll = true;
        newForm.AutoSizeMode = AutoSizeMode.GrowAndShrink;
        newForm.StartPosition = FormStartPosition.CenterScreen;
        newForm.MaximizeBox = false;
        newForm.Controls.Add(label1);
        newForm.Controls.Add(label2);
        newForm.Controls.Add(label3);
        newForm.Controls.Add(label4);
        newForm.Controls.Add(label5);
        newForm.Controls.Add(label6);
        newForm.Controls.Add(label7);
        newForm.Controls.Add(menuStrip1);

        //newForm.ShowDialog();

        //this.Close();

        if(this.InvokeRequired)
        {
            Action act = () =>
            {
                this.Hide();
            };

          this.Invoke(act);
        }

        else
        {
          this.Hide();
        }
    }

Thanks in advance! and sorry if i am post a long posting

A: ShowDialog causes a modal dialog to show. This means, the call newForm.ShowDialog() will block and this.Close() will only be reached AFTER you close the new form. You could call this.Hide() on the main form to make it invisible and close all forms together when you exit your program:
this.Hide();

newForm.ShowDialog();

this.Close();

EDIT
It might appear that your call to this.Hide() is not properly dispatched to the UI-thread and so it refuses to hide the form. Try
if(this.InvokeRequired){
     Action act = () => {
          this.Hide();
     }
     this.Invoke(act)
}
else{
     this.Hide();
}

'NOTHER EDIT
private void AddNewForm(object sender, EventArgs e)
{
    ...

    if(this.InvokeRequired)
    {
        Action act = () =>
        {
            this.Hide();
        };

      this.Invoke(act);
    }

    else
    {
      this.Hide();
    }

    newForm.ShowDialog();

}

A: On the mainform You must assign to both childforms eventhandlers OnFormClosed.
There You can react properly  and control each child forms behaviour as it should be done.


text:
Q: @font-face: удачный опыт использования? У кого был удачный опыт использования, помогите.
Всяко разно пробовал. Максимум чего добился это работы шрифта в Хроме и ФФ. Опера и ИЕ пока отказываются видеть нестандартный шрифт. CSS такой:
/* только для Internet Explorer */
@font-face {
   font-family: etelkatext;
   src: url('EtelkaText.eot');
}

/* далее для всех остальных браузеров */
@font-face {
  font-family: etelkatext;
  src: url('EtelkaText.otf');
}

body
{font-family:etelkatext;}

A: А я бы предложил заюзать гугл шрифты, там и примерчики есть. И, кстати, их даже можно сделать автономными.
Сам использую RaphaelJS (print) в с вязке с Cufón.
UPD.
Может так попробовать:
<!--[if IE]>
<style>
/* только для Internet Explorer */
@font-face {
   font-family: etelkatext;
   src: url('EtelkaText.eot');
}
</style>
<![endif]-->
<!--[if !IE]>
/* далее для всех остальных браузеров */
<style>
@font-face {
  font-family: etelkatext;
  src: url('EtelkaText.otf');
}
</style>
<![endif]-->

A: /* только для Internet Explorer */
@font-face {
  font-family: EtelkaText;
  src: local("EtelkaText"),
  url(path-to/EtelkaText.eot);
}

/* далее для всех остальных браузеров */
@font-face {
  font-family: EtelkaText;
  src: local("EtelkaText"),
  url(path-to/EtelkaText.ttf);
}

A: @font-face {
font-family: "mb";
src:url('fonts/magistralc-bold-webfont.eot?') format('eot'),
    url('fonts/magistralc-bold-webfont.ttf')  format('truetype');
}

Для всех браузеров.
A: По моему без участия JS кроссбраузерности не добиться, вот тут рабочая версия.


text:
Q: Module and submodule definitions, checking if I understood it My book defines an R-module as an abelian group X with the defined operation:
$$\phi:R\times X \to X \\\phi(x) =  \alpha x$$
Such that these conditions are satisfied:
$$\alpha(x+y) = \alpha x + \alpha y$$
$$(\alpha+\beta)x = \alpha x + \beta x$$
$$\alpha(\beta x) = (\alpha\beta) x$$
$$1x = x$$
It then defines a submodule $A$ of the $R$-module $X$ as a subset of $X$ that is also a module over $R$, that is, by definition, $A$ is a subgroup of the abelian group $X$ and it must be closed under the operation $\alpha x$, for $x\in A$
Then it introduces this lemma, which is what I need to know if I understood
A nonempty subset $A$ of module $X$ over $R$ is a submodule of $X$ $\iff$, for arbitrary elements of $\alpha\in R$ and $u,v\in A$ we have $u+v\in A$ and $\alpha u \in A$
In the proof of this lemma, it says that by the definition of submodules, the condition is evidently necessary. It remains to estabilish the sufficiency of the condition. For this purpose, it suffices to prove that the negative $-u$ of every element $u\in A$ is in $A$. This follows from:
$$-u = (-1)u\in A$$
I didn't understand which things are satisfied by this. I can see that now we're dealing with a subset, not a subgroup, therefore we need to check that this forms a group. I can see, at least, that the condition $u+v\in A$ is the closure definition of a group. Since it's a subset of a module, the associative operations are still valid, and the identity is valid as well. It suffices to prove that the inverse it's in $A$, which is what he did.
The condition $\alpha x \in A$ is just for the submodule to be well defined, I guess


text:
Q: standard error derivation using FWL theorem: Is this correct? I'm reading a paper (https://scholar.google.com.br/scholar?oi=bibs&cluster=986729284887040990&btnI=1&hl=en), and there's this derivation in the article which I'm not sure is correct, so I want to check.
Consider a linear regression $$ Y = D\tau + X \beta +\epsilon  $$
By the FWL theorem, $$\hat{\tau} =\frac{ cov(D^{\perp X}, Y^{\perp X} )}{var( D^{\perp X} )},$$ where $Y^{\perp X}$ is the variable $Y$ after removing the component linearly explained by $X$, and other variables using $\perp$ is similarly defined. I'm okay until this part. But three pages later, the paper states that $$ se(\hat{\tau}) = \frac{ sd( Y^{\perp X, D })}{sd(D^{\perp X})} \sqrt{ \frac{1}{df}},$$ which I don't get. Specifically, why is there suddenly $D$ appearing in the sd of $Y$?

A: In more conventional notation (with $Z$ here including all regressors), the standard error is the diagonal element of
$$
s^2(Z'Z)^{-1},
$$
where $s^2$ the sample variance of the residuals. In "your" notation, the residuals are what you get after projecting $Y$ on $X$ and $D$, so $Y^{\perp X, D}$.


text:
Q: Cloud Vision API service is slow suddenly I'm using the Google Cloud Vision API.
Since June 2, Cloud Vision API services have slowed down.
Until June 1, I received a response within one second.
However, from June 2, we need more than 2.5 seconds response time.
Our service quality is degraded, and my service users are complaining
Does this phenomenon only appear to me? What should I do?
This is a graph representing the problem.


text:
Q: Trying to make images as sprites in pygame Why isn't this code working? I'm trying to create a class to quickly create players for my game in pygame. I was trying to create a sprite based on what he did in this video, https://www.youtube.com/watch?v=hDu8mcAlY4E, and his seemed to work fine.
class Player(Sprite):

    def __init__(self,x,y,picture_path,width,height):
      super().__init__()
      self.image = pygame.image.load(picture_path)
      self.rect = self.image.get_rect()

    def move(self):
        self.x += self.dx
        self.y += self.dy
        self.dy += GRAVITY

    def jump(self):
        self.dy -= 15

    def left(self):
        self.dx -= 6
        if self.dx < -12:
          self.dx = -12

    def right(self):
        self.dx = 6
        if self.dx > 12:
            self.dx = 12

player = Player(600,0,'nin.png',20,20)
player2 = Player(600,40,'nin.png',20,20)

If you want the error for this here it is;
Traceback (most recent call last):
  File "main.py", line 107, in <module>
    player = Player(600,0,'nin.png',20,20)
  File "main.py", line 77, in __init__
    super().__init__()
TypeError: __init__() missing 4 required positional arguments: 'x', 'y', 'width', and 'height'
 Traceback (most recent call last):
  File "main.py", line 107, in <module>
    player = Player(600,0,'nin.png',20,20)
  File "main.py", line 77, in __init__
    super().__init__()
TypeError: __init__() missing 4 required positional arguments: 'x', 'y', 'width', and 'height'


A: The base class must be pygame.sprite.Sprite instead of your own Sprite class.
Pygame uses pygame.sprite.Sprite objects and pygame.sprite.Group objects to manage Sprites. pygame.sprite.Group.draw() and pygame.sprite.Group.update() are methods which are provided by pygame.sprite.Group.
The former delegates the to the update method of the contained pygame.sprite.Sprites - you have to implement the method. See pygame.sprite.Group.update():

Calls the update() method on all Sprites in the Group [...]

The later uses the image and rect attributes of the contained pygame.sprite.Sprites to draw the objects - you have to ensure that the pygame.sprite.Sprites have the required attributes. See pygame.sprite.Group.draw():

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect. [...]

See the very basic example:
 repl.it/@Rabbid76/PyGame-Sprite
import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):

    def __init__(self, center_pos, image):
        super().__init__()
        self.image = image
        self.rect = self.image.get_rect(center = center_pos)

    def update(self, surf):
        keys = pygame.key.get_pressed()
        self.rect.x += (keys[pygame.K_d]-keys[pygame.K_a]) * 5
        self.rect.y += (keys[pygame.K_s]-keys[pygame.K_w]) * 5
        self.rect.clamp_ip(surf.get_rect())

player_surf = pygame.image.load('Bird64.png').convert_alpha()
player = Player(window.get_rect().center, player_surf)
all_sprites = pygame.sprite.Group([player])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    all_sprites.update(window)

    window.fill(0)
    all_sprites.draw(window)
    pygame.display.flip()

pygame.quit()
exit()


text:
Q: ESP32 dual core multi tasks priority issue task1 : webServerTask,
task2 : guiTask (use mutex)
I assigned task1 to cpu0 and task2 to cpu1 using the xTaskCreatePinnedToCore function in esp32. Then I expected task1 and task2 to run concurrently on each other's cpu regardless of their respective priorities, isn't that right?
If I increase the priority of task1 over task2, task2 will not run. If I set the priorities to be the same, both tasks will run. Even if I assign tasks to different CPUs, does the execution of the tasks differ according to their priority? Or is it related to the use of semaphore in task2?
case 1: webServerTask run, guiTask does not work (priority: task1 > task2, task2 with mutex)
xTaskCreatePinnedToCore(webServerTask, "webServer", 4096, NULL, 2, NULL, 0);
xTaskCreatePinnedToCore(guiTask, "gui", 4096 * 2, NULL, 1, NULL, 1);

case 2: both webServerTask and guiTask run (priority: task1 = task2, task2 with mutex)
xTaskCreatePinnedToCore(webServerTask, "webServer", 4096, NULL, 1, NULL, 0);
xTaskCreatePinnedToCore(guiTask, "gui", 4096 * 2, NULL, 1, NULL, 1);

case 3: both webServerTask and guiTask run (priority: task1 > task2, task2 without mutex)
xTaskCreatePinnedToCore(webServerTask, "webServer", 4096, NULL, 2, NULL, 0);
xTaskCreatePinnedToCore(guiTask, "gui", 4096 * 2, NULL, 1, NULL, 1)

Task1 and Task2 are implemented as below:
static void webServerTask(void *pvParameters)
{
  // initialize wifi and the web server
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    vTaskDelay(500 / portTICK_PERIOD_MS);
    Serial.print(".");
  }

  // Run the web server loop indefinitely
  while(1)
  {
    WiFiClient client = server.available();
    if (client)
    {
      ...
     }
    vTaskDelay(10 / portTICK_PERIOD_MS);
  }
}

static void guiTask(void *pvParameter)
{
  xGuiSemaphore = xSemaphoreCreateMutex();
  ...  // display

  while (1)
  {
    vTaskDelay(pdMS_TO_TICKS(10));

    if (pdTRUE == xSemaphoreTake(xGuiSemaphore, portMAX_DELAY))
    {
      lv_task_handler();
      xSemaphoreGive(xGuiSemaphore);
    }
  }
}


text:
Q: Reset remote git branch I have two remote branches in git, master and test. master reflects whatever will be deployed to our production environment next. test is the same, but for our testing environment.
Because of stalled or scrapped projects test could, over time, theoretically accumulate a lot of commits not present in master. How do I avoid this?
I know one solution would be to delete my local and remote test branch. Then create a new one based on master and push that to remote. However this approach forces my colleagues and build/deploy systems to also delete their local branches before pulling a the new one.

A: Another approach, allowing to pull the test branch is to reset the index of test to the one of master, not rewriting the history of test, but adding a new commit which would reflect the same state as master.
That would however leave in test history all the extra commits.
git checkout master
git merge -s ours test # make master believe that everything from test has been
                         merged to master up to this point.
git checkout test
git reset master -- . # reset the index content of test to the index of master
git checkout # reset the working tree of test to its new index
git commit -m "test reset to master"
git merge master # should be trivial merge
git push origin master
git push origin test


text:
Q: F90 Interpolation from non-constant-resolution 3D grid to a constant resolution grid I have data on a 3D cartesian grid with varying resolution. The grid is still structured, in that the x resolution is only a function of x, same for y,z. I need to interpolate this data onto a constant resolution grid of approximately the same size. Typical sizes are 256^3, 512^3.
Tri-linear interpolation won't cut it due to the noisy data, whch leaves higher order (for accuracy or smoothness, I have yet to decide which will be best). I am aware of the software
http://jacobwilliams.github.io/bspline-fortran/ but this states that it works on a regular grid. If "regular" means constant resolution, then this may not help my problem. However, I may have misinterpreted what they mean by "regular".
Is anyone aware of open source fortran software that can be used for my problem? Namely  interpolation from one large 3d grid (non-constant-resolution) to a new 3D grid (constant resolution), that is more than tri-linear.
Thanks

A: The term 'regular' grid is not used as often as 'uniform grid' (which your grid is not) and 'structured grid' (which it is). The specifications of bspline-fortran seem to indicate that the interpolation works for structured, rectilinear, stretched grids, so I suppose that this is the definition of 'regular' grid in your case. The good news is that your grid is 'regular' by that definition.
The important question for your case is whether your nonuniform grid is the result of a 'smooth transformation function'. If it is, your grid can be seen as a uniform grid in 'transformed space', and you can use the available 3D interpolations.
My advice is to try it and find some way to evaluate the accuracy.


text:
Q: Partial derivative with logarithmic differentiation So I'm trying to follow the derivation in a book on Analytic combinatorics.  We have the function $$P(z,u)=(1-z)^{-u}$$
and I need to take the partial derivative with respect to $u$,  then evaluate at $u=1$.
So,  my attempt:
$$\ln (P(z,u))=-u\ln(1-z)$$
$$\frac {P_u(z,u)}{P(z,u)}=-\ln (1-z)$$
$$P_u(z,u)=-(1-z)^{-u}\ln (1-z)$$
then evaluating at $u=1$, ending up with
$$-(1-z)^{-1}\ln (1-z)$$
The only problem is, the author has no negative sign in his expression....did I make a mistake in the chain rule or something?

A: No, you didn't make a mistake. Your answer is correct. That's clearly a typo in the book.


text:
Q: Creating a login portal for my WiFi Me and my room mate often have a lot of friends come over to our apartment to play games and what not. So we are talking a lot of devices connecting to my router (cell phones, tablets, laptops etc .. some times even PS3). I currently have a DD-wrt based router.
What I want is the following - Create some kind of a login portal, the way they have in airports and stuff. The first time their device signs in they are shown a page where they enter their name. Then they hit "submit" at which point their internet starts "working".
I attached a USB wifi dongle to my wired Linux box. Installed dnsmasq dhcpserver, installed iptables and got it to work as a "router" by sharing out eth0 over wlan0 (enabling ip_forward, masquerading all that good stuff).. That part works.
How do I do the login portal thing? I am not interested in passwords (all though as a next step that would be cool). My place is like a central "hub" for a lot of my gaming pals, so often I have folks who are friends of friends and I just want to keep a basic track of what's going on etc.

A: Install pfsense on the box you want to use as the router - It has the software you require built in. Plenty of tutorials about to show you how on http://pfsense.org/
The 2.2beta has better USB wifi support - Most atheros/ralink chipsets supported, but no wireless N. Just B/G.


text:
Q: model management in MVC I'm searching for a best practice for making a model in MVC.
I'm making a socket server with concurrent users.
As I understand, a model in MVC has included business logic so that if I get a model from a data access or maybe db SAO.
How can this model object be updated when someone else has changed an attribute in the DB ?
The first solution I can think of is to always get an attribute of model by accessing it from the database.
The second one is to make a model pool and modify the reference.
Any suggestion??

A: If you have just one server and just one process, you could cache your model (static variables or similiar) and you will just have one model in memory that mirrors the database. But this would scale bad (or better won't scale at all). So depending on how much latency you could tolerate, you could have several servers and processes which have their own caches, updating from database in regular intervals. This could of course mean data corruption. Another way will be that if one server changes an entity it informs all other servers via sockets to invalidate that entity in their caches. A midway would be that all servers cache in memory, but every time an object is requested, only the timestamp (or version) is pulled from the database to decide wether the cache is up to date.


text:
Q: Como eu faço um trigger para a validação do angular-input-masks? Tenho um campo :
<input type="text" name="DataNascimento" class="form-control data"
    ng-model="EscolherCurso.DataNascimento" required ui-date-mask/>

que preferi usar o datepicker do jquery. Porém quando o jQuery preenche o valor, o angular não executa a validação de novo.
Tentei usar o evento do datepicker :
onSelect: function (dateText) {
        $(this).val(dateText);
            if ($(this).valid()) {
                $(this).removeClass('invalid').addClass('success');
            }

    }

mas não bombou.


text:
Q: Drupal 7: navigation menu with Views? I want to make a long page consisting of multiple nodes (each of the same Content Type). The page should have navigation on top of it that will allow to jump directly to the desired point of the long page, kind of like here: http://www.apple.com/macbookpro/features.html (there navigation is under the picture)
I used the Views module to assemble a long page from content, and for navigation I tried to use another View of the same content, only inserted in the top of the page as a block. I set this view to display grid of fields; it looks good. Only I could not figure out how to make each cell in the grid to become a link to the content on the same page.
I tried modifying views template, but there $rows variable turned out to be a string with already assembled html. Maybe I could possibly modify the content template, and insert some sort of condition that will change the way content looks based on what part of the page current view is located, but I am not sure how to do that either.

A: In the views, edit the field selected, and there are options there to configure the field as hyperlinks how you may want them. Also you can just let the field link directly to the node, there is an option for that. cheers


text:
Q: Creating QuickXorHash from fileBytes then comparing to Sharepoint hash I'm attempting to compare the hash of a file on the server to the one just uploaded to sharepoint prior to deleting.
MS Docs about QuickXor
I use the code from MS docs above, and have read a couple other SO articles.
I was making the mistake in the article below, but after correcting I'm still not getting the expected result.
Very Similar question on SO
    public static byte[] CalculateQuickXorHash(byte[] theFileBytes)
    {
        using (var hash = new QuickXorHash())
        {
            return hash.ComputeHash(theFileBytes);
        }
    }

From the call:
byte[] hash = FileStorageHelper.CalculateQuickXorHash(theFileBytes);
byte[] sharepointHash = Encoding.ASCII.GetBytes(jObject["file"]["hashes"]["quickXorHash"].ToString());
 if (hash == sharepointHash)....

The hash I'm getting from from sharepoint is 28bytes, the hash computed locally is only 20 bytes.

A: Seems the issue was using a byte array not a 64 bit string –


text:
Q: Add Icon to material-table "lookup" (material-ui React) I use material-ui for my project and material-table for data tables.
I am wondering to know, how can I use custom render (ex. add an icon) in column -> lookup.
for example from material-table documentation:
columns={[
        {
          title: 'Birth Place',
          field: 'birthCity',
          lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
        },
      ]}

it is here simple key-value as string. I want to add an icon to each value
something like this:

A: As per their code of renderLookUpFiled method, React.Element as a value of lookup object should work.
They are rendering {this.props.columnDef.lookup[key]} this means if we pass React.Element, it will render that as well, there might be some props warning but it should work
columns={[
        {
          title: 'Birth Place',
          field: 'birthCity',
          lookup: { 34:
 İstanbul
, 63:
<icon/> Şanlıurfa
 },
        },
      ]}

Code of renderLookUpFiled method from Material-table


text:
Q: Which Wi-Fi network has my HomePod mini? How can I verify the WiFi network being used by my HomePod mini? And, how can I resign the HomePod mini to use a different WiFi?
I used the Home app provided by Apple on my iPhone. I long-pressed the icon for the HomePod mini. I see many settings. But I do not see anything about its current network.

A: Open the HomePod settings and scroll down to "Wi-Fi Address" (in the section directly above "Reset HomePod...") Tap on "Wi-Fi Address" and it will switch to "Wi-Fi Network" and show you the network name.
If you have a Stereo Pair you have to click into "Speakers" and choose the specific device you want to examine first.


text:
Q: How do I configure phoenix to use sockets with postgresql PostgreSQL supports using unix sockets rather than TCP sockets. How do I configure the following block to use unix sockets.
# Configure your database
config :my_app, Sample.Repo,
  adapter: Ecto.Adapters.Postgres,
  database: "ecto_simple",
  username: "postgres",
  password: "postgres"

A: As of March 2018, Postgrex now supports connecting via sockets.
This can be done by supplying a socket or socket_dir option. Here's the changelog from where I picked this up and the source code where you can see an exhaustive list of all options.
From the source code:

*

*:socket_dir - Connect to Postgres via UNIX sockets in the given directory;
  The socket name is derived based on the part. This is the preferred method
  for configuring sockets and it takes precedence over the hostname. If you are
  connecting to a socket outside of the Postgres convention, use :socket instead;

*:socket - Connect to Postgres via UNIX sockets in the given path.
This is especially useful (I suppose) if you're on AppEngine which requires you to connect through an SQL proxy through localhost (127.0.01) which works only through a proxy connection.

A: PostgreSQL prefers unix sockets to TCP sockets on the grounds of performance and privacy. If not already available: TCP can be enabled on the server if you follow simple documentation and have access to do so.
The avenue of client connection is set via environment variables, in particular: PGHOST. From experience drivers such as libpq expect to work that way - it would be shocking if Postgrex did not.
See: https://hexdocs.pm/postgrex/Postgrex.html
The value to supply in PGHOST varies according to the configuration of the server as seen in the file: "postgresql.conf".
It is possible that you may need to create a directory for sockets and set permissions.  The following should help: http://iamvery.com/2013/06/17/postgresapp-with-unix-socket.html
To get a more precise answer you will need to mention your operating system and version; also your version of PostgreSQL.


text:
Q: Guard let construction, still getting fatal error: Index out of range I am trying to parse some data with this code:
func findDate(data: String?) -> String {
    guard let date: String? = (data!.componentsSeparatedByString("T"))[0] else{
        return "20000101"
    }
    return date!
}

I tried the guard structure to prevent errors when there is no data found, or it has a different structure, but I still get the error when I run it:
fatal error: Index out of range
Does somebody know how to fix this?

A: The access of the element at index zero always happens. If the result of the call to components(separatedBy:) returns an empty array, your code crashes. Also, you should avoid force unwrapping data.
A solution to these crashes is to use the first property of the array, which is optional, so you can safely unwrap it.
guard let date = data?.components(separatedBy: "T").first else {
    return "20000101"
}
return date.

Also, this could then be simplified using the nil coalescing operator:
return data?.components(separatedBy: "T").first ?? "20000101"

A: Please check out this code:
func findDate(data: String?) -> String {
    guard let date: String? = (data?.componentsSeparatedByString("T"))?[0] else{
        return "20000101"
    }
    return date!
}

findDate(nil)
findDate("")
findDate("98588T99")

A: There are two issues here:
1) Trying to access an index of an array that isn't large enough doesn't produce nil, it just crashes. For example, this code will crash:
let strings: [String] = []
guard let firstString = strings[0] else {
    // couldn't find firstString
}

Instead, use the first method:
let strings: [String] = []
guard let firstString = strings.first else {
    // couldn't find firstString
}

first attempts to access the first element of the array, and it returns nil if the array doesn't have a first element.
2) The purpose of guard let is to guarantee that the value you get out isn't nil. So your date value should be of type String, not String?, and you shouldn't have to force-unwrap it. For example:
let strings: [String] = ["one", "two", "three"]
guard let firstString = strings.first else {
    // no first string
}
print(firstString) // firstString is not nil, no need to unwrap it


text:
Q: Excel Interop - insert & add data by row Hey guys I need to insert empty rows below a certain row in an excel and then add data into those empty rows I inserted...
So far I am able to create empty rows but I am having a hell of a time trying to figure out how to set Range.Value to an array of type String
Method for inserting Rows:
private void shiftRows(int from, int numberof)
    {
        from++;
        Range r = oXL.get_Range("A" + from.ToString(), "A" + from.ToString()).EntireRow;

        for (int i = 0; i < numberof; i++)
            r.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown);
    }
 // so this would shift the below rows by numberof times.

This method is currently what I am stuck on... which is inserting an array into the new rows one row at a time
    public void inputRowData(string[] data, int rds)
    {
        int bestRow = getRowByRDS(rds);
        string val = getValueOfCell(bestRow, 6);
        if (val == null || val.Equals(""))
        {
            shiftRows(bestRow, data.Length);
            string[] formatedData = formatOutput(bestRow, data);
            for (int i = 0; i < formatedData.Length; i++)
            {
                Range r = oSheet.get_Range((bestRow + i).ToString() + ":" + (bestRow + i).ToString());
                r.set_Value(formatedData[i].Split('\t'));

// have tried r.Value = formatedData[i].Split('\t')
// formatedData is an array of string which contains data for each cell seperated by a tab

            }

        }
        else
        {
            Console.WriteLine("Line has some information already, skipping 1 more");
            shiftRows(bestRow, data.Length + 1);
        }

    }

A: I strongly advise you:

*

*NOT to insert rows but just write empty row instead (safety and performance)

*to set a big array object and do only ONE write in excel (performance)

example (i kept the shiftrows but you should really get rid of it):
public void inputRowData(string[] data, int rds)
{
    int bestRow = getRowByRDS(rds);
    string val = getValueOfCell(bestRow, 6);
    if (val == null || val.Equals(""))
    {
        shiftRows(bestRow, data.Length);
        string[] formatedData = formatOutput(bestRow, data);
        // transform formated data into string[,]
        var string[][] splitedData = formatedData.Select(s => s.Split('\t')).ToArray();
        var colCount = splitedData.Max(r => r.Lenght);
        var excelData = new string[splitedData.Length, colCount]
        for (int i = 0; i < splitedData.Length; i++)
        {
            for (int j = 0; j < splitedData[i].Length; j++)
            {
                 excelData[i,j] = splitedData[i][j];
            }
        }
        oSheet.get_Range("A" + bestRow.ToString()).Resize(splitedData.Length, colCount).Value = excelData;
    }
    else
    {
        Console.WriteLine("Line has some information already, skipping 1 more");
        shiftRows(bestRow, data.Length + 1);
    }

}


text:
Q: How to assert that app sends correct data to API server with POST request I am writing React.js application talking to API server. I have read tons of articles on how to mock these calls and send some fake response from API. I can do testing using @testing-library/react, I can easily mock axios with axios-mock-adapter and test fetch requests using HTTP GET method. But I cannot find anywhere how to make sure that my app, when it sends some POST request, sends correct data to API, i.e. that my app sends json payload with e.g. "id" field, or "name" field set to "abc", or something like this.
I am new to React.js. Please advise how to make tests asserting what the app sends to API. Is it possible?
Let's say that I have a function named doSomething, like below, called with onClick of some button.
const doSomething = async (userId, something) => {
    try {
        await REST_API.post('doSomething', {
            user_id: userId,
            something: something
        });
        return true;
    } catch (error) {
        window.alert(error);
        return false;
    }
};

REST_API above is axios instance.
How can I ensure that the I (or some other developer) didn't make a typo and didn't put "userId" instead of "user_id" in the payload of the request?

A: If you have to be sure you call correctly the api, I'd use jest as follow:
jest.mock('axios', () => ({
  post: jest.fn(),
}));

describe('test', () => {
  it('doSomething', () => {
    const userId = 123;
    const something = 'abc';
    doSomething(userId, something);
    expect(axios.post).toBeCalledWith(
      'doSomething', {
        user_id: userId,
        something,
      },
    );
  });
});

or if you use instance, define it in another file (axios_instance.js) and using the follow test:
jest.mock('./axios_instance', () => ({
  instance: {
    post: jest.fn(),
  },
}));

describe('test', () => {
  it('doSomething', () => {
    const userId = 123;
    const something = 'abc';
    doSomethingInstance(userId, something);
    expect(instance.post).toBeCalledWith(
      'doSomething', {
        user_id: userId,
        something,
      },
    );
  });
});

A: For your need I would use Swagger and its tooling. You would kill three birds with one stone :

*

*Have a proper API documentation : https://swagger.io/tools/swagger-ui/

*Protect Backend : Ensure inputs/outputs are valid, and throw detailed exception if a client sends bad data : https://github.com/cdimascio/express-openapi-validator-example

*Protect Frontend : Use client api generation to genrate js classes used by your clients .. That way they won't arbitrarily create objects manually and send them to server (crossing fingers) but use a dedicated API with setters : https://github.com/swagger-api/swagger-codegen
That way you have a rock solid Frontend + Backend + Documentation combo ..


text:
Q: How to check if comma separated strings have duplicate values in php I have a variable that contains comma separated strings and I would like to create a check if this variable has duplicate strings inside without converting it into an array. If it would make it any easier, each comma separated strings have 3 characters.
example.
$str = 'PTR, PTR, SDP, LTP';

logic: if any of the strings has a duplicate value then display an error.

A: This should work for you:
Just use strtok() to loop through each token of your string, with , as delimiter. Then use preg_match_all() to check if the token is more than once in the string.
<?php

    $str = "PTR, PTR, SDP, LTP";

    $tok = strtok($str, ", ");
    $subStrStart = 0;

    while ($tok !== false) {
        preg_match_all("/\b" . preg_quote($tok, "/") . "\b/", substr($str, $subStrStart), $m);
        if(count($m[0]) >= 2)
            echo $tok . " found more than 1 times, exaclty: " . count($m[0]) . "<br>";
        $subStrStart += strlen($tok);
        $tok = strtok(", ");
    }

?>

output:
PTR found more than 1 times, exaclty: 2

A: You are going to run into some issues with just using explode. In your example, if you use explode, you'll get:
'PTR', ' PTR', ' SDP', ' LTP'

You have to map trim in there.
<?php
// explode on , and remove spaces
$myArray = array_map('trim', explode(',', $str));

// get a count of all the values into a new array
$stringCount = array_count_values($myArray);

// sum of all the $stringCount values should equal size of $stringCount IE: they are all 1
$hasDupes = array_sum($stringCount) != count($stringCount);
?>


text:
Q: Hidden form value not retrieved or stored I have a simple form that can store the date and email, through php, but not a specific hidden value.
Goal: To store the hidden value "clubo" to the f.txt . Can you assist please?
HTML
<form method="post" action="test.php">
    <input type="hidden" name="clubo" value="clubo"/>
    <input type="hidden" name="date" value="date-through-echo"/>
    <input required type="email" name="email" placeholder="join!">
    <input type="submit" name="submitclub" value="Join">
</form>

PHP
if (isset($_POST['submitclub'])){
$clubo = $_POST['clubo'];
$date = $_POST['date'];
$email = $_POST['email'];
$file = fopen("f.txt", "a");
fwrite($file, $clubo);
fwrite($file, $date);
fwrite($file, $email);
fclose($file);
}

A: Just use $_POST array. For security reasons and also to avoid mistakesit is always better to make sure if you want to read from GET or POST. Of course always you need to check if form's action points to the proper script. Finally, your code can be just shortened and/or optimized:
form.html
<form method="post" action="test.php">
    <input type="hidden" name="clubo" value="clubo"/>
    <input type="hidden" name="date" value="date-through-echo" /> <!-- no need for readonly for hidden fields -->
    <input required type="email" name="email" placeholder="join!" /> <!-- no need for `multiple` attr for text fields -->
    <input type="submit" name="submitclub" value="Join">
</form>

test.php
if (isset($_POST['submitclub'])) {
    file_put_contents('g.txt',
        'Club: '.$_POST['clubo'] . PHP_EOL .
        'Date: '.$_POST['date'] . PHP_EOL .
        'E-mail: '.$_POST['email']
    );
}

or test.php if you want to use it in the append mode:
if (isset($_POST['submitclub'])) {
    file_put_contents('g.txt',
        'Club: ' . $_POST['clubo'] . PHP_EOL .
        'Date: ' . $_POST['date'] . PHP_EOL .
        'E-mail: ' . $_POST['email'] . PHP_EOL,
        FILE_APPEND
    );
}

Final thought:
Although I don't need your requirements, I assume that storing data may be done better with some database engine, starting from SQLITE to some more advanced engines like MySQL, Mongo, and others.


text:
Q: libgdx - ShapeRenderer in Group.draw renders in wrong colour MyGroup:
public class GShape extends Group{
private ShapeRenderer shape;

public GShape() {
    super();
    shape = new ShapeRenderer();
}

@Override
public void draw(SpriteBatch batch, float parentAlpha) {
    super.draw(batch, parentAlpha);
    shape.begin(ShapeType.Line);
    Gdx.gl10.glLineWidth(5);
    shape.setColor(1, 1f, 1f, 1f);
    shape.line(0, 0, 200, 100);
    shape.end();
}
}

Main:
public class GameControl implements ApplicationListener {
private Stage stage;
private GShape gShape;

@Override
public void create() {
    stage = new Stage(480,320,false);

    Texture t = new Texture(Gdx.files.internal("data/the200.png"));
    Image i = new Image(t);
    stage.addActor(i);
    gShape = new GShape();
    stage.addActor(gShape);
}

@Override
public void dispose() {
}

@Override
public void render() {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    stage.draw();
//  gShape.render();
}

@Override
public void resize(int width, int height) {
}

@Override
public void pause() {
}

@Override
public void resume() {
}
}

Colour of shape is not white? Why?
http://nw7.upanh.com/b3.s38.d3/352dd792eb77ce6df204a7af47ae1ac6_55348087.cos.jpg?rand=0.19125773780979216

A: You are probably getting inconsistent results because you're mixing SpriteBatch and ShapeRenderer contexts.  Both of these expect state they "store" in OpenGL to be maintained between begin() and end() calls.
The Actor draw() method is called in a context where the SpriteBatch begin() has already been called, so you need to end it before beginning your ShapeRenderer.  (And you need to restart the SpriteBatch before returning.
Like this:
@Override
public void draw(SpriteBatch batch, float parentAlpha) {
  super.draw(batch, parentAlpha);
  batch.end();   //  ** End the batch context
  shape.begin(ShapeType.Line);
  // .. draw lines ...
  shape.end()
  batch.begin(); // ** Restart SpriteBatch context that caller assumes is active
}


text:
Q: hover over two elements set effect to one element I have this list item in my nav , It has a dropDown menu

      Projects

King SALEH Bridge

Internationl future schools

Elwakeel Companies Group

and here is the styles
nav .myDropDown{
    display:none;
    position:absolute;
    min-height:160px;
    background-color:#ffb700;
    top:calc(15px + 100%)
}

and I want to display .myDropDown when hovering on li.projects and it still displayed when hovering on .myDropDown itself , and it disappear when the mouse became not in li.projects or .myDropDown .
I have this jquery code , but it doesn't work ?!
 $("nav .projects").hover(function(){
     $("nav .myDropDown").css("display","block");
 });
 $("nav .myDropDown").hover(function(){
           $(this).css("display","block");
  },function(){
           $(this).css("display","none");
 });

A: Why not only CSS?

ul.myDropDown{
  display: none;
}

li.projects:hover > ul.myDropDown{
  display: block;
}

      Projects

King SALEH Bridge

Internationl future schools

Elwakeel Companies Group

EDIT: I changed your top value and it works:

li.projects {
 position: relative;
}

ul.myDropDown{
  display:none;
    position:absolute;
    min-height:160px;
    background-color:#ffb700;
    top: 0px;
}

li.projects:hover > ul.myDropDown{
  display: block;
}

      Projects

King SALEH Bridge

Internationl future schools

Elwakeel Companies Group

A: You should probably use the CSS answers provided. But if you want to use javascript you should do it like this:
 $("nav .projects").hover(function(){
    $(this).find(".myDropDown").css("display","block");
 }, function(){
     $(this).find(".myDropDown").css("display","none");
 });

You can't keep the top:calc(15px + 100%) if you want it to overlap. If you keep a gap between the dropdown and the link you're removing it before entering it. It's the same with the CSS solution.
https://jsfiddle.net/80tbzcjh/1/

A: use this way
li:hover .myDropDown{dispaly:block;}


text:
Q: Make absolute positioned, centered div scroll without cutting off the first elements I have a list where items can get added or removed. The list needs to be vertically and horizontally centered to it's container. To do that I used the following style:
transform: translate(-50%, -50%);
left: 50%;
top: 50%;
position: absolute;

When elements get added into the list, the user should be able to scroll up and down to view all the elements. But with what I have, the user can scroll but the top part of the list is cut off. I believe that is because of the transform and top 50% I have used.
How do I get the list div to center horizontally and vertically AND scroll without issues when the list overflows?
This is my fiddle with what I have.
I'm using Angular 4.

A: you can set max-height to list and set overflow-y to auto so that whenever list items increased, you will get a scroll inside it.
.list {
    border: 1px solid red;
    width: 200px;
    transform: translate(-50%, -50%);
    left: 50%;
    top: 50%;
    position: absolute;
    max-height: 100%; // Added
    overflow-y: auto;  // Added
}

A: Try to make the child wrapper scrollable and a fixed height like this:
.list{
  max-height: 100%;
  overflow-y: scroll;
}


text:
Q: How can I find my followers? The other day, while attempting to snipe an enemy, Dogmeat kept stepping in my way, so I told him to wait, out of the way. After all the action was over, I went and collected my loot, and went on my way. Without Dogmeat.
Fortunately, I remembered where he was, I managed to retrieve him. However, if this happened again, how can I locate Dogmeat, or any of my other followers, diligently waiting for my return?


text:
Q: What's the cleanest way to tell typescript that each element of Object.keys(foo) is really a key of foo? playground
const foo = {
  a: 1,
  b: 2,
  c: 3
};

Object.keys(foo).forEach(key => {
  foo[key]++; // error: expression of type 'string' can't be used to index ....
})

There must be multiple ways to solve it. I'm looking for a recommended way with least impact on readability. Thanks!
==========
Edit:
Bonus: would be great if I can still have autocompletion when I type foo. in my codebase.

A: This should work:
(Object.keys(foo) as (keyof typeof foo)[]).forEach(key => {
    foo[key]++;
})

This isn't automatically done for you, because in theory it could be unsafe, but I played with various scenarios and couldn't produce a working demo with a runtime error.

A: I think the cleanest way would be to add a type to foo.
const foo: { [key: string]: number } = {
    a: 1,
    b: 2,
    c: 3
};

A: Type foo as a Record:
const foo: Record<string, number> = {
    a: 1,
    b: 2,
    c: 3
};

Object.keys(foo).forEach(key => {
    foo[key]++;
})

See the updated playground

A: TypeScript provides no way to express this at the time foo is declared because somebody might later add additional properties to foo, for instance by:
let o: any;
o = foo;
o.x = 'hello';

Then, Object.keys(foo) will also return x, but trying to increment 'hello' is probably not what you intend ...
More generally, in typescript, an object may always contain surplus properties, because this is what allows you to do:
interface Person = {
    name: string;
}

interface Student extends Person {
    university: string;
}

let student: Student = ...;
let person: Person = student;

That is, TypeScript can never be sure that an Object has no surplus properties, and that's why Object.keys returns Array<string> rather than Array<keyof typeof foo>.
In your case, I might do:
const fooKeys = Object.keys(foo) as Array<keyof typeof foo>;

right after declaring foo. That way, we take a snapshot of the keys we intend to iterate over before anybody else has a chance to modify them. Then, you can do:
fooKeys.forEach(key => {
    foo[key]++;
});


text:
Q: Saving to xml file using vb.net I am trying to save to an xml file using a datagridview. But its giving an error. Can anyone help me. Please find my code below.
i am getting this error :"Exception:Access to the path 'C:\settings.xml' is denied."
 Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Try
            'Write dataset to XML file
            DS.WriteXml(txtXMLFilePath)
            MessageBox.Show("XML data saved successfully to " + txtXMLFilePath)
        Catch ex As Exception
            MessageBox.Show("Exception: " & ex.Message)
        End Try
    End Sub

A: Make sure the .Net worker process has write access to that directory. You may be using the Administrator account, but the .Net worker process (typically 'IIS_IUSRS') is what is trying to write to the directory.
This is to ensure that your application is not an Administrator, as running an application pool under an account that has high-level user rights is a serious security risk.

A: The exception means that the account under which the application is executing does not have permissions to write to the file location specified.
You need to either use an account that does have these permissions or add the needed permissions to the account being used.