text:
Q: While loops with timer in c++ I'm trying to create a while loop that when either the string condition or the timer condition is met, the program will break out of the loop and print out the desired output. And when printing out the desired output, the output will contain the time difference from before and after comparing the answer.
But the loop doesn't run the way i expects it to. So can anyone help me figure out where is the problem with this piece of code?
Below is my code:
void startGame(time_t cd,int gl){
    string guessWord;
    time_t start, end, diff,timeLeft;

    cout << "Scrambled word is " << randomizeWord(gl) << endl;

    while (timeLeft != cd || guessWord.compare(originalWord) == 0)
    {
        start = time(0);
        cout << "You have " << cd << " seconds to guess." << endl;
        cout << "Enter guess : ";
        cin >> guessWord;
        end = time(0);
        diff = end - start;
        //total_time = total_time + diff;
        timeLeft = cd - diff;

        if(guessWord.compare(originalWord) != 0)
        {
            cout << "WRONG! Attempt ... You have " << timeLeft << "seconds left... Try Again" << endl;
            cout << "Enter guess : ";
            cin >> guessWord;
        }
        else
        {
            cout << "You are CORRECT! "<< timeLeft <<" seconds left. Your timing is "<< diff <<" seconds." << endl;
            break;
        }
    }
}

A: Condition explanation
Change your loop condition too:
while ((timeLeft <= cd) && (guessWord.compare(originalWord) != 0))

You will break out if either of the conditions fail. This is because the result of the && is false if either condition fails. So this will continue while a) You have time left and b) you have not guessed the word. Yur use of || will make the loop continue while either is true (thus both have to fail for the loop to exit).
Note: I personally think extra braces () are nice hear to make the expression more human readable. For an inexperienced programmer, they will not need to guess(look up) at the order of precedence
Time Left Calculation:
time_t start    = time(0);  // Make the start time absolute and outside the loop.
                            // Note: Use one line per variable declaration and initialize.
int    timeLeft = cd;       // timeLeft is a relative value that can be negative => `int`

// Notice I adjust timeLeft because of new definition.
while ((timeLeft > 0) && (guessWord.compare(originalWord) != 0))
{
    time_t end       = time(0);
    time_t timeTaken = end-start;        // Total time taken so Far.
    timeLeft         = cd - timeTaken;   // Time left is thus.

A: Your Starting time and end time both are time(0) that could be the problem.
    start = time(0);
    ..
    end = time(0);

A: As @JoshGreifer said, you need to first change timeLeft != cd to timeLeft > cd (or >=, although I would go with the former).
Additionally, before addressing your bug, I can see an issue with your program in that if the user takes a long time and diff > cd, then timeLeft will be negative. It will still allow the user another guess because the if(guessWord.compare(originalWord) != 0) condition is still met.
In your while loop, you are checking guessWord.compare(originalWord) == 0 before a guess has been made (but it's fine because it's null). You are also checking timeLeft != cd before timeLeft has been initialized.
I don't see where you are initializing originalWord, please post the relevant code. Is it a global variable? If so, this might be the source of your error.

A:
Hey guys, its working now after making few changes to it so please take a look at my answer and tell me if there is anything more i should change to the logic or the way I code my program. So i can learn to code programmes in the future the right way.
Below is the new code:
void startGame(time_t countDown,int gl){
//bool succeeded = false;
string guessWord;
time_t start, end, timeTaken;
int timeLeft = countDown;

cout << "Scrambled word is " << randomizeWord(gl) << endl;
start = time(0);//start the time once word is given
//timeLeft refers to the amt of time input by user
cout << "You have " << timeLeft << " seconds to guess." << endl;
cout << "Enter guess : ";
cin >> guessWord;
//the program stopped running after changing '||' to '&&' operator
//so meaning the condition is wrong
//so i changed it back to '||'
while ((timeLeft > 0) || (guessWord.compare(originalWord) == 0))
{
    end = time(0);//takes in the time at the moment user inputs
    timeTaken = end - start;//calculate the amt of time taken by user to input
    timeLeft = countDown - timeTaken;//calculate the amt of time left from the user input of time

    //check whether input by user is the same as the original word from the program
    if(guessWord.compare(originalWord) != 0)
    {
        cout << "WRONG! Attempt ... You have " << timeLeft << "seconds left... Try Again" << endl;
        cout << "Enter guess : ";
        cin >> guessWord;
    }
    else
    {
        cout << "You are CORRECT! "<< timeLeft <<" seconds left. Your timing is "<< timeTaken <<" seconds." << endl;
        break;
    }
}

}


text:
Q: Relativistic inelastic collisions Suppose a clay ball of mass $m$, travelling at speed $v=\sqrt{3}c/2$, collides with an identical clay ball that is at rest. They undergo a perfectly inelastic collision.
After performing the relevant calculations (using two separate methods), I found that $M=\sqrt{6}m$ (where $M$ is the mass of the composite ball) and $u=c/\sqrt{3}$ (where $u$ is the speed of the composite ball).
What I don't understand is how the mass of the composite ball can be greater than the sum of the two balls' separate masses, while its speed is also greater. Where does the extra energy come from?
I would have thought that if the mass of composite ball is greater than $2m$, its speed will be smaller than the pre-collision speed of just the one clay ball. I've looked at similar questions online (such as a question apparently from the Feynman lectures, where $v=4c/5$, rather than $\sqrt{3}c/2$), and in each case, if the mass went up then the speed went down and vice versa.
An explanation would be much appreciated (and if I messed up my algebra, pointing that out would also be appreciated).
Note: I didn't use the expression 'rest mass' for any of the masses above because the question didn't either. Not sure if that's relevant/important.

redpajama_set_name: RedPajamaStackExchange


text:
Q: why doesn't django log the specified application? I has some project with application named "work". The directory of the app also named work, and inside apps.py its also named "work", and in INSTALLED_APPS also, etc.
And I try to log just the application into file. So. I have prescribed the following settings in settings.py:
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'file_logger': {
            'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
        }
    },
    'handlers': {
        'file_logger': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': './logging.txt',
        },
    },
    'loggers': {
        'work.views': {
            'handlers': ['file_logger'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

I initialized inside my views.py (views.py of work app) logger like this:
logger = logging.Logger(__name__)

where __name__ is "work.views" (I checked this one via debugger)
and I have some view, which I want to log:
def view_timesheet(request, t_id=None):
    logger.warning('wwwwwwwwwwwwwwwww')
    # some code
    return HttpResponse('ok')

but when I execute the code of this view, nothing is written to the file. With what "wwwwwwwww" gets logged in the console
This confuses me, because it seems to me that I have done everything according to the documentation and everything should work
A few more details:
If I write "django" instead of "work.views" all django logs will end up in a file.
This leads me to believe that all my logging settings are correct except for the name of the logger key. I also tried to specify just the application "work" instead of "work.views". It also doesn't change anything
What could be wrong?
P.S: django 3.1.5


text:
Q: MERGE instead of CREATE for apoc.create.relationship() The procedure apoc.create.relationship(n1,RelType,{},n2) behaves accordingly to the CREATE statement.
If a relationship of type RelType already exists between nodes n1 and n2 apoc.create.relationship() will create a duplicate.
Is there an equivalent version of  apoc.create.relationship() that behaves like MERGE?

A: There is a procedure
apoc.merge.relationship()
which takes same parameters as apoc.create.relationship() and should do what you need.
It has been mentioned in this blog post, but it seems to be missing from documentation - see this issue.


text:
Q: Launching MySQL without a password I have installed MySQL. During the process of installation I was asked whether I want to determine a password for root user. Well, I entered a password.
Now I can access it through
mysql -u root -p
Well, it works.
The question is what will happen if I use just mysql command?
Well. This is what appears:
mysql>

I'm a bit confused. If I organize a password, how can I get access without entering it.
What privileges do I have in this case?

A: You are connected as ROOT (you can create,detele, alter,procedures,triggers,tables,configurations, users, Dbs, etc) , so you can do whatever you want. It's the same if you do:
mysql -u root -p

or
mysql -u root -p "my_root_pass"

(of course if you have one)
the mysql> just mean that you are connected to your database, however it's not recommended that use that user, also you should give him a password with the grant command.
if you want to see the user that you are using, you can use:
mysql> select current_user;

A: Try to access your database / tables when you see mysql>  If it doesn't give you an error, then your password most likely is still not set for the root account.  If this is the case, you can go ahead and execute this query to set your root password.
grant all privileges on *.* to 'root'@'localhost' identified by 'your new password';

A: The fact that you can "enter" MySQL doesn't mean that you have the ability to do anything. Try and create a database without supplying a password. Try and access a database without the password... I'm fairly sure that you won't be able to do either.


text:
Q: Await call to web service is stopping the execution flow of the program I have the following code:
public async Task IntiateDataFetchingProcess(string[] args)
{
    try
    {
        ProcessArgs(args);

        Log.Information("Run Mode: {RunModeID}", RunModeID);

        switch (RunModeID)
        {
            case RunModeType.A:
                await MethodAAsync();
                break;
            case RunModeType.B:
                await MethodBAsync();
                break;
            case RunModeType.C:
                TestMethod();
                break;
            default:
                break;
        }
    }
    catch (Exception ex)
    {
        throw;
    }
}

private async Task MethodBAsync()
{
   Console.WriteLine(DateTime.Now.ToLongTimeString());

   // Call to webservice to get the data
   var response = await _service.GetDataAsync(input1, request);

   Console.WriteLine(DateTime.Now.ToLongTimeString());
}

On debugging I found that the execution call comes to the below line (of method: MethodBAsync) and stops there.
var response = await _service.GetDataAsync(input1, request);

Can anyone help me to know is there anything that I am missing here.

A: Ah, your code is getting deadlocked!
You just need to add .ConfigureAwait(false); to each line that you are awaiting.
Example:
var response = await _service.GetDataAsync(input1, request);
becomes
var response = await _service.GetDataAsync(input1,
request).ConfigureAwait(false);
For more information on .ConfigureAwait(), Stephen Cleary wrote an awesome post on it.


text:
Q: Skipped a particular test method in testNG i have a method and i want to run this method and then showing skip in report
@Test(priority = 18, dataProvider="excelSheetNameAsMethodName",dataProviderClass=ExcelDataProvider.class)
public void addNotesFromRequisitionListAndDetailsPage(String username,String emailID,String password) throws Exception {

    cbatLoginPage().enterEmailID(emailID, password);
    cbatMyAccountPage().verifyApplicantTrackingTile();
    cbatMyAccountPage().selectTile("Applicant Tracking");
    cbatHomePage().switchWindow();
    cbatHomePage().verifyCBATHomePage(username);
    cbatHomePage().selectWidget("MY REQUISITIONS");
    cbatRequisitionPage().clickFirstNoteIcon();
    String noteText = "Test Note "+ RandomGenerator.GenerateRandomNumber(3);
    cbatRequisitionPage().enterNewNote(noteText);
    cbatRequisitionPage().clickFirstNoteIcon();
    cbatRequisitionPage().verifyNoteAdded(noteText);
    cbatRequisitionPage().selectRequisition();
    cbatRequisitionPage().clickFilledNoteIcon();
    noteText = "Test Note "+ RandomGenerator.GenerateRandomNumber(3);
    cbatRequisitionPage().enterNewNote(noteText);
    cbatRequisitionPage().clickFilledNoteIcon();;
    cbatRequisitionPage().verifyNoteAdded(noteText);
}

how can i Skipped this test case ?
i use throw new skipexception("message") but it doesn't work.

A: Consider you have method A and method B . add annotation depends on tag in your method B so if method A fails method B will be skipped.
@Test(priority = 1, dependsOnMethods = "administration_device_configure_custom_fields_default")


text:
Q: Show border triangle in navbar using CSS I am trying to create a nav bar with an arrow under the item hovered upon. Here's is what I am trying to make:

For the arrow I have used the pseudo elements before and after. Here is some of the code:

body {
  background: #FFFFFF;
  color: #FFFFFF;
  margin: 0px;
  padding: 0px;
  height: 100%;
}
.clear {
  clear: both;
}
.page-wrap {
  width: 980px;
  margin: 0px auto;
  height: 100%;
}
#main-menu {
  background: white;
  height: 55px;
  width: 100%;
  padding: 0px;
  margin: 0px;
  border-bottom: 1px solid black;
}
ul {
  font-family: Arial, Verdana;
  font-size: 18px;
  margin: 0;
  padding: 0;
  list-style: none;
}
ul li {
  display: block;
  position: relative;
  float: left;
}
li ul {
  display: none;
}
ul li a {
  display: block;
  text-decoration: none;
  color: black;
  padding: 0 9px 0 9px;
  background: white;
  margin-left: 1px;
  white-space: nowrap;
  line-height: 55px;
  font: 18px;
  font-family: Arial, Helvetica, sans-serif;
  outline: none;
}
ul li a:hover {
  color: black;
}
#menu a:hover:after {
  content: "";
  position: absolute;
  top: 40px;
  left: 50%;
  margin-left: -15px;
  width: 0px;
  height 0px;
  xxmargin: 0px auto;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-bottom: 15px solid black;
}

Recommended

Recent

Fiddle Link
The arrows are black in color, because of the border color. How to show just the borders of the arrow?

A: You can use a rotated pseudo element with borders :

body {
  background: #FFFFFF;
  color: #FFFFFF;
  margin: 0px;
  padding: 0px;
  height: 100%;
}
.page-wrap {
  width: 980px;
  margin: 0px auto;
  height: 100%;
}
#main-menu {
  background: white;
  height: 55px;
  width: 100%;
  padding: 0px;
  margin: 0px;
  border-bottom: 1px solid black;
}
ul {
  font-family: Arial, Verdana;
  font-size: 18px;
  margin: 0;
  padding: 0;
  list-style: none;
}
ul li {
  display: block;
  position: relative;
  float: left;
}
li ul {
  display: none;
}
ul li a {
  display: block;
  text-decoration: none;
  color: black;
  padding: 0 9px 0 9px;
  background: white;
  margin-left: 1px;
  white-space: nowrap;
  line-height: 55px;
  font: 18px;
  font-family: Arial, Helvetica, sans-serif;
  outline: none;
}
ul li a:hover {
  color: black;
}
#menu a:hover:after {
  content: "";
  position: absolute;
  bottom:-10px;
  left: 50%;
  margin-left:-10px;
  width: 20px;
  height: 20px;
  background:#fff;
  -webkit-transform:rotate(45deg);
  -ms-transform:rotate(45deg);
  transform:rotate(45deg);
  border-left:1px solid #000;
  border-top:1px solid #000;
  box-sizing:border-box;
}

Recommended

Recent

A: Just add before pseudo element like what you add :after
#menu a:hover:after {
  content: "";
  position: absolute;
  top: 41px;
  left: 50%;
  margin-left: -15px;
  width: 0px;
  height 0px;
  margin: 0px auto;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-bottom: 15px solid white;
}
#menu a:hover:before {
  content: "";
  position: absolute;
  top: 40px;
  left: 50%;
  margin-left: -15px;
  width: 0px;
  height 0px;
  margin: 0px auto;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-bottom: 15px solid black;
}

and i have updated you pen please check
http://codepen.io/anon/pen/vOxmGZ

A: It can be easily done using the before and after class. Change your pseudo element to before and than use an after pseudo element to draw a white triangle inside the black trainagle.
For your code, the css can be something like this
#menu a:hover:before {
    content: "";
    position: absolute;
    top: 40px;
    left: 50%;
    margin-left: -15px;
    width: 0px;
    height 0px;
    xxmargin: 0px auto;
    border-left: 15px solid transparent;
    border-right: 15px solid transparent;
    border-bottom: 15px solid black;

    }
#menu a:hover:after {
    content: "";
    position: absolute;
    top: 40px;
    left: 50%;
    margin-left: -15px;
    width: 0px;
    height 0px;
    xxmargin: 0px auto;
    border-left: 12px solid transparent;
    border-right: 12px solid transparent;
    border-bottom: 12px solid white;

}


text:
Q: create CSS grid without writing a div for each cell I need a grid with 100 cells for a battleship game I'm making (using html, css, and JavaScript), but I don't want to create 100 divs in html to make it.

  ...

Is there way were I can avoid this and then just access them by parent in css?
.cell:nth-child(n) {
  //code
}

I know a way where I can work around this without using a grid, but this seems the most simple way if I can just get past this. Any help would be appreciated.

A: You can programmatically create them using Javascript:

var container = document.querySelector('.container')

for (var i = 0; i < 100; i++) {
  var el = document.createElement('div')
  el.classList.add('item-' + (i + 1))
  container.appendChild(el)
}

console.log(container.children.length) // 100

If you inspect by pressing Cmd/Ctrl+Shift+C in Chrome, you can see that there are a hundred divs.
Each of them has a class attribute that equals item-n, where n is a number between 1 and 100.

A: I thought you might need some CSS as well? I used @GalaxyCat105's script (above) and added some grid-style magic.

var container = document.querySelector('.container')

for (var i = 0; i < 100; i++) {
var el = document.createElement('div')
el.classList.add('item-' + (i + 1))
container.appendChild(el)
}

console.log(container.children.length) // 100
@import url('https://fonts.googleapis.com/css?family=Nunito+Sans:400,700|Cormorant+Garamond:300,700|Titillium+Web:200,200i,400,400i,700|Orbitron:700&display=swap');

:root {
    --color-woodsmoke:      #161B1E;
    --color-boulder:        #767676;
    --color-gallery:        #F0F0F0;
}

*, *:before, *:after {
    box-sizing: border-box;
}

body {
    font-family: 'Nunito Sans', sans-serif;
    font-size: 20px;
    line-height: 1.4;
    color: var(--color-woodsmoke);
    margin: 0;
}

h1 {
    font-size: 3rem;
    text-align: center;
}

.container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: .5em;
    padding: 1em;
}

[class^="item"] {
    min-height: 10em;
    background: var(--color-gallery);
    border: 1px solid var(--color-boulder);
    box-shadow: 1px 2px 4px rgba(0,0,0,0.04);
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>100 Items</title>

One hundred items


text:
Q: When inserting a record, Wordpress automatically set non set variable to 0 I have this php snippet:
$sql = "
    CREATE TABLE $tablename (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        code varchar(255) NOT NULL UNIQUE,
        name varchar(255) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        created_by mediumint(9) NOT NULL,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NULL,
        updated_by mediumint(9) NULL,
        PRIMARY KEY (id)
    ) $charset_collate;
";

$wpdb->query($sql);

And later, later on I'm running this:
$wpdb->insert($tablename, ['code' => 'test', 'name' => 'Test'], ['%s','%s']);

What should lead to the MySQL exception saying 'created_by cannot be null', but except this it is set to 0.

I tried manual insert:
INSERT INTO `my_table` (`code`, `name`) VALUES ('test_list2', 'Test List 2')

And I got expected exception.

I also tried to put trigger before insert to be sure, that change went from the Wordpress:
delimiter $$

CREATE TRIGGER before_insert_on_my_table
    BEFORE INSERT ON my_table
    FOR EACH ROW
    BEGIN
        IF NEW.created_by IS NULL THEN
            SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'created_by column has to be set to current user id and not null';
        ELSEIF NEW.created_by = 0 THEN
            SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'created_by column has to be set to current user id and not 0';
        END IF;
    END$$

BUT that trigger return message: 'created_by column has to be set to current user id and not null'.

Knows anybody what's going on?


text:
Q: Подскажите по загрузке данных в Unity (архитектурное решение) Рад Вас приветствовать
Введение: создаётся карточная игра с разными типами карт (например карты "Враг" и карты "Предмет"). Каждый тип имеет свои данные. Так как этих карт будет большое количество, было принято решение загружать данные о картах из json файла.
Пример загрузки карт типа "Враг":
{
 "AllEnemies": [
{
  "Id": 0,
  "CardName": "Big fly",
  "Stats": [ 0.5, 0, 5, 0.25, 70 ],
  "Sprites": [ "someSprite", "someSprite"]
},
{
  "Id": 1,
  "CardName": "Bug",
  "Stats": [ 0.5, 0.25, 30, 1.4, 15 ],
  "Sprites": [ "someSprite", "someSprite"]
}
}

Соответственно у других типов карт сериализуемые поля будут отличаться.
Вопрос: как архитектурно и в какой момент времени лучше сделать загрузку этих данных?
Рассказываю свою реализацию, которую я считаю громоздкой и неверной, но ничего лучше придумать пока что не могу
У меня есть абстрактный класс
public abstract class LoadCardsFromJson : MonoBehaviour
{
    [SerializeField]
    private Texture2D _spriteSheet;
    protected Sprite[] allSprites;

    private void Awake()
    {
        allSprites = Resources.LoadAll<Sprite>("CardSprites/" + _spriteSheet.name);
    }
    public abstract List<Card> LoadCardsFromFile(string fileName);
}

Который будет наследоваться классами, отвечающих за загрузку каждого типа карты, например загрузка карт врагов:
public class LoadEnemies : LoadCardsFromJson
{
    public override List<Card> LoadCardsFromFile(string fileName)
    {
        List<Card> returnEnemies = new List<Card>();
        //логика загрузки карт врагов
        return returnEnemies;
    }
}

Также есть абстрактный класс CardController,который будет наследоваться остальными контроллерами.
public abstract class CardController : MonoBehaviour
{
    private CardView _cardView;
    private List<Card> _cards;

    public abstract void LoadCards();
}

Каждый класс, который унаследует CardController, должен будет реализовать метод LoadCards() и будет содержать в себе нужный Load класс
(для EnemyController - LoadEnemies, для ItemController - LoadItem, и т.д.)
Например, EnemyController будет выглядеть так:
public class EnemyController : CardController
{
    [SerializeField]
    private LoadEnemies _loadEnemies;

    private List<Card> _allEnemies = new List<Card>();

    private void Awake()
    {
        LoadCards();
    }

    public override void LoadCards()
    {
        _allEnemies = _loadEnemies.LoadCardsFromFile("Enemies");
    }

На Unity сцене будет пустой GameObject, содержащий в себе все Controller'ы (EnemyController, ItemController и т.д.) и при запуске сцены в каждом будет запускаться метод Awake() и, соответственно, подгружаться все данные из json файлов
Но эта реализация мне очень не нравится по следующим причинам:

*

*Дублирование кода для каждого типа

*Для каждого нового типа данных мне нужно будет создавать большое количество кода, который уже написан, но используется чуть иначе в других типах карт

В связи с этим я ищу больше архитектурное решение моей проблемы, если это вообще проблема. Если можно этот код сделать более абстрактам и удободополняемым, я буду рад прочесть любые комментарии на этот счёт
P.S. Я думал о том, что это всё можно привязать через события, но так и не придумал как именно

A: LoadCardsFromJson, судя по названию он из некого источника, и из json выдавать модели данных в виде соответствующих типу структур, но вместо этого вижу текстуры и спрайты... что? Подбором ресурсов по данным это другая ответственность. В Unity3D для этих дел есть JsonUtility.
LoadEnemies, зачем он нужен не понимаю, при сериализации твоего одного большого джейсена выйдет что-то типа:
[Serializable]
public struct AllCardData
{
    public ItemCardData[] AllItems;
    public EnemyCardData[] AllEnemies;
}

Названия ужасные, почему нельзя просто items и enemys?
CardController... если не знаешь чем занимается класс и в чем его ответственность, назови его controller, древняя традиция. Есть визуализация, лист кард и еще грузит карты... что это? зачем это?

Дублирование кода для каждого типа

Напиши метода в базовом классе и не придется дублировать его в наследниках, а просто вызывать метод.

Для каждого нового типа данных мне нужно будет создавать большое количество кода, который уже написан, но используется чуть иначе в других типах карт

Что бы этого избежать, есть наследование, абстракция и вообще можно выделять поведения в самостоятельные классы.

Вообще это не имеет никакого смысла хранить и грузить все данные из json. Все карты в игре, их картинки, звуки, эффекты и т.д. изначально в проекте, а не на сервере, если добавляются новые, выпускается апдейт. Храня данные в тексте потом геморой связывать их с упомянутыми ресурсами, и вообще грузить... зачем это нужно?
Все можно хранить и настроить в ScriptableObject
public class CardData : ScriptableObject
{
    [SerializeField] private string _name;
    [SerializeField] private Sprite _image;
    [SerializeField] private AudioClip _useClip;
    ...

    public string Name => _name;
    public Sprite Image => _image;
    public AudioClip UseClip => _useClip;
    ...
}

[CreateAssetMenu(fileName = "UnitCard", menuName = "Card/Data/Unit")]
public class UnitCardData : CardData
{
    ...
}

[CreateAssetMenu(fileName = "ItemCard", menuName = "Card/Data/Item")]
public class ItemCardData : CardData
{
    ...
}

[CreateAssetMenu(fileName = "CardsDataCollection", menuName = "Card/DataCollection")]
public class CardsDataHolder : ScriptableObject
{
    [SerializeField] private CardData[] _collection;

    public IEnumerable<CardData> Collection => _collection;
    public IEnumerable<UnitCardData> UnitCollection =>
        _collection.Where(c => c is UnitCardData).Cast<UnitCardData>();
    public IEnumerable<ItemCardData> ItemCollection =>
        _collection.Where(c => c is ItemCardData).Cast<ItemCardData>();
}

public class Card
{
    protected readonly CardData data;

    protected Card (CardData data)
    {
        this.data = data;
    }

    public virtual void Use ();
}

public class UnitCard : Card
{
    public UnitCard (EnemyCardData data) : base(data)
    {
    }

    public UnitCardData UnitData => data as UnitCardData;

    public override void Use ()
    {
        ...
    }
}

И какой нибудь генератор карт, который кастит типы данных и создает соответствующие карты
public static class CardDataExtension
{
    public static Card GetCard (this CardData data)
    {
        if (data is UnitCardData uData)
            return new UnitCard(uData);
        else if (data is ItemCardData iData)
            return new ItemCard(iData);
        else
            throw new Exception("unrecognized card data type");
    }
}

public class Foo : MonoBehaviour
{
    [SerializeField] private CardsDataHolder _cards;

    public void DoSometing ()
    {
        var data = _cards.UnitCollection.First();
        UnitCard card = data.GetCard() as UnitCard;
    }
}


text:
Q: How to select class properties via jQuery This is the HTML in question:
xxx a01
xxx a021
xxx aa021
xxx aaa2021

On click on a link, jQuery:
$("a").click(function(){
   alert($(this).html()); // we get xxx a01 , xxx a021 and so on..
})

How do I get the class value, such as a01, b02, c03 and so on?
thanks.

A: Use this.className, it's faster and less redundant than $(this).attr("class").
$("a").click(function(){
    alert(this.className);
});

*

*element.className - Mozilla Developer Network

Most attributes are directly accessible as properties of the element, so wrapping jQuery around this and using attr() or prop() are generally unnecessary.

Read more on this at http://whattheheadsaid.com/2010/10/utilizing-the-awesome-power-of-jquery-to-access-properties-of-an-element (plug).

A: You can use jQuery's .attr() method in order to retrieve any attribute from an element.
$(this).attr("class")

A: alert($(this).attr('class'));

http://api.jquery.com/attr/


text:
Q: Procura uma variável no JSP Trabalho com várias páginas JSP que se comunicam, e atualmente preciso encontrar uma variável que está presente em várias páginas, preciso encontrar onde ela está sendo declarada.

A: Existe a Opção "Buscar em Projetos" que você encontra a partir do menu "Editar". Nela tem vários parâmetros que você insere para efetuar a busca, tais como:

*

*Palavra a ser pesquisada nos projetos

*Extensão de arquivo;

*Projeto a ser pesquisado;
Estou usando a versão 8 e funcionou.

Fonte:
  http://pt.wingwit.com/P/java-programming/89248.html#.U205lyjpx0c


text:
Q: Testing anonymous function equality with Jest Is there a way to test anonymous function equality with jest@20?
I am trying to pass a test similar to:
const foo = i => j => {return i*j}
const bar = () => {baz:foo(2), boz:1}

describe('Test anonymous function equality',()=>{

    it('+++ foo', () => {
        const obj = foo(2)
        expect(obj).toBe(foo(2))
    });

    it('+++ bar', () => {
        const obj = bar()
        expect(obj).toEqual({baz:foo(2), boz:1})
    });
});

which currently yields:
  ● >>>Test anonymous function equality › +++ foo

    expect(received).toBe(expected)

    Expected value to be (using ===):
      [Function anonymous]
    Received:
      [Function anonymous]

    Difference:

    Compared values have no visual difference.

  ● >>>Test anonymous function equality › +++ bar

    expect(received).toBe(expected)

    Expected value to be (using ===):
      {baz: [Function anonymous], boz:1}
    Received:
      {baz: [Function anonymous], boz:1}

    Difference:

    Compared values have no visual difference.

A: In such situation, without rewriting your logic to use named functions, you don't really have another choice other than declaring the function before the test, e.g.
const foo = i => j => i * j
const foo2 = foo(2)
const bar = () => ({ baz: foo2, boz: 1 })

describe('Test anonymous function equality', () => {
  it('+++ bar', () => {
    const obj = bar()
    expect(obj).toEqual({ baz: foo2, boz: 1 })
  });
});

Alternatively, you can check whether obj.bar is any function, using expect.any(Function):
expect(obj).toEqual({ baz: expect.any(Function), boz: 1 })

which might actually make more sense depending on the context of the test.


text:
Q: Significance of differentiation of the equation of trajectory of a projectile with respect to different variables The original question was:

A fighter plane is flying horizontally at a height of 250 m from ground with constant velocity of 500m/s.It passes exacily over a cannon which can fire a shell at any time in any direction with a speed of 100 m/s. Find the duration of time for which the plane is in danger of being hit by a cannon shell.
Note: Just to clear any confusions, the plane is passing exactly over the canon, so the whole action is taking place in 2D.

My attempt:
The equation of trajectory for the cannon shell is:
$$y=x\tan\theta -\frac{gx^2\sec^2\theta}{2u^2}$$
Now comes the part where I will have to find the boundary till where the danger zone for the plane extends to.
The questions that came up at this stage were:
1) With respect to which variable($x,y,\theta)$ should the equation of trajectory should be partially differentiated?
2) What would be the significance or what would the equations represent physically after it has been differentiated with any of the three variables $(x,y,\theta)$?
3) In order to obtain the maximum range of danger zone, which variable(s) must be maximized?
However, the answers for Q.1 & Q.2 aren't yet completely and convincingly known to me but my opinion on Q.3 is as follows:
For maximum range of the danger zone, I will need to adjust my canon in such a way that it adjusts its $\theta$(projection angle) to give maximum x & y.
Therefore, differentiating the $x$ or $y$ with respect to $\theta$ and equating $\frac{\partial y}{\partial\theta}=0$,
We obtain, $\tan\theta=\frac{u^2}{gx}$ . Substituting this value of $\tan\theta$ we can obtain the maximum area of danger zone.
I would like to know the answers to my first (if my answer to the 3rd question is correct then the answer for the first question is clear) and second question and whether my opinion on the third question is correct or not.


text:
Q: Implementing a 3D Matrix in C++ using Nested std::vector I have a 3D Matrix with the MxNxL elements. Both M and N are known at the compile time. Whereas, L is variable and depends on user's input. But it will be provided at the beginning of the program and will never change during the life time of the program. I want to implement this Matrix in C++11 and I want to give the user the flexibility to rotate the 3D Matrix along both the the 1st and 2nd dimension of the matrix.
I would like to know what is the best and most efficient design option to implement this Matrix?
I have seen the below solution which uses std::vector. With std::vector the user can rotate any dimension using std::rotate. The solution is taken from this thread. However, vsoftco mentions that it is not good to use nested vector but rather make it linear. But since I have the requirement of rotating across dimension, having linear array will make the processing hard.
#include <vector>

#define M_SIZE 360
#define N_SIZE 180

template<typename T>
using vec = std::vector<T>;

int main()
{
    uint16_t L;
    std::cin << L;
    vec<vec<vec<double>>> v{M_SIZE, vec<vec<double>>{N_SIZE, vec<double>{L}}};
}

Again, using dynamic c array is a possible solution but std::rotate would only work on the last dimension of the 3D Matrix.
Note: I would prefer to do this without relying on a third party library.

A: I don't know if this will help you to achieve what you are after but this is a Matrix class that I have started to build using modern C++ features; such as variadic templates. The Matrix Class is self contained into a single header file.
#ifndef MATRIX_H
#define MATRIX_H

#include <cstddef>  // std::size_t
#include <numeric>  // std::accumulate
#include <vector>

namespace /*Your namespace name here*/ {

template<typename Type, std::size_t... Dims>
class Matrix {
public:
    static const std::size_t numDims_ = sizeof...(Dims);

private:
    std::size_t numElements_;

    std::vector<Type> elements_;
    std::vector<std::size_t> strides_;

public:
    Matrix() noexcept;

    template<typename... Args>
    Matrix(Args&&... args) noexcept;

    const Type& operator[](std::size_t idx) const;

    std::size_t numElements() const { return elements_.size(); }

    const std::vector<std::size_t>& strides() const { return strides_; }
    const std::vector<Type>& elements() const { return elements_; }
};

template<typename Type, std::size_t... Dims>
Matrix<Type, Dims...>::Matrix() noexcept :
    strides_({ Dims... }) {
    using std::begin;
    using std::end;
    auto mult = std::accumulate(begin(strides_), end(strides_), 1, std::multiplies<>());
    numElements_ = mult;
    elements_.resize(numElements_);
}

template<typename Type, std::size_t... Dims>
template<typename... Args>
Matrix<Type, Dims...>::Matrix(Args&&... args) noexcept :
    elements_({ args... }),
    strides_({ Dims... }) {
    numElements_ = elements_.size();
}

template<typename T, std::size_t... d>
const T& Matrix<T, d...>::operator[](std::size_t idx) const {
    if (idx > numElements_)
        throw std::runtime_error("Invalid index");
    return elements_[idx];
}

} // Your namespace name here
#endif MATRIX_H

And a small sample program using it:
#include <iostream>
#include <exception>

#include "Matrix.h"

int main() {
    try {
        using /*your namespace name here*/;
        Matrix<double, 2, 2, 2> mat( 1.0 ,1.1, 1.2, 1.3,
                                     1.4, 1.5, 1.6, 1.7 );

        // Print the elements from the use of getting the vector
        for (auto& e : mat.elements()) {
            std::cout << e << " ";
        }
        std::cout << '\n';

        // Print the elements from the use of using operator[]
        for ( std::size_t n = 0; n < mat.numElements(); n++ ) {
            std::cout << mat[n] << " ";
        }
        std::cout << '\n';

        // Print out the strides
        std::cout << "Number of strides: " << mat.numDims_ << '\n';
        for (auto& s : mat.strides()) {
            std::cout << s << " ";
        }
        std::cout << '\n';

    } catch ( std::exception& e ) {
        std::cerr << e.what();
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

-Output-
 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7
 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7
 Number of strides: 3
 2 2 2

This class is far from complete as it is only just the containing shell of any arbitrary Dimensional Size of Any MxNx...Zx... Matrix. In the template argument list it expects a single Type: int, float, char, user defined etc. The variadic arguments for the tempale arguments after the Type determines how many Dimensions this matrix has, and the dimensional size of each dimension. Examples:
Matrix<type,1> = a 1 matrix which in essence would be a scalar
Matrix<type,1,2> = a 1x2 matrix and would be considered a vector
Matrix<type,3,1> = a 3x1 matrix and would be considered a vector
Matrix<type,2,2> = a 2x2 matrix
Matrix<type,3,4> = a 3x4 matrix
Matrix<type,3,3,3> = a 3x3x3 Matrix (3D-Matrix) and has 27 elements
Matrix<type,3,4,5,3,2> = a 3x4x5x3x2 (5D - Matrix) and has 360 elements

// The number of elements will always equal the product of all of the strides.
// When creating an arbitrary matrix size; careful consideration needs to be taken
// when it comes to how many dimensions and the size of that dimension. Even lower
// dimensional matrices can explode in the amount of elements...
Matrix<type, 128, 356, 242> = a 128x356x242 (3D - Matrix) but has 11,027,456 elements

// It is the Matrix's user defined variadic constructor that the number of arguments
// in the parameter list that has to equal the total amount of elements defined by
// the product of all of its strides.

When working with higher dimensional matrices it is hard to visualize them, but they can easily be managed with the use of the strides vector. We can use these for proper indexing.
The challenging aspect of this design approach is being able to implement the actual arithmetic-computational operators. For this if we have two different matrices that have different strides, they will be treated as different types... and this is just with simple matrix arithmetic; when it comes to matrix multiplication things even get harder because the edges of Matrix A and Matrix B have to be of the same size. Ex: 4x2 * 2x3 would give a 4x3 Matrix. And this is only a 2D matrix issue, when getting into 3D, 4D, ... ND matrices the notation even gets harder. However this template approach does allow the code to be more generic and readable to be self contained into a single class as opposed to having many different matrix classes for various matrix sizes...


text:
Q: How to find out the rarkey value for delete key How to find out the rarkey value for delete key. If I use rarkey then I can't use any other key is it any alternative method for "on rawkeyDown theKey"

A: If you capture the rawKey value in a rawKeyDown handler, you must pass the message if you want any of the key presses to be handled by the engine. This is the case with any of the key messages you want to handle (e.g., rawKeyUp, keyDown, keyUp); if you do not pass the message, it's normal functionality will be preempted.
on rawKeyDown pCode
   if pCode is 65535 then
      # do what you want to do to handle the delete key here
   else
      pass rawKeyDown
   end if
end rawKeyDown


text:
Q: Реализация поиска по таблице mssql через C# Не работает поиск по БД. По идее, после нажатия по кнопке, в DataGridView должны оставаться только подходящие записи, но этого не происходит. Также, после нажатия кнопки, в DataGridView изменяется та запись, которую я хотел найти.
private void search_pl_but_Click(object sender, EventArgs e)
{
    connection.Open();
    if (фИОПловцаTextBox.Text != "" || фИОПловцаTextBox.Text != " ")
    {
        пловцыDataGridView.DataSource = "";
        SqlDataAdapter dataAdapter = new SqlDataAdapter($@"SELECT * FROM Пловцы WHERE ФИОПловца LIKE '%{фИОПловцаTextBox.Text}%'", connection);
        dataAdapter.Fill(swimmingPoolDataSet, "Пловцы");
        пловцыDataGridView.DataSource = swimmingPoolDataSet.Tables["Пловцы"];
    }
    else
    {
        load_data();
    }

    connection.Close();
}

A: if (...Text != "" || ...Text != " ")

Это условие выполняется всегда. Соответственно, ветка else не выполнится никогда.

Читаем документацию. Описание метода DataAdapter.Fill:

Добавляет или обновляет строки

То есть при каждом запросе вы добавляете новые строки в датасет. Старые при этом не удаляются.
Удалить их можно, например, методом Clear().

Если в вашем коде произойдёт исключение, то соединение останется открытым.
Вообще, датаадаптер сам открывает и закрывает соединение. Можно не вмешиваться в этот процесс.

Вот слегка облагороженный код.
private void search_pl_but_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrWhiteSpace(фИОПловцаTextBox.Text))
    {
        swimmingPoolDataSet.Tables["Пловцы"]?.Clear();

        string sql = "SELECT * FROM Пловцы WHERE ФИОПловца LIKE @name";
        string name = $"%{фИОПловцаTextBox.Text}%";

        using (var dataAdapter = new SqlDataAdapter(sql, connection))
        {
            dataAdapter.SelectCommand.Parameters.Add("name", SqlDbType.NVarChar).Value = name;
            dataAdapter.Fill(swimmingPoolDataSet, "Пловцы");
        }

        пловцыDataGridView.DataSource = swimmingPoolDataSet.Tables["Пловцы"];
    }
    else
    {
        load_data();
    }
}

Конечно, крайне желательно убрать кириллицу из кода.
Имена таблиц и sql-запросы не должны быть прописаны повсеместно в коде. Они должны браться из ресурсов или настроек. Или хотя бы заданы константами.
search_pl_but - что это за название? "but" - сокращеие от "butt"? А "pl" что значит? Вы сами это сможете сказать спустя несколько месяцев?


text:
Q: Nested Resource testing RSpec I have two models:
class Solution < ActiveRecord::Base
  belongs_to :owner, :class_name => "User", :foreign_key => :user_id
end

class User < ActiveRecord::Base
  has_many :solutions
end

with the following routing:
map.resources :users, :has_many => :solutions

and here is the SolutionsController:
class SolutionsController < ApplicationController
  before_filter :load_user

  def index
    @solutions = @user.solutions
  end

  private
    def load_user
      @user = User.find(params[:user_id]) unless params[:user_id].nil?
    end
end

Can anybody help me with writing a test for the index action?  So far I have tried the following but it doesn't work:
describe SolutionsController do
  before(:each) do
    @user = Factory.create(:user)
    @solutions = 7.times{Factory.build(:solution, :owner => @user)}
    @user.stub!(:solutions).and_return(@solutions)
  end

  it "should find all of the solutions owned by a user" do
    @user.should_receive(:solutions)
    get :index, :user_id => @user.id
  end
end

And I get the following error:
Spec::Mocks::MockExpectationError in 'SolutionsController GET index, when the user owns the software he is viewing should find all of the solutions owned by a user'
#<User:0x000000041c53e0> expected :solutions with (any args) once, but received it 0 times

Thanks in advance for all the help.
Joe
EDIT:
Thanks for the answer, I accepted it since it got my so much farther, except I am getting another error, and I can't quite figure out what its trying to tell me:
Once I create the solutions instead of build them, and I add the stub of the User.find, I see the following error:
NoMethodError in 'SolutionsController GET index, when the user owns the software he is viewing should find all of the solutions owned by a user'
undefined method `find' for #<Class:0x000000027e3668>

A: It's because you build solution, not create. So there are not in your database.
Made
  before(:each) do
    @user = Factory.create(:user)
    @solutions = 7.times{Factory.create(:solution, :owner => @user)}
    @user.stub!(:solutions).and_return(@solutions)
  end

And you mock an instance of user but there are another instance of User can be instanciate. You need add mock User.find too
  before(:each) do
    @user = Factory.create(:user)
    @solutions = 7.times{Factory.create(:solution, :owner => @user)}
    User.stub!(:find).with(@user.id).and_return(@user)
    @user.stub!(:solutions).and_return(@solutions)
  end

A: I figured out my edit, when a find is done from the params, they are strings as opposed to actual objects or integers, so instead of:
User.stub!(:find).with(@user.id).and_return(@user)

I needed
User.stub!(:find).with(@user.id.to_s).and_return(@user)

but thank you so much shingara you got me in the right direction!
Joe


text:
Q: What is the origin of != in the meaning "not equal to"? As a programmer I have always assumed that using != as meaning not equal to when writing text (usually on the internet) came from programming languages. Is this true or is the origin different?

A: Yes, this is from programming languages such as C and C++.

The symbol used to denote inequation — when items are not equal — is a
  slashed equals sign "≠" (Unicode 2260).
Most programming languages,
  limiting themselves to the ASCII character set, use ~=, !=, /=, =/=,
  or <> to represent their boolean inequality operator.

Source: Wikipedia.

(Edit: Combining vincente and Mark Hurd's comment with something extra.)
!= may have first appeared in the B language, which was a precursor to C. It does not appear in BCPL which was an inspiration for B, so perhaps the B designers were the first.
And some languages (including B and C) use !  for logical negation (aka NOT), so != is slightly more natural than > and the other ASCII-only operators. Again, BCPL is different: it uses ~a to mean "NOT a", but uses a!b for !(a+b).

A: C and the unix shells use != for not equal, it comes from the maths symbol ≠.
The earlier computer langauge FORTRAN that was (and is) used for more mathematical work uses .ne. because it was invented before the symbols on keyboards were standardised

A: Yes, this originated in the C language.


text:
Q: creating a lucene index to find parent based on data of children I am trying to understand how to build a lucene index for data that has a 1 to many relation.
suppose I have a table for families with id and family name
and a table of people with id, first name, and hobbies (which is  free text).
how would I create a lucene index that will help me find families that have family members that their hobbies match the search query (as full text search) ?
I want to get each matching family just once (even if there are several family members that their hobbies are a hit for the query.
What If I also had a hobbies field on the family record it self (in addition to personal hobbies) and I wanted to get all the families that either match on the family hobby or on the hobby of on of the family members ?

A: You may treat families as documents that are composed of hobbies (terms). Index hobbies in a searchable field, no matter they are family hobbies or personal hobbies. For the rest of the fields just store them as additional fields.


text:
Q: I want to create a computed column based off a substring of another column in SQL I have a column called TAG_
Data in the TAG_ column could like the below:
STV-123456
TV-12456
ME-666666
I want to create two computed columns
One that shows the first part of TAG_ before the hyphen
STV
TV
ME
One that shows the second part of TAG_ after the hyphen
123456
12456
666666
This shouldn't be hard but the light bulb is not on yet. Please help.

A: try this:
SELECT SUBSTRING(TAG_ ,0,CHARINDEX('-',TAG_ ,0)) AS before,
SUBSTRING(TAG_ ,CHARINDEX('-',TAG_ ,0)+1,LEN(TAG_ )) AS after from testtable

and the result:

Hope this helps!

A: Example for MySQL, syntax is likely different for other vendors:
create table t
( tag_ text not null
, fst text generated always as (substr(tag_, 1, locate('-', tag_)-1)) stored
, snd text generated always as (substr(tag_, locate('-', tag_)+1)) stored
);

Fiddle


text:
Q: On radio button click show text file data in textarea When a radio button is clicked i want to see data inside textarea that is written in test.txt file in html.

function radiobtn(proposal){
    document.getElementById("result").value=proposal;
}
<input type="textarea" name="params" id="result" required>

<input id="open" type="radio" name="proposal" onclick="radiobtn(this.value)" value = "READ"  >Data Entry


text:
Q: Rate of change Pandas Data Frame after grouping I am new to python pandas and have been trying to get the rate of return using pct_change().  I would like to get monthly rate of change by feedcode.
This my current code:
In [134]:
df3 = pd.read_csv(r'C:\Users\sector_set.csv')
df3.set_index('Date', inplace= True)
df3= pd.DataFrame(df3,columns = ['Feed','Close']) # filter specific col
grouped = df3.groupby('Feed')  #group by Feedcode
df3 = grouped.resample('BM', how=lambda x:x[-1]) #ending of every month only
df3['Rate_Return'] = df3.pct_change()  # Rate of Return of each feedcode
df3

OUTPUT:
                   Close  Rate_Return
Feed   Date
   A   2015-09-30  5.60     NaN
       2015-10-30  5.75    0.026786
  AAV  2015-09-30  4.32   -0.248696
       2015-10-30  4.62    0.069444

I have two issues:

*

*The calculated rate of return is incorrect as it reference prior day feedcode price to calculate the return for the next feed code. For example, Feed AAV 2015-09-30 should be NaN and not -0.248696

*I would like to remove all NaN
I am trying to calculate the returns to get something like this:
Output:
                   Close  Rate_Return
Feed   Date
   A   2015-10-30  5.75    0.026786
  AAV  2015-10-30  4.32    0.069444

What is the best way of doing this?
Thanks in advance for any help

A: IIUC you need groupby by Feed from multiindex and apply pct_change. Then you can use subset of df3, where column Rate_Return is notnull
df3['Rate_Return'] = df3.groupby(level=0).pct_change()
print df3
                 Close  Rate_Return
Feed Date
A    2015-09-30   5.60          NaN
     2015-10-30   5.75     0.026786
AAV  2015-09-30   4.32          NaN
     2015-10-30   4.62     0.069444

print df3[df3.Rate_Return.notnull()]
                 Close  Rate_Return
Feed Date
A    2015-10-30   5.75     0.026786
AAV  2015-10-30   4.62     0.069444


text:
Q: Multipanel with raster (spplot) and scatter plot in R I have one raster and one scatter plot that I want to put together in a single multipanel plot. However, the par(mfrow=c()) that usually works to put together different normal plots, doesn't work when I am trying to visualize a raster with the sp::spplot function. I am looking for a way to put both types of plots together in a single figure
This IS an example code of what I have been trying to do, but it ends with the plot in separate figures.
library(sp)

r <- raster(system.file("external/test.grd", package="raster"))
x <- rnorm(100, 1, 2)
y <- rnorm(100, 1, 5)

par(mfrow=c(1,2))
spplot(r)
plot(x, y)


text:
Q: C# calling an unmanaged C driver(dll) I'm really not sure what I am doing wrong. I am passing a string to my dll written in C from C# as lots of examples on the net state..for some reason the string is coming out as NULL in the C dll. Any idea of what I am doing wrong?
C:
 extern __declspec(dllexport) void Cmd(long CmdType,long DataPar, const char *DataStr);

 void Cmd(long CmdType,long DataPar,const char *DataStr)
 {
     // DataStr is NULL here even when passing a string with data in it
 }

C#:
    [DllImport(@"pjsua-i386-Win32-vc8-Debug.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]

    public static extern void Cmd(long CmdType, long DataPar,[MarshalAs(UnmanagedType.LPStr)]String s);

    Cmd(1,0,"TEST");

I've also tried other things like IntPtr and marshalling across the string but all turns out the same with NULL. And also a bunch of other things.

A: In Microsoft C++ and C, on 32 and 64-bit builds a long is only 32 bits.
However, in C# a long is always 64 bits.
So what I think is happening is that some of the bytes of the two 64 bit longs that are pushed onto the stack by the C# call are being popped off as the Data* in the C++.
Because the second parameter you're pushing is 0, it so happens that bytes with value 0 are being used for the pointer, hence it is null.
Change the declaration to int instead of long to solve your problem.

A: Did you try the below option:
    [DllImport(@"pjsua-i386-Win32-vc8-Debug.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    public static extern void Cmd(int CmdType, int DataPar,IntPtr s);

    Cmd(1,0,Marshal.StringToHGlobalAnsi(str));


text:
Q: How to restrict access to models in Ruby on Rails 4 using Pundit and Rolify I have only just jumped on the Rails in the last few months and have run into my first real snag in my current project which I have been unable to find an answer for.
My aim is to implement some fine grained control over which user role(s)/group(s), generated from Rolify and controlled by Pundit, have access to a particular category, subcategory or article via the Upmin admin console. A category/article should be capable of allowing more than one user role/group access to its contents.
The answer here demonstrates scoping a role to a particular instance of a model, which is nice, but I would also like to have that control from the model instance via a simple checkbox form in my applications admin console (Upmin_admin for those interested).
Am I right in thinking that there isn't too much to produce this functionality, other than creating a category/article instance view partial in the admin console which lists all of the roles/groups and their current CRUD settings for that particular category/article instance. Or am I missing a few intermediary steps?
A nudge in the right direction would be greatly appreciated.
Thanks!
Some background of my app:
In my web application I have nested resources, categories, articles and comments like so:
resources :categories do
  resources :articles do
    resources :microposts, only: [:new, :create, :edit, :destroy
  end
end

(I am aware it is not best practice to have nested resources deeper than one level, however I've only just jumped on the Rails train and :shallow = true wasn't delivering the results I was looking for.)
The categories act as nested sets courtesy of Awesome Nested Set and are capable of "holding" both categories and articles (and by extension comments).
Users are authenticated via an LDAP server using Devise - I will be configuring this in the near future to automatically allot a user to the correct group/role.

A: From re-reading the Rolify documentation I have come up with the beginnings of the solution to my problem.
Whenever a user creates a category, subcategory or article I'll run
user.add_role :current_role Model.Instance_id

which I can then query from the admin portal by getting the instances id. Then by querying all of the user roles within the system and comparing them against the instances associated roles, I can create the view partial for the admin console.
model_instance = Model.find(instance_id)
model_instance.roles #returns all of the roles associated with that instance

I would also need to create a few methods to handle the (mass)assignment/reassignment of roles so that when a checkbox is (de)selected that the expected result is achieved, such as adding a role/group to a instance and vice versa. Probably something along the lines of (ruby flavoured pseudocode to follow!!)
users = User.with_any_role(:some_role)

def assignRoleToModel(model_instance, users, role)
  if model_instance.roles.empty?
    users.each { |u| u.add_role creatorRole model_instance }
  end
  flash[:warning] = "#{Model_instance.name} already has that role assigned to it!"
end

where model_instance is the instance of the model I want to control group/role access to, users is a list of users who have the role I want to add to the model_instance and role is the role I wish to allow access to the model_instance.
Update
An example of how to control roles via a form https://github.com/RolifyCommunity/rolify/issues/246


text:
Q: ListView Not Updating When ItemsSource Changed I've done a lot of reading on this, but I'm evidently still missing something.  I could work around it by passing in an ObservableCollection to the class constructor but I want to understand why it's failing.    There is nothing in the output window indicating a broken binding.  A Visibility Converter I have on the ObservableCollection<> property works fine.  Here is the XAML.  the problem is with the DetailsListBox
<StackPanel Grid.Column="2" >
    <Label
        Name="DetailsLabel" Foreground="Black"  Height="20" Width="Auto"
        FontSize="8"
        Content="{Binding Description, Converter={StaticResource DetailConverter}}"
        Visibility="{Binding Path=DetailsList, Converter={StaticResource DetailsVisConverter}}"
        Background="Transparent"
        Margin="0" Padding="0"
        HorizontalAlignment="Center">
    </Label>
    <ListBox
        Name="DetailsList"
        ItemsSource="{Binding Path=DetailsList}"
        Visibility="{Binding Path=DetailsList, Converter={StaticResource DetailsVisConverter}}"
        >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding Path=.}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>

Here is the code-behind creating the class instance and setting up the ObservableCollection:
    NodeAsThumb hosthumb = CreateClusterNodeAsThumb(host);
    hosthumb.DataContext = hosthumb;
    ObservableCollection<string> PortDetails = new ObservableCollection<string>();
    foreach (PortResult pr in hostports) { PortDetails.Add(pr.Interface); }
    hosthumb.DetailsList = PortDetails;

Here is some of the class definition, including the PropertyChanged handler. OnPropertyChanged is getting called.  I originally had DetailsList as a List<>, but read it should be an ObservableCollection<> as it would fire the ICollectionChanged, but that doesn't appear to be happening.
public  class NodeAsThumb :FabricThumb, INotifyPropertyChanged
{

    private ObservableCollection<string> _detailsList = null;
    public ObservableCollection<string> DetailsList { get { return _detailsList; } set { _detailsList = value; OnPropertychanged("DetailsList"); } }

  // I have verified that this gets fired when DetailsList is assigned to
 public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, e);
    }

    private void OnPropertychanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

Lastly, the VisiblityConverter that does work, and is also bound to DetailsList.  When it is null, I want it hidden. I thought it might be the VisibilityConverter still having it collapsed, so I disabled it but ended up with an always empty list.
public class DetailsListVisiblityConverter : IValueConverter
{

    public Object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
        {
            return Visibility.Collapsed;
        }
        else
        {
            return Visibility.Visible;
        }
    }

    public Object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Here is the output window after setting the TraceLevel to High:
System.Windows.Data Warning: 56 : Created BindingExpression  (hash=1635228) for Binding (hash=30787047)
System.Windows.Data Warning: 58 :   Path: 'DetailsList'
System.Windows.Data Warning: 60 : BindingExpression (hash=1635228): Default mode resolved to OneWay
System.Windows.Data Warning: 61 : BindingExpression (hash=1635228): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 62 : BindingExpression (hash=1635228): Attach to System.Windows.Controls.ListBox.ItemsSource (hash=59834015)
System.Windows.Data Warning: 67 : BindingExpression (hash=1635228): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=1635228): Found data context element: ListBox (hash=59834015) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=1635228): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=1635228): Resolve source deferred
System.Windows.Data Warning: 56 : Created BindingExpression (hash=61434729) for Binding (hash=30787047)
System.Windows.Data Warning: 58 :   Path: 'DetailsList'
System.Windows.Data Warning: 60 : BindingExpression (hash=61434729): Default mode resolved to OneWay
System.Windows.Data Warning: 61 : BindingExpression (hash=61434729): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 62 : BindingExpression (hash=61434729): Attach to System.Windows.Controls.ListBox.ItemsSource (hash=51565323)
System.Windows.Data Warning: 67 : BindingExpression (hash=61434729): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=61434729): Found data context element: ListBox (hash=51565323) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=61434729): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=61434729): Resolve source deferred
System.Windows.Data Warning: 56 : Created BindingExpression (hash=27129916) for Binding (hash=30787047)
System.Windows.Data Warning: 58 :   Path: 'DetailsList'
System.Windows.Data Warning: 60 : BindingExpression (hash=27129916): Default mode resolved to OneWay
System.Windows.Data Warning: 61 : BindingExpression (hash=27129916): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 62 : BindingExpression (hash=27129916): Attach to System.Windows.Controls.ListBox.ItemsSource (hash=40297137)
System.Windows.Data Warning: 67 : BindingExpression (hash=27129916): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=27129916): Found data context element: ListBox (hash=40297137) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=27129916): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=27129916): Resolve source deferred
System.Windows.Data Warning: 67 : BindingExpression (hash=1635228): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=1635228): Found data context element: ListBox (hash=59834015) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=1635228): Activate with root item NodeAsThumb (hash=46479497)
System.Windows.Data Warning: 107 : BindingExpression (hash=1635228):   At level 0 using cached accessor for NodeAsThumb.DetailsList: RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 104 : BindingExpression (hash=1635228): Replace item at level 0 with NodeAsThumb (hash=46479497), using accessor RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 101 : BindingExpression (hash=1635228): GetValue at level 0 from NodeAsThumb (hash=46479497) using RuntimePropertyInfo(DetailsList): <null>
System.Windows.Data Warning: 80 : BindingExpression (hash=1635228): TransferValue - got raw value <null>
System.Windows.Data Warning: 89 : BindingExpression (hash=1635228): TransferValue - using final value <null>
System.Windows.Data Warning: 67 : BindingExpression (hash=61434729): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=61434729): Found data context element: ListBox (hash=51565323) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=61434729): Activate with root item NodeAsThumb (hash=1807185)
System.Windows.Data Warning: 107 : BindingExpression (hash=61434729):   At level 0 using cached accessor for NodeAsThumb.DetailsList: RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 104 : BindingExpression (hash=61434729): Replace item at level 0 with NodeAsThumb (hash=1807185), using accessor RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 101 : BindingExpression (hash=61434729): GetValue at level 0 from NodeAsThumb (hash=1807185) using RuntimePropertyInfo(DetailsList): <null>
System.Windows.Data Warning: 80 : BindingExpression (hash=61434729): TransferValue - got raw value <null>
System.Windows.Data Warning: 89 : BindingExpression (hash=61434729): TransferValue - using final value <null>
System.Windows.Data Warning: 67 : BindingExpression (hash=27129916): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=27129916): Found data context element: ListBox (hash=40297137) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=27129916): Activate with root item NodeAsThumb (hash=22613965)
System.Windows.Data Warning: 107 : BindingExpression (hash=27129916):   At level 0 using cached accessor for NodeAsThumb.DetailsList: RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 104 : BindingExpression (hash=27129916): Replace item at level 0 with NodeAsThumb (hash=22613965), using accessor RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 101 : BindingExpression (hash=27129916): GetValue at level 0 from NodeAsThumb (hash=22613965) using RuntimePropertyInfo(DetailsList): <null>
System.Windows.Data Warning: 80 : BindingExpression (hash=27129916): TransferValue - got raw value <null>
System.Windows.Data Warning: 89 : BindingExpression (hash=27129916): TransferValue - using final value <null>
'FabricAnalyzer.exe' (CLR v4.0.30319: FabricAnalyzer.exe): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework-SystemCore\v4.0_4.0.0.0__b77a5c561934e089\PresentationFramework-SystemCore.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
System.Windows.Data Warning: 56 : Created BindingExpression (hash=63575268) for Binding (hash=22674843)
System.Windows.Data Warning: 58 :   Path: 'DetailsList'
System.Windows.Data Warning: 60 : BindingExpression (hash=63575268): Default mode resolved to OneWay
System.Windows.Data Warning: 61 : BindingExpression (hash=63575268): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 62 : BindingExpression (hash=63575268): Attach to System.Windows.Controls.ListBox.ItemsSource (hash=66716242)
System.Windows.Data Warning: 67 : BindingExpression (hash=63575268): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=63575268): Found data context element: ListBox (hash=66716242) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=63575268): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=63575268): Resolve source deferred
System.Windows.Data Warning: 56 : Created BindingExpression (hash=55244468) for Binding (hash=22674843)
System.Windows.Data Warning: 58 :   Path: 'DetailsList'
System.Windows.Data Warning: 60 : BindingExpression (hash=55244468): Default mode resolved to OneWay
System.Windows.Data Warning: 61 : BindingExpression (hash=55244468): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 62 : BindingExpression (hash=55244468): Attach to System.Windows.Controls.ListBox.ItemsSource (hash=28507895)
System.Windows.Data Warning: 67 : BindingExpression (hash=55244468): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=55244468): Found data context element: ListBox (hash=28507895) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=55244468): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=55244468): Resolve source deferred
System.Windows.Data Warning: 56 : Created BindingExpression (hash=53268321) for Binding (hash=22674843)
System.Windows.Data Warning: 58 :   Path: 'DetailsList'
System.Windows.Data Warning: 60 : BindingExpression (hash=53268321): Default mode resolved to OneWay
System.Windows.Data Warning: 61 : BindingExpression (hash=53268321): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 62 : BindingExpression (hash=53268321): Attach to System.Windows.Controls.ListBox.ItemsSource (hash=20831783)
System.Windows.Data Warning: 67 : BindingExpression (hash=53268321): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=53268321): Found data context element: ListBox (hash=20831783) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=53268321): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=53268321): Resolve source deferred
System.Windows.Data Warning: 67 : BindingExpression (hash=63575268): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=63575268): Found data context element: ListBox (hash=66716242) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=63575268): Activate with root item NodeAsThumb (hash=19140135)
System.Windows.Data Warning: 107 : BindingExpression (hash=63575268):   At level 0 using cached accessor for NodeAsThumb.DetailsList: RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 104 : BindingExpression (hash=63575268): Replace item at level 0 with NodeAsThumb (hash=19140135), using accessor RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 101 : BindingExpression (hash=63575268): GetValue at level 0 from NodeAsThumb (hash=19140135) using RuntimePropertyInfo(DetailsList): <null>
System.Windows.Data Warning: 80 : BindingExpression (hash=63575268): TransferValue - got raw value <null>
System.Windows.Data Warning: 89 : BindingExpression (hash=63575268): TransferValue - using final value <null>
System.Windows.Data Warning: 67 : BindingExpression (hash=55244468): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=55244468): Found data context element: ListBox (hash=28507895) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=55244468): Activate with root item NodeAsThumb (hash=31430389)
System.Windows.Data Warning: 107 : BindingExpression (hash=55244468):   At level 0 using cached accessor for NodeAsThumb.DetailsList: RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 104 : BindingExpression (hash=55244468): Replace item at level 0 with NodeAsThumb (hash=31430389), using accessor RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 101 : BindingExpression (hash=55244468): GetValue at level 0 from NodeAsThumb (hash=31430389) using RuntimePropertyInfo(DetailsList): <null>
System.Windows.Data Warning: 80 : BindingExpression (hash=55244468): TransferValue - got raw value <null>
System.Windows.Data Warning: 89 : BindingExpression (hash=55244468): TransferValue - using final value <null>
System.Windows.Data Warning: 67 : BindingExpression (hash=53268321): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=53268321): Found data context element: ListBox (hash=20831783) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=53268321): Activate with root item NodeAsThumb (hash=35867003)
System.Windows.Data Warning: 107 : BindingExpression (hash=53268321):   At level 0 using cached accessor for NodeAsThumb.DetailsList: RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 104 : BindingExpression (hash=53268321): Replace item at level 0 with NodeAsThumb (hash=35867003), using accessor RuntimePropertyInfo(DetailsList)
System.Windows.Data Warning: 101 : BindingExpression (hash=53268321): GetValue at level 0 from NodeAsThumb (hash=35867003) using RuntimePropertyInfo(DetailsList): <null>
System.Windows.Data Warning: 80 : BindingExpression (hash=53268321): TransferValue - got raw value <null>
System.Windows.Data Warning: 89 : BindingExpression (hash=53268321): TransferValue - using final value <null>
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=WWPN; DataItem=null; target element is 'DataGridTextColumn' (HashCode=30423852); target property is 'Visibility' (type 'Visibility')
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=SwitchName; DataItem=null; target element is 'DataGridTextColumn' (HashCode=33040847); target property is 'Visibility' (type 'Visibility')
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=WWPN; DataItem=null; target element is 'DataGridTextColumn' (HashCode=19299281); target property is 'Visibility' (type 'Visibility')
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=SwitchName; DataItem=null; target element is 'DataGridTextColumn' (HashCode=47325326); target property is 'Visibility' (type 'Visibility')

A: I would not bind an ObservableCollection and reinitialize it. Even with INotifyPropertyChanged and OnPropertyChanged.
Please just Clear() your ObservableCollection and use a Property like Count to apply Visibility.
public class MyClass : BaseViewModel
{
    public System.Collections.ObjectModel.ObservableCollection<string> MyCollection
    {
        get;
    }

    public MyClass()
    {
        MyCollection = new System.Collections.ObjectModel.ObservableCollection<string>();
        MyCollection.CollectionChanged += MyCollection_CollectionChanged;
    }

    public bool IsEmpty
    {
        get
        {
            return MyCollection.Count == 0;
        }
    }

    public void RefillMyCollection(IEnumerable<string> values)
    {
        MyCollection.Clear();
        foreach(string value in values)
        {
            MyCollection.Add(value);
        }
    }

    private void MyCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        OnPropertyChanged("IsEmpty");
    }

}

You will need another IValueConverter, but u have so many possibilitys. Like IsEmpty, Count, HasItems. I think you get the idea.


text:
Q: How to select only one div at a time in angular 10 I have to create a sort filter in my application where I can select only one option at a time to sort my results. My UI is such that I can not use checkboxes. It is simple list. So I am creating the list through div. Can anyone suggest how to implement selection and deselection of div in angular. I can select only one div at a time. Also If I have selected any option and now i click on option 2 then option 1 div should get de-selected and option 2 div should get selected.

A: One solution would be to set the 'current' value when the div is clicked.
Add a class when the 'current' value matches the item's value.
<div *ngFor="let item of items"
(click)="onItemSelection(item)
[class.current-selection]="item === currentValue">
   {{ item }}
</div>

Handle the event in your component.ts file by storing the new value:
currentValue: string;

onItemSelection(newValue: string) {
   this.currentValue = newValue;
}

Then update the look of the current item in your component.scss file:
.current-selection {
  background-color: green;
}


text:
Q: How to keep the focus on one form while opening other? I have form that takes few seconds to load and open,
i need the other form (Form Represents "Please Wait ...") to be focused and stable while opening the main form.
I close the please wait form after 2 secs BUT it doesn't take the general focus.
This is the code i use to open the two forms :
        LoadingPage load = new LoadingPage();
        load.Show();

        load.TopMost = true;

        //
        string contractorType = "importer";

        //
        customersPage obj = new customersPage(this, contractorType);
        obj.MdiParent = homeObj;
        obj.Show();

Please, any idea ?
thanks,

A: That may be behaving funny because customerPage is an MDI child.  Have you considered making LoadingPage modal?  You would of course have to load your customerPage from events within LoadingPage (e.g. Form_Load or a 100ms timer callback, etc.,) because the call to ShowModal will block until LoadingPage closes.
The idea is that if LoadingPage is modal, then no other window in the same thread can take focus from it.


text:
Q: "Cannot read property of 'setMap' of undefined" when trying to remove markers in GoogleMaps component (Vue) I'm trying to remove markers from my map every time I fetch new results from the API. I want to do this so that the markers from the previous fetch won't be on the map. I read the Google Maps API documentation, it states to iterate through the markers and use the "setMap(null)" function on each marker to remove that marker from the map. I keep getting the "Cannot read property of 'setMap' of undefined" in the Chrome dev console.
The following code is how I'm trying to remove the markers, and is very similar to what the Google Maps API documentation is doing, except I'm not using multiple functions. Instead, I just check if the array holding the markers is not null, then I try to remove the markers and set the array holding the markers to null.
watch: {
    async events() {
        try {
            const google = await gMaps();

            if(this.locations !== null) {
                for(let i = 0; i < this.locations.length; i++) {
                    this.locations[i].setMap(null);
                }

                this.locations = [];
            }

            this.locations = this.events.map(event => {
                new google.maps.Marker({
                    position: {
                        lat: parseInt(event.latitude, 10),
                        lng: parseInt(event.longitude, 10)
                    },
                    map: this.map,
                    title: event.title
                })
            })
        }
        catch(error) {
            console.error(error)
        }
    }
}

The following is all of the code inside of the script tag in my Google Maps component.
import gMaps from '../lib/gMaps.js'

export default {
    name: 'GoogleMaps',
    props: {
        events: Array
    },
    data() {
        return {
            map: null,
            locations: []
        }
    },
    async mounted() {
        try {
            const google = await gMaps();
            const geocoder = new google.maps.Geocoder();
            this.map = new google.maps.Map(this.$el);

            geocoder.geocode({ address: 'USA'}, (results, status) => {
                if (status !== 'OK' || !results[0]) {
                    throw new Error(status);
                }

                this.map.setCenter(results[0].geometry.location);
                this.map.fitBounds(results[0].geometry.viewport);
            });
        } catch (error) {
            console.error(error);
        }
    },
    watch: {
        async events() {
            try {
                const google = await gMaps();

                if(this.locations !== null) {
                    for(let i = 0; i < this.locations.length; i++) {
                        this.locations[i].setMap(null);
                    }

                    this.locations = [];
                }

                this.locations = this.events.map(event => {
                    new google.maps.Marker({
                        position: {
                            lat: parseInt(event.latitude, 10),
                            lng: parseInt(event.longitude, 10)
                        },
                        map: this.map,
                        title: event.title
                    })
                })
            }
            catch(error) {
                console.error(error)
            }
        }
    }

A: Your locations array is not empty, but filled with undefined elements (e.g. [undefined, undefined, undefined]).
Since locations is populated in this.locations = this.events.map(...), the problem must be there.
And it is. As .map() argument, you are using an arrow function with {}s and not returning anything.
Your code is equivalent to:
this.locations = this.events.map(event => {
    new google.maps.Marker(...)
    return undefined;
})

Fix: You have two options: use the shorter version (without braces) or add a return statement.
Removing the braces:
            this.locations = this.events.map(event => // { removed
                new google.maps.Marker({
                    position: {
                        lat: parseInt(event.latitude, 10),
                        lng: parseInt(event.longitude, 10)
                    },
                    map: this.map,
                    title: event.title
                })
            ) // was: })

Or adding a return:
            this.locations = this.events.map(event => {
                return new google.maps.Marker({      // added return here
                    position: {
                        lat: parseInt(event.latitude, 10),
                        lng: parseInt(event.longitude, 10)
                    },
                    map: this.map,
                    title: event.title
                })
            })


text:
Q: Code Coverage and Silverlight 4 Is there any way to get Code Coverage metrics for Silverlight 4?  I have been trying to get this up and running for some time.
For a while there was code coverage in the Silverlight Unit Test Framework, but to my understanding it is now broken.
Any ideas on how I can pull off some code coverage metrics in my application?

A: We use ncover for measuring code coverage for our Silverlight 3 code. We use nunit testing framework. We have found ncover to be very useful along with ncover explorer which precisely points out the section of code which isn't covered by unit tests. They have a free 21-day trial edition.


text:
Q: How can I fix a MemoryError when executing scikit-learns silhouette score? I run a clustering algorithm and want to evaluate the result by using silhouette score in scikit-learn. But in the scikit-learn, it needs to calculate the distance matrix: distances = pairwise_distances(X, metric=metric, **kwds)
Due to the fact that my data is order of 300K, and my memory is 2GB, and the result is out of memory. And I can not evaluate the clustering result.
Does anyone know how to overcome this problem?

A: Set the sample_size parameter in the call to silhouette_score to some value smaller than 300K. Using this parameter will sample datapoints from X and calculate the silhouette_score on those instead of the entire array.


text:
Q: Folders created in visual studio solution under solution explorer not appearing in source control explorer I converted my MVC solution to layered architecture .
For this I added folders in my solution in Solution Explorer. Everything is working good, my colleagues are able to take the latest of solution and the folders are appearing in solution explorer.

The issue is I am not able to see the folder structure in TFS(in
  Source Control Explorer.)

Probably I should have create the folder structure in TFS directly.But now I have lot of changes checked in since I created the folder, so I think this option will not work.
Please Advice.

A: It's  supposed to be it. The root cause is Visual Studio solutions Folder are not real Folders.

Solution Folders only seem to be "virtual folders", because they are
  not really created in the Filesystem and files inside solution folders
  are just sitting in the same folder as the .sln file.

You can create real folders in a "project" within the solution, but not in the solution itself. Details about this area, you could refer below questions:

*

*Visual Studio Solutions Folder as real Folders

*What is a solution folder in visual studio
Source Control Explorer is used to manage files in TFVC, the files in the solution folder will shown up in the source control explorer and be the same level with .sln file, however the  solution folders itself will not appearing in source control explorer and keep the folder structure.

A: At least for C# solutions in Visual Studio 2019 you can manage individual forders in the solution.
To do this the view has to be switched to Folder View using the Switch View button in Solution Explorer.

Look here for detailed description


text:
Q: Attempted import error: 'ReactReduxContext' is not exported from 'react-redux' I am trying to setting up a new react-admin console (following the offcial tutorial : https://marmelab.com/react-admin/Tutorial.html). The current version of react-admin is 3.3.1.
But when execute command yarn start the following error occured  :
./node_modules/ra-core/esm/core/CoreAdminContext.js
Attempted import error: 'ReactReduxContext' is not exported from 'react-redux'.

What can I do ?

A: Delete your yarn lock / package lock and yarn install.
As per this thread

The problem comes from duplicate Redux packages, coming from duplicate
  react-admin dependencies, coming from an outdated data provider
  (designed for 2.9 while react-admin is in 3.x). Either upgrade your
  data provider, or downgrade react-admin to 2.9.

A: Update your react-redux to the latest version. In my case, i updated to 7.2.4
npm install react-redux@latest

or
npm install react-redux@7.2.4


text:
Q: file does not update with affect of `sed` deletion I am having trouble with getting a file updated with the effect of a sed deletion.
when i perform the following, replacing <> with appropriate filename
sed '$d' <filename>

the immediate shell output shows the last line was deleted, but upon doing
cat <filename>

it shows that this deletion hasn't been stored, why is this?

A: You need the -i flag to change the file in place.  Without it, sed writes to standard output.


text:
Q: Get the  value for each webpage with Selenium in Python I have a list of websites that I want to loop through and extract the Genres of the films. They all come from boxofficemojo.
An example link is the following: https://www.boxofficemojo.com/release/rl3829564929/
In the inspect, the structure of the page for the section that I want to extract is like this:

   Genres

  Action Adventure Thriller

When I run the following code:
driver = webdriver.Chrome("C:\SeleniumDrivers\chromedriver.exe")
driver.get("https://www.boxofficemojo.com/release/rl3829564929/")
driver.implicitly_wait(3)
my_element = driver.find_element_by_xpath("/html/body/div[1]/main/div/div[3]/div[4]/div[7]/span[2]")
my_element.text

I get the following results:
'Action Adventure Thriller'

which is the desirable result for this particular movie. However,when I go to other movies, the xpath is different and I cannot access it automatically.
The ideal solution would be to loop through the websites and extract the genres of the films irrespective of the xpath that the  Genres has in each individual film page.

A: my_element = driver.find_element_by_xpath("//div[@class='a-section a-spacing-none' and contains(.,'Genres')]/span[2]")
my_element.text

Search for a more unique xpath that fits your perimeters.

A: For each relevant website you visit, if the label Genre is followed by the genre name within a  tag, to extract the text you can use either of the following Locator Strategies:

*

*Using xpath:
driver.get("https://www.boxofficemojo.com/release/rl3829564929/")
print(driver.find_element_by_xpath("//span[text()='Genres']//following::span[1]").text)

Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

*

*Using XPATH:
driver.get("https://www.boxofficemojo.com/release/rl3829564929/")
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[text()='Genres']//following::span[1]"))).get_attribute("innerHTML"))

*Console Output:
Action Adventure Thriller

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: Foreign key is not valid in MVC I have Code First Approach here. I have listed the models below
public class BookInfo
{
    [Key]
    public int BookInfoid { get; set; }
    public string ISBN { get; set; }
    public string Title { get; set; }
    [ForeignKey("Publisher")]
    public int Publisherid { get; set; }
    public string Edition { get; set; }
    public string Printing { get; set; }
    public int Pages { get; set; }
    public string Language { get; set; }
    public string Summary { get; set; }
    public string CoberPage { get; set; }
    public DateTime DatePublished { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
    public int Thikness { get; set; }
    public float Weight { get; set; }
    public string AmazonLink { get; set; }

    //public Transaction Transaction { get; set; }
   // public BookByAuthor BookByAuthor { get; set; }
   // public ICollection<BookByCategory> BookByCategory { get; set; }
    public Publisher Publisher { get; set; }
   public LibraryBook LibraryBook { get; set; }
}

  public class BookStatus
{
    [Key]
    public int BookStatusid { get; set; }
    public string Name { get; set; }

   public LibraryBook LibraryBook { get; set; }
}

  public class LibraryBook
   {
    [Key]
    public int LibraryBookid { get; set; }
    [ForeignKey("BookInfo")]
    public int BookInfoid { get; set; }
    [ForeignKey("BookStatus")]
    public int BookStatusid { get; set; }
    public float Price { get; set; }
    public DateTime ObtainedFrom { get; set; }

    //public ICollection<Transaction> Transactions { get; set; }
    public IEnumerable<BookStatus> BooksStatus { get; set; }
    public IEnumerable<BookInfo> BooksInfo { get; set; }
}

My DbContext is
   public class DBContext:DbContext
   {
    public DbSet<City> Cities { get; set; }
    public DbSet<Contact> Contacts { get; set; }
    public DbSet<Publisher> Publishers { get; set; }
    public DbSet<BookInfo> BooksInfo { get; set; }
    public DbSet<Member> Members { get; set; }
    public DbSet<BookStatus> BooksStatus { get; set; }
    public DbSet<Author> Authors { get; set; }
    public DbSet<LibraryBook> LibraryBooks { get; set; }
   // public DbSet<Transaction> Transactions { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

}
When I try to add a Controller  I am Getting an error as given below. I am using MVC5(Code First Approach)
**Unable to retrieve metadata for Library_management_Syatem.LibraryBook.The Foreignkey Attribute on property 'BookInfoid'on type 'Library_management_Syatem.LibraryBook' is not valid. The Navigation Property 'BookInfoid' was not found on the dependent type 'Library_management_Syatem.LibraryBook'. The name value should be a valid navigation propertye.
Please Help Me**

A: You've got the "ForeignKey" attribute on the wrong property.  This is how it should be for the publisher (I think it helps to put "virtual" on the complex types):
public class BookInfo
{
    [Key]
    public int BookInfoid { get; set; }
    public string ISBN { get; set; }
    public string Title { get; set; }
    public int Publisherid { get; set; }
    public string Edition { get; set; }
    public string Printing { get; set; }
    public int Pages { get; set; }
    public string Language { get; set; }
    public string Summary { get; set; }
    public string CoberPage { get; set; }
    public DateTime DatePublished { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
    public int Thikness { get; set; }
    public float Weight { get; set; }
    public string AmazonLink { get; set; }

    //public Transaction Transaction { get; set; }
   // public BookByAuthor BookByAuthor { get; set; }
   // public ICollection<BookByCategory> BookByCategory { get; set; }

   [ForeignKey("Publisherid")]
   public virtual Publisher Publisher { get; set; }
   public LibraryBook LibraryBook { get; set; }
}


text:
Q: Email Activity log of SendGrid shows Delivered but no email received in the mailbox I have been using SendGrid for sending email from java using the SMPT Host, Username and Password. I had created send grid SMTP using Azure. It has been working fine and emails were received in the mail inbox. However now when I am sending the emails, it shows as Delivered in the EmailActivity at URL https://app.sendgrid.com/email_activity?
However, no emails are received in the inbox of email. I am using one Gmail id as the sender and another Gmail id as the recipient but it was working fine earlier.
What can be the issue? Thanks.