text:
Q: How can I close this search dropdown after a click? When I try and add a onClick="{this.displayResults(false)}" to the  the dropdown li, it will not appear.
When I try and add the onClick="{this.displayResults(false)} to the Search Results div, it conflicts with the inputs onChange event.
Any suggestions on how I can close the dropdown when a user clicks a search result?
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import * as actions from '../actions';

class Search extends Component {

handleSearchTerm(term) {
    if (!term == "") {
        this.props.getSearchResults({term});
        this.displayResults(true);
    } else {
        this.displayResults(false);
    }
}

displayResults(display) {
    if (display === false) {
        $( ".search-results" ).css( "display", "none" );
    } else {
        $( ".search-results" ).css( "display", "block" );
    }
}

buildResultsList() {
    if (!this.props.searchResults) {
        return null;
    } else {
        const searchResultsList = this.props.searchResults.map(function (result) {
            return ([

,
                <Link to={`/project-spotlight/${result.uri}`} className="dropdown-item" id="search-result">
{result.urlName}
</Link>
            ]);
        });
        return searchResultsList;
    }
}

render() {
    console.log(this.props.searchResults);

    return (

            <form className="form-inline nav-search">
                <input
                    className="form-control mr-sm-2"
                    onChange={(e) => this.handleSearchTerm(e.target.value)}
                    id="navBarSearchForm"
                    aria-expanded="false"
                    aria-haspopup="true"
                    type="text"
                    placeholder="What Pod you looking for?"
                    autoComplete="off">
                </input>
            </form>

-Pods-

                {this.buildResultsList()}

    );
}

}

function mapStateToProps(state) {
return { searchResults: state.search.searchResult};
}

export default connect(mapStateToProps, actions)(Search);

A: Add event.preventDefault(); to your handler method

If this method is called, the default action of the event will not be
  triggered.

import React, { Component } from 'react';

export default class MyComponent extends Component {
  handleClick(event) {
    event.preventDefault();
    //...
  }

  render() {
    return (<button onClick={this.handleClick.bind(this)}>Submit</button>)
  }
}


text:
Q: With wicket where does hibernate.cfg.xml file go? I'm new to Wicket and Hibernate and can't get past the "org.hibernate.HibernateException: /hibernate.cfg.xml not found" error. I've put that file in every location imagineable but I'm still stuck. Where exactly does that file go and/or am I missing a wicket file config setting somewhere?

A: Ensure hibernate.cfg.xml file placed in classpath.

A: If you're just starting with Wicket and Hibernate, you may be interested in the Databinder toolkit.

A: I'd place the hibernate,cfg.xml in the /WEB-INF folder of your application.

A: the common form to connect that technologies is with springframework, take  a look http://wicketinaction.com/2009/06/wicketspringhibernate-configuration/
and also springframework help you with  lazy load exception, and transaction management

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I pass Thread safe Arguments/Objects to my Fitnesse Fixture? Similar to how do i pass program arguments in java for my Fitnesse Fixture?
.. I wish to kick off my Fitnesse tests in parallel using fitnesseMain.FitNesseMain.launchFitNesse(Arguments arguments)... and pass thread-safe objects to each test to be accessed later by test code run by Fitnesse.
The test code itself is plain old Java, invoked from Fitnesse using givwenzen. The Java test code goes on to dynamically kick off Selenium tests.
I need to pass these thread-safe objects through Fitnesse all the way to the Java test scripts so that they start a Selenium RemoteWebDriver with the correct org.openqa.selenium.remote.DesiredCapabilities.
I have tried using the good old java.lang.ThreadLocal, but it appears that Fitnesse is  spawning threads of its own to run the tests which effectively eliminates this option.

A: Considering Givwenzen is written using Slim, I don't think what you want to do is possible. If possible, it certainly isn't easy, as Slim works by running the tests in a separate process.
So when you run FitNesse, it creates the web server and the wiki.  That runs as one java task.  When you click on the Test or Suite buttons (or use the URLs) it creates a new Java process that is the SlimServer.  Then the FitNesse server sends instructions to the SlimServer as strings and then the SlimServer processes those into instructions to run tests. So the coupling between the code that is launched via FitNesseMain to the slim tests is actually sort of loose.  This is done on purpose, as it lets the SlimServer implementation be language independent.
Within the SlimServer, there is the ability to work with actual object references, and that might be OK, but I have doubts that the chain of custody will be threadsafe at each step.
Sorry.  Maybe someone else will have an idea for how to work around the issues I've described.


text:
Q: How to run parted mklabel in a script without user prompt? I am trying to write a bashscript that will re-partition a drive using the parted utility. Since it is running in a script, I would like parted to not prompt the user for input (or alternatively, have a method to answer those prompts).
Initially, I tried passing the '-s' or '--script' option to parted but it does not do work the way I expected. When I try running parted $DRIVE -s mklabel gpt in the script, I expect that parted will answer the three prompts with 'i', 'y', and 'i' (ignore, yes, ignore) to the warnings it gives. However, my script stops execution with the following message: Error: Partition(s) on /dev/nvme1 are being used.
Running that command manually shows that message and allows me to pass the response 'i' to ignore the warning and continue. From some googling, I gathered that parted will go with the default response when running with the -s option. I assume that when this warning appears, the default option is to cancel so as to not accidentally ruin a drive.
When running the script without passing -s to parted, I get prompted at the terminal for input, and when given, the rest of the script runs fine. I then tried piping in the responses using echo like so echo "i\ny\ni" | repart.sh but that does not appear to work either.
Is there a way to override this default to get the desired behavior? If not, is there some other way to achieve this?
For context: the target machine running this script is running Ubuntu 18.04.3 LTS
Note: While I can install additional utilities that are not standard on Ubuntu, I would prefer not to.
EDIT: I have found a solution thanks to @chexum! I modified my script to called the wipefs utility before running parted: wipefs -a -f $DRIVE and then modified my parted command to pipe 'i' into it to answer the one remaining prompt: yes "i" | parted $DRIVE mklabel gpt. It now works completely automated. As a note to any future readers, using the wipefs utility carries its own risks if you are not careful, this solution worked well for my purposes but may not be well suited for others.


text:
Q: Unable to Initialize WebDriver Chrome and all the tests are failing I recently upgraded Chrome Browser Version to 78, Selenium Web Driver version to 3.141.0 and Selenium Chrome Driver Version to 78.0.3904.7000.
When i ran my tests on Remote Machine through Azure pipeline, all my tests are failing because of bellow failure. Please suggest how to handle this

OneTimeSetUp:
  Automation.Test.Framework.Models.Exceptions.AtGenericException : Error
  initializing WebDriver Chrome
  ----> System.InvalidOperationException : Driver does not support manipulating HTML5 web storage. Use the HasWebStorage property to test
  for the driver capability

A: Since Chrome 75, the default setting of the w3c spec compliance has switched to true.
However the C# binding only passes the option if it is set to true (assuming the deafult to be false).
This means we cannot set it to false at all with the current stable C# binding.
https://github.com/SeleniumHQ/selenium/issues/7521


text:
Q: Multiple Git repositories in a Theia workspace I have a workspace in which I have added several folders, each of them having its own Git repository, my workspace file looks like:
{
   "folders": [
      {
         "path": "myproject1"
      },
      {
         "path": "myproject2"
      },
      ...
      {
         "path": "myprojectN"
      },
   ],
   ...
}

Unfortunately, in the Git view Theia only manages Git changes in the first folder. None of the changes done in the other folders is displayed.
Is it normal ? How can I make the Git view managing several Git repositories (one per folder) like the desktop version of VSCode does ?
Thank you in advance for any help

A: I got the answer on the Theia forum: https://github.com/eclipse-theia/theia/issues/8291#issuecomment-668074089
The "SCM: Change repository" command allow to change the "active" Git repo in the Git view.


text:
Q: Can I make some text visible on a users profile if they are viewing their own profile but hide it if somebody else is viewing it? I am using the BuddyPress plugin with WP-Job-Manager plugin for my website. I am also using another plugin called BP-job-manager to display users resumes on their Buddypress profiles. Unfortunately the BP-Job-manager Plugin is a little buggy and is not supported.
Currently if a user is logged in and they visit their own profile they can click the resumes tab and there is some text which states "Your resume can be viewed, edited or removed below." and underneath they have options to view, edit or remove their own resumes when they hover over it.
If a user is logged in and selects to view another users profile they can also view the other users resumes but they do not have the options to edit or remove somebody else's resume but the text  "Your resume can be viewed, edited or removed below." is still visible.
This is how it looks when I inspect it:
https://prnt.sc/qskqbd
I have temporarily used this CSS to hide it from everyone:
#resume-manager-candidate-dashboard > p {
    display: none;
}

But I still wanted it visible if a user is viewing their own profile as the features to edit and remove their resumes are still there.
I came across the "is_user_logged_in()" function online and I found an example:
/**
 * Give a personalized message for logged in users and a generic one for anonymous visitors
 */
function wpdocs_personal_message_when_logged_in() {
    if ( is_user_logged_in() ) {
        $current_user = wp_get_current_user();
        printf( 'Personal Message For %s!', esc_html( $current_user->user_firstname ) );
    } else {
        echo( 'Non-Personalized Message!' );
    }
}
add_action( 'loop_start', 'wpdocs_personal_message_when_logged_in' );

I was wondering if this code could be modified, for example after $current_user = wp_get_current_user(); is there anything that can be added to check whether current user is the same as the user whose profile is being viewed?
...and then echo the text "Your resume can be viewed, edited or removed below." if user is the same?
...and then else the text "Your resume can be viewed, edited or removed below." is hidden.
I was just wondering whether there was a way of doing all this in php?
Thank you

A: Since you are using BuddyPress the bp_is_my_profile function can be helpful.
Change your code to the following and it'll work as you want.
if (is_user_logged_in() && bp_is_my_profile()) {
   $current_user = wp_get_current_user();
   printf( 'Personal Message For %s!', esc_html( $current_user->user_firstname ) );
}

A: Example:
<?php
$checkuser = $_SESSION[userid];
if($current_user = $checkuser){
echo 'THIS IS INFORMATIONS';
}else{
echo 'Nothing to see';
}?>

Please provide more information about your issue. so we look into it together.


text:
Q: How to make an annotaion that calls other annotations I usually use specific lombok and spring annotations in every class that I open in work.
Is there a way that I can create my custom annotation that will call the annotations that I need?
This is my class for exmple:
@Getter
@Setter
@Embeddable
@AllArgsConstructor
@Builder
public class SomeName{}

And I want it to be:
@SomeAnnotationName
public class SomeName{}

A: lombok doesn't support this, but it have feature request for it.


text:
Q: How to justify the approximation ratio of this deterministic algorithm.(Weighted MAX-k-Cut) The weighted MAX-k-CUT problem asks for the maximum-weighted cut in a weighted undirected graph.
Suppose now each vertex is one-by-one greedily assigned to the group that can maximize the total weight of new cuts.
How to know the approximation rate of the deterministic algorithm?

A: It's 1/2. This particular algorithm can be obtained by applying the method of conditional expectations to the randomized approximation that choose the assignment of each node independently and uniformly at random, which obtains 1/2 of the total edge weight in expectation and hence at least 1/2 of OPT.
An example where the ratio is 1/2 + ε can be obtained by taking K2,n with unit edge weights, adding an infinitestimally costed edge between the two vertices on one side and forcing the algorithm to consider them first.


text:
Q: Sending images from gallery to Web Service using SOAP I have trawled the net and can't find any documentation on sending images (or any attachments) to a Web Service using SOAP.
I have been sending text data fine but I now need to send images from the gallery along with the text data, which poses another problem - making two or more async tasks at once. I will need to make 4 calls in total IF the record to send has an image affiliated with it;

*

*Send the text data.

*Check if the file already exists on the server.

*Send the file.

*Link the file with a record on the server using a u_id sent back from the server.

I was advised to use a Base64 method to convert the file to a String then send it but I have a feeling theres a cleaner way of doing it using SOAP (no pun intended).
Any feedback greatly appreciated.
* Please note that I was using a httpClient but had to change to using SOAP also I'm relatively new to Android so forgive me if I've said anything stupid here.

A: There are three ways of sending attachments with SOAP.

*

*base64Binary

*SwA - SOAP with Attachments

*MTOM
base64Binary sends the attachments as base64 inline in the SOAP message. i.e. The Attachment in embedded in the SOAP Message. Bloats the message by 33%.
SWA sends the Attachment outside the SOAP message (The SOAP message contains a reference to the attachment). But the SOAP infoset does not contain the attachment.
MTOM Provides the best of both world. The Attachment is sent outside the SOAP message with a reference to it but the attachment appears as if it is embedded in the SOAP message (The SOAP infoset contains the attachment)
Due to the fact that attachments sent using MTOM appear as it the attachment is part of the SOAP message it allows you to use other WS-* QOS (Quality of Service) attributes. For e.g MTOM messages can be signed and encrypted using WS-Security. Thus this provides a mechanism to send Secured Attachments without the need for additional specs.
This example shows how to use MTOM with Apache AXIS2.


text:
Q: how to dynamically declare a 2-d array in c using type: int(*)[ ]? I have tried using int**(pointer to a pointer) and int*[](array of pointers) but i am unable to perform the task with pointer to an array.How can we use pointer to an array and malloc function to create an 2-d array in c.
Please provide a sample code:)

A: void *allocateMemory2DArray(size_t x, size_t y)
{
    int (*array)[x][y];

    array = malloc(sizeof(*array));
    return array;
}

5d array
void *allocateMemory5DArray(size_t x, size_t y, size_t v, size_t q, size_t r)
{
    int (*array)[x][y][z][q][r];

    array = malloc(sizeof(*array));
    return array;
}

A: So let's start from the ground up.
The typical way to dynamically allocate an N-element array of T (for some arbitrary T) is
T *p = malloc( sizeof *p * N ); // sizeof *p == sizeof (T)

This allocates enough space for N objects of type T, with p pointing to the first element
   T *        T
   +–––+      +–––+
p: |   |–––––>|   | p[0]
   +–––+      +–––+
              |   | p[1]
              +–––+
               ...
              +–––+
              |   | p[N-1]
              +–––+

Now, replace T with an array type - R [M]:
R (*p)[M] = malloc( sizeof *p * N );

This allocates enough space for N objects of type R [M] - IOW you've allocated an NxM array of R.  p still points to the first element, it's just that in this case the first element is an array in itself.
   R (*)[M]    R [M]
   +–––+       +–––+
p: |   |––––––>|   | p[0][0]
   +–––+       + - +
               |   | p[0][1]
               + - +
                ...
               + – +
               |   | p[0][M-1]
               +––—+
               |   | p[1][0]
               + – +
               |   | p[1][1]
               + - +
                ...
               + – +
               |   | p[1][M-1]
               +–––+
                ...
               + – +
               |   | p[N-1][M-1]
               +–––+

You'd index into p like any regular 2d array.
You can extend this to higher-dimensioned arrays - replace R with another array type like Q [L]:
Q (*p)[M][L] = malloc( sizeof *p * N );

This allocates space for an NxMxL array, and again you'd index into it like any 3d array p[i][j][k].
The semantics are exactly the same in every case - you're allocating space for N objects, it's just that the types of the objects are different.


text:
Q: Ignoring/removing specific values from an XML using XSLT I'm trying to remove unwanted information from our XML:
<STEP-ProductInformation ExportTime="2017-12-06 16:32:55"
ExportContext="de_DE" ContextID="defaultcontext" WorkspaceID="Main"
UseContextLocale="false">
<Qualifiers>
<Qualifier ID="Qualifier root">
  <DimensionPointLink DimensionPointID="Qualifier root"/>
</Qualifier>
<Qualifier ID="AllCountries">
  <DimensionPointLink DimensionPointID="AllCountries"/>
</Qualifier>
<Qualifier ID="std.lang.all">
  <DimensionPointLink DimensionPointID="std.lang.all"/>
</Qualifier>
<Qualifier ID="de">
  <DimensionPointLink DimensionPointID="de"/>
</Qualifier>
<Qualifier ID="DE">
  <DimensionPointLink DimensionPointID="DE"/>
</Qualifier>
<Qualifier ID="fr">
  <DimensionPointLink DimensionPointID="fr"/>
</Qualifier>
<Qualifier ID="FR">
  <DimensionPointLink DimensionPointID="FR"/>
</Qualifier>
</Qualifiers>
<Products>
<Product ID="PROD1" UserTypeID="OBJ_MASTER_PRODUCT" ParentID="PARENT1">
  <Name>52470025-1</Name>
  <Values>
    <Value AttributeID="ATTR_1" ContextID="de_DE"
    QualifierID="de">Je m'appelle Alex Testtest 3</Value>
    <Value AttributeID="ATTR_2" ContextID="fr_FR"
    QualifierID="de">Je m'appelle Alex Testtest 3</Value>
  </Values>
</Product>
</Products>
</STEP-ProductInformation>

The aim is to ignore/remove all the values relating to ContextID="de_DE", making the outcome:
<STEP-ProductInformation ExportTime="2017-12-06 16:32:55"
ExportContext="de_DE" ContextID="defaultcontext" WorkspaceID="Main"
UseContextLocale="false">
<Qualifiers>
<Qualifier ID="Qualifier root">
  <DimensionPointLink DimensionPointID="Qualifier root"/>
</Qualifier>
<Qualifier ID="AllCountries">
  <DimensionPointLink DimensionPointID="AllCountries"/>
</Qualifier>
<Qualifier ID="std.lang.all">
  <DimensionPointLink DimensionPointID="std.lang.all"/>
</Qualifier>
<Qualifier ID="de">
  <DimensionPointLink DimensionPointID="de"/>
</Qualifier>
<Qualifier ID="DE">
  <DimensionPointLink DimensionPointID="DE"/>
</Qualifier>
<Qualifier ID="fr">
  <DimensionPointLink DimensionPointID="fr"/>
</Qualifier>
<Qualifier ID="FR">
  <DimensionPointLink DimensionPointID="FR"/>
</Qualifier>
</Qualifiers>
<Products>
<Product ID="PROD1" UserTypeID="OBJ_MASTER_PRODUCT" ParentID="PARENT1">
  <Name>52470025-1</Name>
  <Values>
    <Value AttributeID="ATTR_2" ContextID="fr_FR"
    QualifierID="de">Je m'appelle Alex Testtest 3</Value>
  </Values>
 </Product>
</Products>
</STEP-ProductInformation>

So far I have created the following XSL code:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:template match="node()">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>
<xsl:template match="Value[@ContextID='de_DE']"></xsl:template>
</xsl:stylesheet>

However, this excludes the Qualifier IDs and DimensionPointIDs as well as the Product ID, the UsertypeID and PartentID!
How can I achieve my objective?
Many thanks!

A: You need to implement the identity transformation as the starting and base point of your stylesheet as
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

to make sure attributes are copied as well.
Or move to Saxon 9.8 or Altova 2017/18 and XSLT 3 and simply write <xsl:mode on-no-match="shallow-copy"/>.


text:
Q: Android SQLite возвращает пустое значение Помогите, пожалуйста, разобраться с SQLite.
DatabaseHelper.java
 public class DatabaseHelper extends SQLiteOpenHelper {

    private final String LOG = "###MY_DB_LOG###";

    public static final String TABLE = "PROJNAMES";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "projname";
    public static final String COLUMN_INFO = "info";

    private static final String DB_NAME = "PROJECTSBASE.db"; //имя базы
    private static final int DB_VERSION = 1; //версия базы

    private String CreateTable = "CREATE TABLE " + TABLE + " ("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_NAME + " TEXT, "
            + COLUMN_INFO + " TEXT" + ");";

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
         }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CreateTable);

        ContentValues c = new ContentValues();
        c.put(COLUMN_NAME, "Star Wars");
        c.put(COLUMN_INFO, "Luke Skywalker");
        db.insert(TABLE, null, c);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

Кусок кода из MainActivity
 DatabaseHelper DatabaseHelperMain = new DatabaseHelper(this);
            try {
                SQLiteDatabase db = DatabaseHelperMain.getReadableDatabase();

                /*
                Создаем курсор для получения таблицы PROJECTSNAME столбцов NAME и MAIN_INFO тех записей,
                у которых значение _id равно ....
                 */
                Cursor cursor = db.query(DatabaseHelperMain.TABLE, null, null,null,null,null,null);

                if(cursor.moveToFirst()){

                    nameText = cursor.getString(cursor.getColumnIndex(DatabaseHelperMain.COLUMN_NAME));

                }

                newnameP = nameText;
                mainStorage.addItem(newnameP);

                Log.i(LOG,  newnameP + " !!!");

                cursor.close();
                db.close();

            }   catch (SQLException e) {
                Toast toast = Toast.makeText(this,"Database unvaliable", Toast.LENGTH_SHORT);
                toast.show();
            }

При этом лог Log.i(LOG,  newnameP + " !!!"); показывает null !!!. Подскажите, с чем может быть ошибка? Курение доков не помогает.
Заранее спасибо за внимание.

A: В вашей БД нет ни одной записи. Поэтому вы получаете null как результат.
Метод onCreate(SQLiteDatabase db) срабатывает только при первом обращении приложения к классу. Было бы не логично, каждый раз при запуске приложения создавать пустые таблицы и вносить данные по умолчанию.
Если БД менялась, например добавились таблицы, нужно увеличивать значение DB_VERSION, например на 1. И в методе onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) выполнять операции по обновлению уже установленной БД приложения.
Дам рекомендации касательно работы с БД. (Любые константы и классы должны начинаться с Заглавной буквы, а переменные и методы со строчной, нарушение не является ошибкой, но эти правила упростят процесс понимания кода.)
DatabaseHelper dbHelperMain = new DatabaseHelper(this); // если обращение к БД происходит только в одном методе, тогда можно оставить, в противном случае - перенести код в onCreate активити.
SQLiteDatabase db = dbHelperMain.getReadableDatabase();
Cursor cursor = db.query(dbHelperMain.TABLE, null, null,null,null,null,null);
if(cursor.moveToFirst()){
//всю работу с переменными, которым присваивается значение из БД, нужно делать в этом условии.
nameText = cursor.getString(cursor.getColumnIndex(dbHelperMain.COLUMN_NAME));
newnameP = nameText;
mainStorage.addItem(newnameP);
}
else{
//В БД не оказалась записей, здесь можно либо вызвать метод, который добавит нужные данные, либо выведет сообщение, что записей в базе нет.
Toast toast = Toast.makeText(this,"По запросу не нашлось ни одной записи", Toast.LENGTH_SHORT).show();
}
Log.i(LOG,  newnameP + " !!!"); //для отладки лучше оставлять вне условий
cursor.close(); // да нужно освободить память после работы с курсором.
//db.close(); // не нужно закрывать соединение, это может привести к ошибкам.
//Особенно если другой метод всё еще работает с БД, или пытается открыть соединение.
//обычно соединение само закрывается (поправьте если ошибаюсь)


text:
Q: Передача id объекта View в метод контроллера ASP.NET MVC Есть БД с перечнем кандидатов, с помощью EF создал DbContext -
VoterContext VC = new VoterContext();
из которого вытягиваю данные в представление
public ActionResult Candidats()
    {
        IEnumerable<Candidat> candidats = VC.candidats;
        ViewBag.Candidat = candidats;
        return View();
    }

В представлении данные из БД транслируются с помощь цикла @foreach
@foreach (var b in ViewBag.Candidat)
    {

@b.CandidatInfo

@b.CandidatPartion

@b.CandidatProgramm

Проголосовать

    }

В цикле есть переход к методу
Проголосовать

Вопрос: Как создать метод в контроллере, который при нажатии на кнопку транслировал бы только те данные из выборки @foreach, которую выбрал пользователь? То есть - в синтаксис Razor вместо @b. поместить CandidatId указанного кандидата?
Прошу прощения за не точности в вопросе, из за этой "чудо-технологии" сплошная каша в голове.

A:
Есть метод в контроллере, который выводит перечень данных в компонент View с помощью @foreach цикла.

Нет, это не метод и не в контроллере, это кусок кода из вьюхи.
ActionResult Vote(string id)
{
    достать данные из бд по id
    return View(данные)
}

Вообще, как-то размыто написано, уточните ваш вопрос.

A: Я бы вам советовал по Модели организовать View (строго типизированно)
@foreach (var b in Model)
{

@b.CandidatInfo

@b.CandidatPartion

@b.CandidatProgramm

@Html.ActionLink("Проголосовать", "Vote", "Home", new { id = @b.CandidatId, info= @b.CandidatInfo, data = @b.CandidatPartion }, null

}

Вы должны именно по "id" отправлять потому что маршрутизация по умолчанию у вас такая
routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

А далее вы эти "id, info, data" получаете в Controller - Home, в методе Vote
public ActionResult Vote(int? id, string info, string data)
{
    // Something
    return View()
}

Если я конечно правильно всё понял


text:
Q: SSIS 2012 extracting bool from .csv failing to insert to db "returned status 2" Hi all quick question for you.
I have an SSIS2012 package that is reading a flat file (.csv) and is loading it into a SQL Server database table. However, I am getting an error for one of the columns when loading the OLEDB Destination:
[Flat File Source [32]] Error: Data conversion failed. The data conversion for column "Active_Flag" returned status value 2 and status text "The value could not be converted because of a potential loss of data.".
I am wondering if this is because in the flat file (which is comma delimited), the values are literally spelled out "TRUE" or "FALSE". The advanced page on the flat file properties has it set to "DT_BOOL" which I thought was right. It was on DT_STRING originally, and that wasn't working either.
In the SQL server table the column is set up as a bit, and allows nulls. Is this because it is literally typed out TRUE/FALSE? What's the easiest way to fix this?
Thanks for any advice!

A: It actually turned out there was a blank space in front of "True"/"False" in the file. Was just bad data and I missed it. Fixing that solved my issue. Thank you though, I did try that and when that didn't work that's when I knew it was something else.


text:
Q: Speed up random number generation in MATLAB Is there any way to generate pseudo-random numbers to less precision and thus speed the process up?
Another thing is that I know it saves time if random numbers are generated all at once (e.g. rand(100,1000)), instead of one by one. Could someone explain why this is true?

A: If you have a CUDA-capable GPU, you can do random number generation on it, as it's supposed to be much faster... Specifically Philox4x32-10:
parallel.gpu.rng(0, 'Philox4x32-10');
R = gpuArray.rand(sZ,'single'); % run this for more info: doc('gpuArray/rand')

A: MATLAB actually implements more than one random number generator. They differ significantly in terms of execution time and in terms of "randomness" (I think, but I didn't verify). However, I understand from your question that speed is more important for you.
% 'twister' is the default in MATLAB Versions 7.4 and later
tic();
for i=1:1000000
    rand('twister');
end
toc();
%Elapsed time is 2.912960 seconds.

% 'state' is the default in MATLAB versions 5 through 7.3
tic();
for i=1:1000000
    rand('state');
end
toc();
% Elapsed time is 2.162040 seconds.

% 'seed' is the default in MATLAB version 4
tic();
for i=1:1000000
    rand('seed');
end
toc();
% Elapsed time is 0.758830 seconds.

Important note: I ran the script above with an rather old version of MATLAB (v.7.6, a.k.a. R2008a). In newer versions, the syntax rand(generator) is discouraged . Instead, you should use the function rng(seed, generator) (online documentation). As a side effect, rng(seed, generator) gives you even more random number generators to choose from. Check the documentation for details.
Regarding the second question: Whatever generator you pick, generating many random numbers at once will always be faster than generating many single random numbers. This is because MATLAB's internals are heavily optimized for parallel processing.
tic();
for i=1:100000
    rand();
end
toc();
% Elapsed time is 0.024388 seconds.

tic();
rand(100, 1000);
toc();
% Elapsed time is 0.000680 seconds.

A: Since R2015a the rng function for configuring and seeding the global generator has a 'simdTwister' option that uses a faster "SIMD-oriented Fast Mersenne Twister" algorithm:
rng(1,'twister');
R = rand(1e4); % Warmup for timing
tic
R = rand(1e4);
toc

rng(1,'simdTwister');
R = rand(1e4); % Warmup for timing
tic
R = rand(1e4);
toc

This will probably be the fastest builtin generator for your system (excepting the possibility of GPU-based generators). On my computer it's a little more than twice as fast as the default Mersenne Twister algorithm for large arrays.


text:
Q: CMV / Disclaimer Widget Decline URL Once I remove the existing comment lines within the example that is included with the config script, the page including the disclaimer doesn't load.
declineHref: 'http://esri.com',

Can you explain why this may not be working?

A: Sounds like you maybe missing a comma or possible have an extra comma in the configuration of the disclaimer widget.  Look for those.  Use the structure of the configuration for the other widgets in your app as an example.
If you need further assistance, please post all the lines for configuration object for that widget so I can provide a more pinpointed answer.
EDITED ANSWER AFTER RECEIVING WIDGET CONFIG VIA E-MAIL.
Here is the widget config that was received:
disclaimer: {
    include: true,
    id: 'disclaimer',
    type: 'floating',
    path: 'gis/dijit/Disclaimer',
    title: 'Terms of Agreement',
    options: {

        // you can customize the button text
        i18n: {
            accept: 'Agree',
            decline: 'Decline'
        },

        // pre-define the height so the dialog is centered properly
        style: 'height:295px;width:375px;',

        // you can put your content right in the config
        content: '
Blah Blah Blah...

'

        // or you can provide the url for another page that includes the content
        //href: './disclaimer.html',

        // the url to go to if the user declines.
        declineHref:  'http://www.googlei.com/',

    }
},

As I suspected, you were missing a comma at the end of the line for the contents property.
I also removed the additional comma at the end of the line for the declineHref property. An extra comma in the last property of a JSON object would foul up older versions of internet explorer where other browsers are more forgiving. If this is the last widget in your configuration file, you should also remove the comma at the end of the last line of this widget config for the same reason.
Here is the corrected config:
disclaimer: {
    include: true,
    id: 'disclaimer',
    type: 'floating',
    path: 'gis/dijit/Disclaimer',
    title: 'Terms of Agreement',
    options: {

        // you can customize the button text
        i18n: {
            accept: 'Agree',
            decline: 'Decline'
        },

        // pre-define the height so the dialog is centered properly
        style: 'height:295px;width:375px;',

        // you can put your content right in the config
        content: '
Blah Blah Blah...

',

        // or you can provide the url for another page that includes the content
        //href: './disclaimer.html',

        // the url to go to if the user declines.
        declineHref:  'http://www.googlei.com/'

    }
},

One final note: You may want to replace the pirate flag image with your own text. That was in the disclaimer example just for fun ;)


text:
Q: conic sections, ellipse A particle is travelling clockwise on the elliptical orbit given by
$$\displaystyle \frac{x^2}{100} + \frac{y^2}{25} = 1$$
The particle
leaves the orbit at the point $(-8, 3)$ and travels in a straight line tangent to the ellipse.
At which point will the particle cross the $y$-axis?

A: HINT:
From Article $262$ of this, the equation of the tangent at $P(h,k)$ of $$\frac{x^2}{a^2}+\frac{y^2}{b^2}=1\text{   is      }\frac{x\cdot h}{a^2}+\frac{y\cdot k}{b^2}=1$$
So, the equation of the tangent here will be $$\frac{x\cdot (-8)}{100}+\frac{y\cdot 3}{25}=1$$
Now to cross the $y$ axis, $x=0$

A: We have $x^2/100+y^2/25=1$ so if we set $F(x,y)=x^2/100+y^2/25-1=0$ then $$y'=m_{\text{tangant} }=\frac{-F_x}{F_y}=\frac{-x}{4y}$$ and so $$m_{(-8,3)}=\frac{8}{12}$$ and the equation of the tangent line as @lab noted is $$y=\frac{8}{12}(x+8)+3$$

A: I like to work with homogeneous coordinates.
The ellipse is represented by
$$C = \begin{bmatrix} \frac{1}{100} & 0 & 0 \\
0 & \frac{1}{25} & 0 \\
0 & 0 & -1 \end{bmatrix}$$
the 3×3 matrix such that
$$ \left. \begin{pmatrix} x & y & 1 \end{pmatrix} \begin{bmatrix} \frac{1}{100} & 0 & 0 \\
0 & \frac{1}{25} & 0 \\
0 & 0 & -1 \end{bmatrix} \begin{pmatrix} x \\ y \\ 1 \end{pmatrix} =0 \right\} \frac{x^2}{100} + \frac{y^2}{25} -1 =0 $$
The tangent point is $P=(-8,3,1)$ (you verify tangency by $P\cdot C P=0$)
The tangent line is $L=C P = (-\frac{2}{25}, \frac{3}{25}, -1)$ with equation
$$ \left. (x,y,1) (-\frac{2}{25}, \frac{3}{25}, -1)=0 \right\} -2x+3y-25=0 $$
You can work out the rest.


text:
Q: R programming - treat NA in a file as 0 Really simple question, to which I haven't been able to Google/find an answer.
I have a simple file - "test.txt"
Gender arch1
M      99
F      97
M      NA

I load this into a resultset using read.table - works fine.
attach(resultset)

Now, I want _something_ that will give me
mean(arch1, [_SOMETHING_]) = 65.3 (and *_NOT_* 98)

i.e. not na.rm = T or similar. Basically, I want to treat NA as 0 - and I don't want to do something complicated like here with matrices and dataframes.
Just NA = 0 from the file. Surely, I can't be the first person to have wanted this? And I don't want discussions about how NA and 0 are not the same thing. I think it's perfectly valid to want to calculate an average even over missing students!

A: Something like this?
sum(arch1, na.rm = T)/length(arch1)

A: You can replace the NAs with zeros before using mean:
mean(replace(arch1, is.na(arch1), 0))
# [1] 65.33333

A: you could replace the NA by zero with resultset$arch1[is.na(resultset$arch1)]=0 and then compute the mean of the arch1 column

A: Below is my suggestion on how to implement the solution to which I have now given as the correct answer:
avg_without_NA = function(vec)
{
  my_ans = sum(vec, na.rm = T)/length(vec)
  return(my_ans)
}

So, now all I have to do is make a simple function call and my code is encapsulated in! Simpler all round, and easier to read!


text:
Q: Why everytime the final number comes the same? I have come across an interesting puzzle.
Write $20$ numbers. Erase any two number say $x$ and $y$ and and replace with
$\text{Number}_{new} = xy/(x + y)$
OR
$\text{Number}_{new}= x + y + xy$

Where some possible choices of  are:
You are to repeat 19 times, until you get a single number.
The final result will be independent of the choices of pairs made.
Why is the result the same every time ?
Example:
Suppose I take $4$ numbers $\{2 , 4 , 5 , 7\}$

*

*Now if I take $2$ and $4$ and get new number. New set will be  $\{\frac86, 5 , 7\}$
Now if I take 5 and 7. New set will be  $\{\frac86 , \frac{35}{12}\}$ And the final
value will be  $\{\frac{140}{153}\}$

*Now if I take $2$ and $5$ and get new number. New set will be  $\{\frac{10}7, 4 ,
    7\}$. Now if I take $4$ and $7$. New set will be  $\{\frac{10}7 , \frac{28}{11}\}$ And
the final value will be  $\{\frac{140}{153}\}$ again
How is this possible?
Thanks in advance.

A: Hint: Assuming you meant $xy\over{x+y}$, Final answer will always be of the form
$$1\over{\sum _{i=1}^{i=20}{1\over{x_i}}}$$

A: The keywords here are associativity and commutativity. The operation $x \circ y = \frac{xy}{x + y}$ clearly has the property $x \circ y = y \circ x$. Less obviously, it also has the property
$$(x \circ y) \circ z = x \circ (y \circ z).$$
You can verify this by computing both sides to be $\frac{xyz}{xy + yz + zx}$. Once you know this, it follows that $x \circ y$ defines a commutative semigroup (on, say, the positive reals, to ensure that the division is always well-defined), and in a commutative semigroup the expression
$$x_1 \circ x_2 \circ ... \circ x_n$$
is well-defined without the need to insert parentheses (by associativity) and moreover independent of the order of the $x_i$ (by commutativity).
One slick way to see that $\circ$ is indeed associative and commutative is to write it as
$$x \circ y = \frac{1}{ \frac{1}{x} + \frac{1}{y} } = f^{-1}(f(x) + f(y))$$
where $f$ (say, as a function from the positive reals to the positive reals) denotes inversion. Then the associativity and commutativity of $\circ$ follows from the associativity and commutativity of $+$, since
$$x \circ y = f^{-1}(f(x) + f(y)) = f^{-1}(f(y) + f(x)) = y \circ x$$
and
$$\begin{align*} (x \circ y) \circ z &=& f^{-1}(f(f^{-1}(f(x) + f(y))) + f(z)) \\\
 &=& f^{-1}(f(x) + f(y) + f(z)) \\\
 &=& f^{-1}(f(x) + f(f^{-1}(f(y) + f(z)))) \\\
 &=& x \circ (y \circ z). \end{align*}$$
It follows by induction that
$$x_1 \circ ... \circ x_n = f^{-1}(f(x_1) + ... + f(x_n)) = \frac{1}{ \frac{1}{x_1} + ... + \frac{1}{x_n} }.$$
You can think of this as saying that $\circ$ is just another name for the addition operation, but it's being encoded in a funny way by $f$ and you need to decode it by $f^{-1}$ for everything to make sense. More formally, $f$ defines an isomorphism from the positive reals under $\circ$ to the positive reals under addition.

By writing down other choices for $f$ you can write down more complicated examples of functions with the same property using transport of structure. For example, if $f(x) = \log x$, then $f^{-1}(x) = e^x$, and
$$f^{-1}(f(x) + f(y)) = e^{\log x + \log y} = e^{\log x} e^{\log y} = xy$$
so $f$ defines an isomorphism from, say, positive reals under multiplication to the reals under addition (both of which define groups).
As another example, if $f(x) = x^2$, then $f^{-1}(x) = \sqrt{x}$, and
$$f^{-1}(f(x) + f(y)) = \sqrt{x^2 + y^2}$$
so $f$ defines an isomorphism from, say, the non-negative reals under the operation $x \circ y = \sqrt{x^2 + y^2}$ to the non-negative reals under addition.
As a final example, let $f(x)$ be the inverse hyperbolic arctangent, so that $f^{-1}(x) = \tanh(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}}$. Then it turns out that
$$f^{-1}(f(x) + f(y)) = \frac{x + y}{1 + xy}$$
which is (in appropriate units) the velocity-addition formula in special relativity, and $f$ defines an isomorphism from the interval $(-1, 1)$ under the above operation to the reals under addition.

A: Let us find some characteristic of the set of numbers that does not change when you group two of them the way you describe.
The formula $\frac{xy}{x+y}$ suggests the following characteristic: $$\chi(a,b,c,\ldots)=\frac{1}{a}+\frac{1}{b}+\frac{1}{c}+\ldots$$ Indeed, if we take two numbers $m$ and $n$ and group them, then $$\chi(a,b,\ldots,m,\ldots,n,\ldots)=\frac{1}{a}+\ldots+\frac{1}{m}+\ldots+\frac{1}{n}+\ldots=\frac{1}{a}+\ldots+\frac{m+n}{mn}+\ldots=\chi(a,b,\ldots,\frac{mn}{m+n},\ldots)$$
Therefore, when you group any two numbers in the set, its characteristic does not change, and what you are going to get at the end (regardless of the sequence of pairs you choose) is one number $x$ such that $$\chi(a,b,c,\ldots)=\frac{1}{a}+\frac{1}{b}+\ldots=\chi(x)=\frac{1}{x}$$


text:
Q: Cannot convert from object to string error Hi I have code like this :
foreach (DataRow dr in upCSV.Rows)
                    {
ObjectParameter getCustomField1 = new ObjectParameter("CustomField1", String.IsNullOrEmpty(dr["CustomField1"]) ? null : Convert.ToInt32(dr["CustomField1"]));

var results = ordertable.usp_AppUpdateUserData(Convert.ToInt32( getCustomField1) )
   }

Here I am getting error as Cannot convert from object to string .
Here Customefield1 is of int type and it has null value. So when i debug, it is showing value for customfield1 as  " ". So how can I convert this to int and pass it to my Stored procedure ?

A: You can cast your dr["CustomField1"] object directly to an int?:
foreach (DataRow dr in upCSV.Rows)

{
int? CustomField1 = dr["CustomField1"] as int?;
ObjectParameter getCustomField1 ;
if (CustomField1.HasValue)
{
    getCustomField1 = new ObjectParameter("CustomField1", CustomField1);
}
else
{
    getCustomField1 = new ObjectParameter("CustomField1", typeof(global::System.Int32));
    getCustomField1.Value = DBNull.Value;
}
    var results = ordertable.usp_AppUpdateUserData(getCustomField1);

}


text:
Q: Hosting asp.net MVC 5 website picture
I am having troubles with iis. I have created a website and published my files in here - the structure looks good. Now when I try to load that site from outside - I get the server error as if something is broken here or not set properly.
I've tested the same functionality locally  and I can host just fine. Anyone know what might be missing here?


text:
Q: Debugging by outputting the full XML of a variable in xslt using xml:message I have a variable called $statuses.
I want to output the full XML, rather than just the values in the nodes, so I tried to do the following:-
<xsl:message>Contents of the nodeset_statuses:-
    <xsl:copy-of select="$statuses"/>
</xsl:message>

However, this only outputs the values in the nodes in the XML which is not what I want. I want the XML "as it is". I've seen some examples of "prettyPrint" templates like with dom4j but I'll be honest it really shouldn't be that much work.
Is there any Java method call available?
I tried something like:
<xsl:message>
    <xsl:variable name="output" select="java:System.out.println('print me something')"/>
</xsl:message>

With an XML namespace definition of:
xmlns:java="http://xml.apache.org/xslt/java"

But that didn't work as it returned the error:

System.out.println isn't a recognised part of the java / xslt apache extensions.

Does anyone know what the actual Java call is to achieve what I want or a way to do it?
Thanks in advance.

A: Your comment suggests you're using Xalan, which has an extension for writing output to different result documents.  Add
xmlns:redirect="http://xml.apache.org/xalan/redirect"
extension-element-prefixes="redirect"

to the <xsl:stylesheet> root element of your transformation, then you can use
<redirect:write select="'statuses_debug.xml'">
  <statuses>
    <xsl:copy-of select="$statuses"/>
  </statuses>
</redirect:write>

to dump the variable to a separate file (I've added a single root element to make the output well-formed if $statuses contains more than one element).

A: Use the document function and the xsl:variable nodeset to read the value:
<xsl:message>
  <xsl:value-of select="document('')/*/xsl:variable/@select[../@name='output']"/>
</xsl:message>


text:
Q: Writing an integral in terms of the Hypergeometric Function I have the following function defined as an integral:
$G(x,k,s) = 1 - (k-1) \int_0^{x/s} (1-t)^{k-2} dt$
Or alternatively directly as:
$G(x,k,p) = (1-\frac{x}{s})^{k-1}$
Is there any way (or approximation) to write it as a function of the Gaussian hypergeometric function $_2F_1(a,b;c,1)$ or $_2F_1(a,b;c,z)$?

A: $$_2F_1(a,b;c;z)=\frac{\Gamma(c) }{\Gamma(b)\Gamma(c-b)}\int_0^1\theta^{b-1}(1-\theta)^{c-b-1}(1-\theta z)^{-a}d\theta$$
Let $\quad a=2-k \quad;\quad b=1\quad;\quad c=2  $
$$_2F_1(2-k,1;2;z)=\int_0^1(1-\theta z)^{k-2}d\theta$$
Let $\quad \theta=\frac{s}{x}t\quad;\quad z=\frac{x}{s}$
$_2F_1(2-k,1;2;x/s)=\int_0^{x/s}(1-t)^{k-2}\frac{s}{x}dt$
$$\int_0^{x/s}(1-t)^{k-2}dt = \frac{x}{s}\:_2F_1\left((2-k)\:,\:1\:;\:2\:;\:\frac{x}{s}\right)$$


text:
Q: Using Doorkeeper inside Rails Engine I am trying to implement doorkeeper into my Rails App. My App consists of 2 mountable engines. Api and CoreApi.
  constraints :subdomain => 'api' do
    mount Api::Engine => '/'
  end

  constraints :subdomain => 'core.api' do
    mount CoreApi::Engine => '/'
  end

I want to use Doorkeeper in the CoreApi Engine to protect those endpoints with OAuth. I have included the Doorkeeper gem in my gemspec for that engine. I have also set the symbol in the initializer.
CoreApi::Doorkeeper = ::Doorkeeper

Everything is working except when I try to visit the applications index path for doorkeeper. I ran rake routes and the paths for the CoreApi engine list all the doorkeeper paths. The issue is
undefined local variable or method `new_oauth_application_path'

its referring to the url helper on line 11 of doorkeeper-1.0.0/app/views/doorkeeper/applications/index.html.erb
I can't figure out why this is not resolving. I assume its because doorkeeper is a rails mountable engine and I am trying to mount it inside a rails mountable engine.

A: Add to first line of config/initializers/doorkeeper.rb:
Doorkeeper::ApplicationController.send(:include, CoreApi::Engine.routes.url_helpers)


text:
Q: Making only specific parts of a string uppercase For a project of mine, I am parsing reddit comments and trying to make them uppercase. It works perfectly well with plain text, however with things such as links it creates bugs, making the characters in the link uppercase and therefore making the link unusable. Now links on reddit have very simple syntax, namely [text](url). I would like to output [TEXT](url) knowing my comment will most probably have some other content.
I tried using regexes, but this doesn't work while I still think I'm pretty close :
import re

def make_upper(comment):
    return re.sub(r"\[([^ ]*)\]\(([^ ]*)\)", r"[\1]".upper() + r"(\2)", comment)

That regex is a bit messy (like all regexes ;) but still readable to me and I wouldn't mind explaining it if need be.
Input:
"blablabla (btw, blargh!) [text](url) blabla"

Desired output:
"BLABLABLA (BTW, BLARGH!) [TEXT](url) BLABLA"

A: This is the approach I took after some experimenting. I'm sure people will downvote me and let me know in comments if I've overlooked something just like I did to them.
Step 1: The Regex
You were almost right here, but I would make it non-greedy so that it doesn't treat two links separated by non-linked text as one.
MARKDOWN_LINK_REGEX = re.compile(r'\[(.*?)\]\((.*?)\)')

Also, at least for the part in square brackets, don't assume there won't be spaces. People can link as many words as they want, even whole sentences.
Step 2: The Function
def uppercase_comment(comment):
    result = comment.upper()
    for match in re.finditer(MARKDOWN_LINK_REGEX, comment):
        upper_match = match.group(0).upper()
        corrected_link = upper_match.replace(match.group(2).upper(),
                                             match.group(2))
        result = result.replace(upper_match, corrected_link)
    return result

First, make the whole comment uppercase, then make corrections. For the corrections, I loop over all the non-overlapping matches the regex above produces (re.finditer), fix the link by lowercasing what's in parentheses, then make that replacement in the original comment string.
As was pointed out in the comments, lowercasing a link will not always work -- the original case must be preserved. In the updated function, we loop over matches in the original comment (and thus the original case) to generate the replacement, adding it to the uppercase string we created at the beginning.
Step 3: Testing it Out
if __name__ == '__main__':
    print(uppercase_comment('this comment has zero links'))
    print(uppercase_comment('this comment has [a link at the end](Google.com)'))
    print(uppercase_comment('[there is a link](Google.com) at the beginning'))
    print(uppercase_comment('there is [a link](Google.com) in the middle'))
    print(uppercase_comment('there are [a few](Google.com) links [in](StackOverflow.com) this one'))
    print(uppercase_comment("doesn't matter (it shouldn't!) if there are [extra parens](Google.com)"))

Produces
THIS COMMENT HAS ZERO LINKS
THIS COMMENT HAS [A LINK AT THE END](Google.com)
[THERE IS A LINK](Google.com) AT THE BEGINNING
THERE IS [A LINK](Google.com) IN THE MIDDLE
THERE ARE [A FEW](Google.com) LINKS [IN](StackOverflow.com) THIS ONE
DOESN'T MATTER (IT SHOULDN'T!) IF THERE ARE [EXTRA PARENS](Google.com)

Please comment with feedback and fixes. Note mine is in Python 3 but the only 3-specific thing I'm using is the print function.

A: Thanks to all of you, here's a combined version of all of your suggestions, that does everything I want it to :
def make_upper(comment):
    native_links = re.findall(r"\[.*?\]\((.*?)\)", comment)
    result = comment.upper()
    for url in native_links:
        result = result.replace(url.upper(), url)
return result

I'm not quite sure it's the fastest way but in the final algorithm this code shouldn't be used too often so that'll do, thanks again!

A: The previous answers rely on global search and replace to handle the solution.  This is flawed for the case where the URL for a link is also contained in the rest of the text.  A guaranteed safe way to do it is to construct the new string as you go along.
For example, while this isn't elegant, it does the trick:
MARKDOWN_LINK_REGEX = re.compile(r'(.*?)(\[.*?\])(\(.*?\))(.*)')

def uppercase_comment(text):
    result = ""
    while True:
        match = MARKDOWN_LINK_REGEX.match(text)
        if match:
            result += match.group(1).upper() + match.group(2).upper()
            result += match.group(3)
            text = match.group(4)
        else:
            result += text.upper()
            return result


text:
Q: Thunderbolt or Mini display port Connect Macbook Pro mid 2012 to a 3d projector I have a question regarding connecting my Macbook Pro mid 2012 to a 3d projector.
So I understood my 3d projector has HDMI input and I need to connect it with my Macbook Pro.
I was a bit confused with mini display port and thunderbolt. As I understood my Macbook Pro Mid 2012 has thunderbolt 1, am I right.
So then I need to buy, Thunderbolt 1 to HDMI adapter. Mini Display port to HDMI will not work as I understood.
But then I searched through internet and found this adapter which description says that it's Mini Display port (thunderbolt) - HDMI adapter.
Currently I can't understand what should buy... There are only two points that I want to connect my Macbook Thunderbolt 1 port and HDMI port on my projector, which cable you can advice.
To summarize here are few important question to understood:

*

*Macbook Pro mid 2012 contains Thunderbolt 1 port (up to 10GB) YES/NO

*Is there any difference between Mini Display Port and Thunderbolt 1. Can I buy Mini Display Port to HDMI to output 3d HD video to my projector via Macbook Pro mid 2012.


text:
Q: XFCE (Xubuntu) Alt-Tab switcher: missing app icons I have missing icons for Slack and MailSpring (Electron based apps I believe) in Xubuntu 18.04 application switcher:

The application's icon appears correctly everywhere else (i.e. in panels, app launchers, etc.) - it is only the switcher that is not working.
I have tried solution from here with no luck: App icon not showing in switcher (alt+tab)
Any ideas would be greatly appreciated :)


text:
Q: Is there a way to connect to Kafka on an Azure virtual machine using port 80 or 443? If not, why? I would like to connect to Kafka using port 80 on my Azure virtual machine. I installed Java and Kafka on the virtual machine. I added inbound port rule for port 80.

I added port=80 to Kafka's config/server.properties file. I ran zookeeper succesfully.
When I try to connect to kafka I get this error:

ERROR [KafkaServer id=0] Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
org.apache.kafka.common.KafkaException: Socket server failed to bind to 0.0.0.0:80: Permission denied

I can connect to kafka using other ports, I tried 9092, 8000, 8080, 4430
But I can't connect to it using port 80 or 443. The problem is I want to access Kafka using port 80 or 443 because I want to produce messages using a web server which is only allowed to use port 80 or 443.
Why can't I connect to kafka using port 80 on an Azure virtual machine?

A: According to my knowledge, you can do the same things you did in your local machine. So you can connect the Kafka that configured in the VM using the port 80. And as the error shows, the problem is the permission. You need to check the permission of the Kafka or the User you use to configure the Kafka.
And for the Web App, it only can expose one port to the outside world, and the ports must be 80 or 443. But your application can listen to any ports inside the Web App, then you just need to set the environment variable WEBSITES_PORT for the port. Azure will route the requests outside from the port 80 to the port your application listens to. See the issue My custom container listens to a port other than port 80. How can I configure my app to route requests to that port?


text:
Q: Converting a C-String to all lower I'm trying to convert a C-String to all lower case wihout the use of tolower from ctype.h .
Hower my code does not seem to work: I'm receiving a runtime error. What I'm trying to do is changing the ASCII value of the  capitalized letters bij 'a' - 'A' which should convert those values to the ones for lower case as far as I'm aware.
#include <stdio.h>
void to_lower(char* k) {
    char * temp = k;
    while(*temp != 0) {
        if(*temp > 'A' && *temp < 'Z') {
            *temp += ('a' - 'A');
        }
        temp++;
    }
}

int main() {
    char * s = "ThiS Is AN eXaMpLe";
    to_lower(s);
    printf("%s",s);
}

A: Two errors.
This code won't convert A and Z to lowercase :
if(*temp > 'A' && *temp < 'Z') {

Use >= and <= instead.
And it's not legal to try to modify a string literal ! Arrays can be modified, string literals can't.
Change that char * s = "ThiS Is AN eXaMpLe"; to char s[] = "ThiS Is AN eXaMpLe";

A: Even if you don't use the existing standard library function, it may still be useful to follow its interface. tolower converts an individual character. Applying this function to a string can be written as a de-coupled function.
#include <stdio.h>
#include <string.h>

int to_lower (int c) {
    if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c))
        c = c - 'A' + 'a';
    return c;
}

void mapstring (char *str, int (*f)(int)) {
    for (; *str; str++)
        *str = f(*str);
}

int main() {
    char s[] = "THIS IS MY STRING";

    mapstring(s, to_lower);
    printf("%s\n", s);
    return 0;
}

A: Two problems that I can see immediately: (1) char *s = "This..." creates a non-writable string. You need to use a character array and copy a string into it. (2) if (*temp > 'A' && *temp < 'Z') skips A and Z. You need >= and <=.


text:
Q: Event listener functions changing when using React hooks I have a component that uses event listeners in several places through addEventListener and removeEventListener. It's not sufficient to use component methods like onMouseMove because I need to detect events outside the component as well.
I use hooks in the component, several of which have the dependency-array at the end, in particular useCallback(eventFunction, dependencies) with the event functions to be used with the listeners. The dependencies are typically stateful variables declared using useState.
From what I can tell, the identity of the function is significant in add/remove EventListener, so that if the function changes in between it doesn't work. At first i tried managing the hooks so that the event functions didn't change identity between add and remove but that quickly became unwieldy with the functions' dependency on state.
So in the end I came up with the following pattern: Since the setter-function (the second input parameter to useState) gets the current state as an argument, I can have event functions that never change after first render (do we still call this mount?) but still have access to up-to-date stateful variables. An example:
import React, { useCallback, useEffect, useState } from 'react';

const Component = () => {
  const [state, setState] = useState(null);

  const handleMouseMove = useCallback(() => {
    setState((currentState) => {
      // ... do something that involves currentState ...
      return currentState;
    });
  }, []);

  useEffect(() => {
    window.addEventListener('mousemove', handleMouseMove);
    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
    };
  }, [/* ... some parameters here ... */]);

  // ... more effects etc ...

  return test;
};

(This is a much simplified illustration).
This seems to work fine, but I'm not sure if it feels quite right - using a setter function that never changes the state but just as a hack to access the current state.
Also, for event functions that require several state variables I have to nest the setter calls.
Is there another pattern that could handle this situation in a nicer way?

A:
From what I can tell, the identity of the function is significant in add/remove EventListener, so that if the function changes in between it doesn't work.

While this is true, we do not have to go the extreme of arranging for even function not to change identity at all.
Simple steps will be:
Declare event function using useCallback - dependency list of useCallback should include all the stateful variables that your function depends on.
Use useEffect to add the event listener. Return cleanup function that will remove the event listener. Dependency list of useEffect should include the event listener function itself, in addition to any other stateful variable your effect function might be using.
This way, when any of stateful variable used by event listener changes, even listener's identity changes, which will trigger running of the effect, but before running the effect cleanup function returned by previous run of the effect will be run, properly removing old event listener before adding the new one.
Something on the lines of:
const Component = () => {
    const [state, setState] = useState();

    const eventListner = useCallback(() => {
        console.log(state); // use the stateful variable in event listener
    }, [state]);

    useEffect(() => {
        el.addEventListner('someEvent', eventListner);
        return () => el.removeEventListener('someEvent', eventListner);
    }, [eventListener]);
}

A: @ckedar 's solution can solve this question, but it has performance problem, when the eventListener change, react will remove and addEvent on the dom。
you can use useRef() instead useState(),if you want listen state change, you can use useStateRef():
import React, { useEffect, useRef, useState } from 'react';

export default function useStateRef(initialValue:any): Array<any>{
  const [value, setValue] = useState(initialValue);
  const ref = useRef(value);
  useEffect(() => {
    ref.current = value;
  },[value])
  return [value,setValue,ref];
}


text:
Q: Manipulation of SVG icon's dimensions I have the following SVG file

<svg width="523" height="524" style='background-color: teal;' xmlns="http://www.w3.org/2000/svg">

    <symbol id="icon-ec2d25d9" viewBox="0 0 60 30">
     <g stroke="#000" fill="#fff">
     <path d="M0 0h60v60H0z" fill="#FFF"/>
     <path d="M0 0l30 37.1v-18l30 37.2" fill="none"/>
     </g>
     <g>
     <path fill="none" d="M-1-1h583v403H-1z"/>
     </g>
     </symbol>

  <path d="M85 84 127 84 127 126 85 126 "/>
  <use href="#icon-ec2d25d9" x="85" y="84" width="22" height="36"  fill="none" stroke="black" class="icon 4"/>
</svg>

(https://jsfiddle.net/L5xz73j4/) and I would like to modify the dimensions of the small icon inside the black rectangle to match the width and height of the rectangle. I'm generating these kinds of SVG's on the fly so I cannot start playing with the width and height attributes by hand. My question is that can I use the path element of the black rectangle to achieve this or what's the appropriate way?

A: I've changed the viewBox of the symbol to viewBox="0 0 60 60" acording to the size of the group inside. Now the symbol is square. In order to make the use fill the black square I've changed the width and the height of the use to width="42" height="42" i.e, the size of the black square.
I hope this is what you are asking

<svg width="523" height="524" style='background-color: teal;' xmlns="http://www.w3.org/2000/svg">

    <symbol id="icon-ec2d25d9" viewBox="0 0 60 60">
     <g stroke="#000" fill="#fff">
     <path d="M0 0h60v60H0z"/>
     <path d="M0 0l30 37.1v-18l30 37.2" fill="none"/>
     </g>

     <!--<g><path fill="none" d="M-1-1h583v403H-1z"/></g>-->

     </symbol>

  <path d="M85 84 127 84 127 126 85 126 " />
  <use href="#icon-ec2d25d9" x="85" y="84" width="42" height="42"  fill="none" stroke="black" class="icon 4"/>
</svg>


text:
Q: Changing color of molecules using cmd I have written a python script to draw molecules in PyMol utilizing PYMOL API. I had loaded a file with geometry and then I wanted to change a color of carbon atoms.
I utilized cmd.color( "black", selection = "*C" ), but any changes were displayed. I am not sure if I understand all arguments of the color function. Maybe something wrong is with the second argument?

A: Have you made sure you have correct atoms selected in "*C" variable?
cmd.color('black', selection=cmd.select('c*'))

https://pymol.org/dokuwiki/doku.php?id=api:cmd:select
since "c*" selects every all carbon atoms such as ca, cb, and so on, this solution might work.


text:
Q: NSSortDescriptor Order Values Less than 10.0 NSSortDescriptor is not ordering correct when distance is less than 10.0.
Code (Order array by Distance):
// Order Array by Distance (Distance = NSString)
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES];
[_contentData sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];

Right Ordering (When distance values are > 10.0):
    (
            {
            distance = "11.256649";
        },
            {
           distance = "257.428821";
        },
            {
            distance = "4534.256851";
        }
    )

Wrong Ordering (When any distance value is < 10.0):
    (
            {
           distance = "252.428821";
        },
            {
            distance = "4514.256851";
        }
            {
            distance = "8.362996"; // Wrong ordering when distance < 10.0
        },
    )

A: I don't think the issue here is that the value is less than 10.  It appears that your values are strings, and are being ordered character by character.  "8" comes after "4", so it's ordered later.
If you convert your string values to NSNumbers, they should sort properly.


text:
Q: Can't get failing script to return exit code I've got a simple powershell script like this:
Set-Strictmode -version Latest
$ErrorActionPreference = 'Stop'

try
{
  Write-Host "aaa $(MyFunc "bbb)"
}
catch
{
  Write-Host "Caught the error!"
  Write-Host $error
  exit 666
}

(Note that this script has an error in the first Write-Host line.)
I need my scripts to run in such a way that if there are any  errors, it will return with a non-zero value.   This is the purpose of setting "Set-Strictmode", "$ErrorActionPreference", and wrapping it all in a try…catch block.
But when I run it from the windows cmd.exe, you can see that the error is not caught and that it does not return an error code:
D:\jjj>powershell -F jjj.ps1
At D:\jjj\jjj.ps1:6 char:28
+   Write-Host "aaa $(MyFunc "bbb)"
+                            ~~~~~
The string is missing the terminator: ".
At D:\jjj\jjj.ps1:6 char:34
+   Write-Host "aaa $(MyFunc "bbb)"
+                                  ~
Missing closing ')' in subexpression.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

D:\jjj>echo Exit Code is %errorlevel%
Exit Code is 0

I suspect that the unmatched quotes in the errorful line is mangling the interpretation so much that the try…catch block is never properly instantiated.
So, here's the question:  what can I do to ensure that any execution errors of my PowerShell script cause it to return with a non-zero errorcode?

A: You have a syntax error there, not a runtime error. There's nothing you can do except actually fixing it. Syntax errors can't be caught at runtime, because they occur when PowerShell parses the code, i.e. before the instructions actually get executed.
If you run the script from within PowerShell the automatic variable $? will be set to $false, though. If you run it in a new powershell process like this:
powershell "C:\path\to\your.ps1"

the errorlevel ($LASTEXITCODE in PowerShell) will be set to 1 on errors. Unfortunately the errorlevel is not set when you run the script using the -File parameter:
powershell -File "C:\path\to\your.ps1"

which you'd normally do to have regular exit codes from the script returned to the caller.


text:
Q: Abstract test classes with xUnit.net and ReSharper test runner
I wanted to unit-test an abstract class by creating abstract test-class with  abstract factory method (using this approach) that polymorphically gets the concrete instance. Something like this:
public abstract class Base
{
  public bool MyMethod()
  {
    return true;
  }
}

public class Derived : Base {}

// Tests

public abstract class BaseTest
{
  [Fact]
  public void MyMethod_MakeTestFailByAssertingFalseReturn()
  {
    //Arrange
    var instance = GetConcreteInstance();

    //Act
    bool result = instance.MyMethod();

    //Assert
    Assert.False(result);
  }

  protected abstract Base GetConcreteInstance();
}

public class DerivedTest : BaseTest
{
  protected override Base GetConcreteInstance()
  {
    return new Derived();
  }
}

So far, so good. But ReSharper test runner gives this error:

Inconclusive: Test wasn't run

for all tests inside BaseTest class. Even the ones that are ignored. I tried to run the tests with Visual Studio test runner, but it doesn't detect any of them.

A: You can check this. Also i had problems with text explorer that didnt find my tests, i manage to fix the problem when i delete a temp visualstudioextension directory which you can find at path - C:/users/USERNAME/AppData/Local/Temp/VisualStudioTestExplorerExtensions.


text: Q: tbl_regression - resolving long tables by indicating categorical variables were included but not breaking down stats for each category My regression model uses several control variables that contain several categorical values, each. When I use tbl_summary to get a table, it comes out very long. I don't really care about showing the results for these variables. Is there a way to collapse the tbl_regression display of a given variable, to show that it was included in the regression but without listing all its categorical values?


text:
Q: LDAP Authentication failed. Could that be due to change in domain? I could login to a web application when i was under the domain "X" but recently migrated to "y".  But my VS.Net 2003 code doesn't do anything to verify the domain.  As long as i'm registered with the database, it takes me in.  I'm really surprised why it stopped working all of a sudden.  Could there be anything due to Active directory setting at the network level?
FYI: I use my windows login id (the same registered in the database) and domain password to login.
Here is the code.
When login.aspx loads, i call Authenticate() method
            private void Authenticate()
            {
                try
                {
                    oBELogin = new EntityLogin(); //Property

                    oBELogin.UserId = Context.User.Identity.Name.Split('\\')[1].ToString(); //Here i used to get "domain name\login id".
                    dsLogin = (DataSet)oWFLogin.DBAuthentication(oBELogin,"Y"); //This is a web service call for authentication.  From there Database layer -> Stored procedure call.  Everything happens fine

                    if(dsLogin.Tables[0].Rows.Count>0)
                    {
                       //Code for session that works.
                        Response.Redirect("Page2.htm",false);
                    }
                }
                catch(System.Threading.ThreadAbortException excep) {}
                catch(System.IndexOutOfRangeException exOutOfRange)
                {
                  //Write IndexOutOfRangeException
                }

                catch(Exception ex)
                {
                  //LDAP error
                }
            }

I'm supplying proper login credentials on the web form.
I've set domain specific values in web.config but those are not being used anywhere in this scope.  I wish i should give more details about the problem.  But however i think, this is
the maximum i could get to.
Further information: I could record this error message to the log file.
8/14/2012 11:45:06 PM : System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Runtime.InteropServices.COMException (0x8007052E): Logon failure: unknown user name or bad password
   at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
   at System.DirectoryServices.DirectoryEntry.Bind()
   at System.DirectoryServices.DirectoryEntry.get_NativeObject()
   at WorkFlow.WorkFlowLogin.Login()
   at WorkFlow.WorkFlowLogin.LDAPAuthentication(EntityLogin oBELogin, String strURL, String strDomain)
   --- End of inner exception stack trace ---   at Web.Login.LDAPUserAuth()
   at Web.Login.btnLogin_ServerClick(Object sender, EventArgs e) Source = Web Url = http://localhost:8090/Web/WorkFlow/WorkFlowLogin.asmx


text:
Q: GoPro on wifi and internet on Lan I have here an gopro and I would like to connect to it while still being able to browse the internet, so I connect my wifi to the gopro's one ( and I can interact with it) but when I then use my usb - LAN adapter I can connect to the internet, but not to the gopro anymore
I think this sould be possible by adding routes, but I don't have any experiance on routes on windows.
Anyone got an idea on how to accomplish this?
Additional info:
If you are connnected to the gopro and go to the 10.5.5.9:8080 in your browser you can interact with the footage / live stream

A: Try doing this:
https://youtu.be/ISzhlMCpk5I
You'll need a spare wireless router with DD-WRT or something similar but once setup you'll be good to go.


text:
Q: Auto-stretch a multipart CSS background by content size I am building a CSS site and fail solving this partial problem:
On the left side there is a box which consists of three images. A top image, an (optional and stretched) middle image, and a bottom image.
I want the box to the left automatically stretch if there is more content inside. This already works for the right side with my current code.
(I put both columns into a container div and set the left box to height: 100.)
But now there shall also be content in the left box. This content does overflow because I set the left box to position: absolute. Thus it does not increase the size.
I didn't manage to get this effect without position: absolute though. I tried using float etc.
Here is the example code:

        Header etc

                Content here will auto-stretch the container vertically (and the box to the left!)

        Footer etc

With this stylesheet:
#centerwrapper {
    width: 500px;
    margin: 0 auto;
}
#verticalstretcher {
    position: relative;
    min-height: 280px; /* Sum of the top and bottom image height */
    width: 100%;
    background-color: orange;
}
#bgtop {
    position: absolute;
    width: 185px; /* width of the bg images */
    height: 100%;
    background: url(css/img/bg_navi_left_top.gif) no-repeat;
}
#bgbottom {
    position: absolute;
    width: 100%;
    height: 100%;
    background: url(css/img/bg_navi_left_bottom.gif) bottom no-repeat;
}
#bgmiddle {
    position: absolute;
    width: 100%;
    top: 250px; /* Don't cover top GIF */
    bottom: 15px; /* Don't cover bottom GIF */
    background-color: yellow; /* Repeated image here */
}
#content {
    margin-left: 200px; /* Start the text right from the box */
}

It looks like this (Colored it for better understanding):

The yellow part is actually a stretched image, I left it out for the example, it works as expected.
How can I add text into the left box that will also stretch it? Or is it possible with TABLE instead of CSS at this point?
EDIT: BitDrink's solution looks this way at my browser (current FF)
alt text http://img502.imageshack.us/img502/1241/layoutsample2.png

A: I could be wrong here but what you are trying to achieve here is two columns of the same height no matter how much text is in the left or right columns.
Equal Height Columns using CSS is the best CSS technique for this where by the backgrounds and bottom curved edges would need to be given to div#vertical stretcher.
The only other way that I know to make two columns equal height is to use JavaScript. See The Filament group article on setting equal heights with jQuery.

A: the problem is the absolute positioning! If you want an automatic resize (in vertical) of the left box, just apply a "float:left" to #bgtop!
Notice that the attribute "min-height" is not supported from all browsers (for example IE6)! The code below is an example:

        Header etc

                text top

                        text middle

                            text bottom

         Content here will auto-stretch the container vertically (and the box to the left!)

Footer etc

You can see the result below:

The 4 div(s) resize vertically according to their content!


text:
Q: AbstractModel VS ConcreteModel of pyomo? how does "opt.options["tol"]" make the difference in finding optimal solution? I have an AbstractModel and a ConcreteModel solving the same problem, but they are performing differently. It is mainly about initial value of a variable and tolerance of ipopt.

*

*When I initialize my variable model.x as 10 and opt.options["tol"] = 1E-64:
ConcreteModel can find optimal solution, while abstract model "Solved To Acceptable Level". (But the solutions they find are actually the same)

*When I initialize my variable model.x as 100 and opt.options["tol"] = 1E-64:
ConcreteModel can find the optimal solution, while abstract model sometimes "Solved To Acceptable Level" and sometimes "Cannot load a SolverResults object with bad status: error".

*If I just use the ipopt's default value of the tolerance, both ConcreteModel and AbstractModel can find the same optimal solution no matter how I initialize the variable model.x.
So I wonder how opt.options["tol"] makes a difference? Why is ConcreteModel always able to find an optimal solution in this case while AbstractModel not?
Variable
model.x = Var(model.Crops, model.Inputs, initialize = 100, within=NonNegativeReals)

solve script of AbstractModel
instance = model.create_instance(data="AbstractCDFarm.dat")
opt = SolverFactory("ipopt")
opt.options["tol"] = 1E-64
results = opt.solve(instance, tee=True)
instance.display()

solve script of ConcreteModel
opt = SolverFactory('ipopt')
opt.solve(model, tee=True)
opt.options["tol"] = 1E-64
results = opt.solve
model.display()

A: You're calling solve twice for the ConcreteModel and it looks like the output you're seeing is for the default Ipopt tolerance not for the tolerance of 1E-64. Why are you setting such a low tolerance? 1E-64 is smaller than machine precision so it's an impossibly small tolerance to converge to.


text:
Q: Why do I get an error "Neither BindingResult nor plain target object for bean name 'user' available as request attribute" in this case? Why do I get this error? Before connecting the validation and adding forms of the
form: label / input - everything worked for me
 @RequestMapping(method = POST, value = "/reg")
    public String registration(@ModelAttribute("userReg") @Valid User user, BindingResult bindingResult,
                               HttpSession session) {
        if(bindingResult.hasErrors()) return "redirect:/reg";
        if (userDAO.findByLogin(user.getLogin()) == null) {
            userDAO.persist(user);
            session.setAttribute("login", user.getLogin());
            return "welcomepage";
        }
        return "Registration";
    }

Exceptions:
 org.apache.jasper.JasperException: An exception occurred processing JSP page /Registration.jsp at line 18

    15: <form:form action="/reg" method="post" modelAttribute="user">
    16:

    17:

    18:                 <form:label path="login">Login:</form:label>
    19:                  <form:input path="login"/>
    20:                  <form:errors path="login"/>
    21:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute

Continuing the form from the error:
 ...

                 <form:label  path="password">Password:</form:label>
                 <form:input  path="password"/>
                 <form:errors path="password"/>

    <input type="submit" value="Registration">
</form:form>

A: This error happens because you don't pass the object 'user' to Model in your controller.
Returning ModelAndView is a option but you can put the object in the Model object and return your page address.
@GetMapping("/user")
public View retrieveUser(ModelMap model, HttpServletRequest request) {
  model.addAttribute("user", userService.getUser());
  String contextPath = request.getContextPath();

return new RedirectView(contextPath); }

A: The problem was that the page did not have the required attribute. And the error crashed because the name field was not found in the "user" that was not filled.
To fix the error i added object ModelAndView() with "user" atribute.
@RequestMapping(method = GET, value = "/reg")
public ModelAndView registration() {
    return new ModelAndView("Registration","user",new User());
}


text: Q: it is possible to have multiple html in vue.js? I'm currently using vue.js and I have a basic knowledge about vue.js, I'm just curious if its possible to create many html in one project. and if possible can you help me on how to create one. thanks in advance for the answer.


text:
Q: macports dependency: upgrade all packages not depending on a specific port I have upgraded to Maverick
when I run:
sudo port upgrade outdated

I get the error:
Error: eigen does not build on Mavericks or later.

I have plenty of ports that does not depend on eigen, how do i figure out which ones they are and how do I update them?
For example:
sudo port install pypy

upgraded pypy to the newest version, but sudo port upgrade outdated did not work because it crashes before it reaches pypy
questions:

*

*is there a way to upgrade all packages that does not depend on a specific port (eigen in my case)

*or atleast: is there a way to get a list of all ports that depends (or does not depend) on a specific port

NB: I have uninstalled (I am an idiot) eigen, so I cannot do
sudo port -n upgrade outdated
# -n: don't upgrade dependencies (affects upgrade and install)

Update
what Vortexfive suggested should work:
sudo port upgrade outdated and not rdepof:eigen

however it dosent if you have already deleted eigen, so do not follow my example!

A: To list the installed ports that depend on a specific port you can do port list rdepof:eigen.
To list the installed ports that do not depend on a specific port do port list installed and not rdepof:eigen.
Finally to update all ports that do not depend on a specific port do sudo port upgrade outdated and not rdepof:eigen.
I'm however not completely sure if this will work with the port (eigen) already uninstalled.


text:
Q: How to manage nohup.out file in Tornado? I built a web service using tornado and it serves days and nights. I used the command to start my service:
nohup python my_service.py &

The service log is able to write to nohup.out. However, the file becomes bigger as time goes. I want to know how can I manage it more conveniently? For saying, using an automatic method to generate the log files with proper names and size? Such as:
service_log_1.txt
service_log_2.txt
service_log_3.txt
...

Thanks.

A: Yes, there is. Put a cron-job in effect, which truncates the file (by something like  "cat /dev/null > nohup.out"). How often you will have to run this job depends on how much output your process generates.
But if you do not need the output of the job altogether (maybe its garbage anyways, only you can answer that) you could prevent writing to file nohup.out in first place. Right now you start the process in a way like this:
nohup command &

replace this by
nohup command 2>/dev/null 1>/dev/null &

and the file nohup.out won't even get created.
The reason why the output of the process is being directed to a file is:
Normally all processes (that is: commands you enter from commandline, there are exceptions, but they don't matter here) are attached to a terminal. Per default (this is how Unix is handling this) this is something which can display text and is connect to the host via a serial line. If you enter a command and switch off the terminal you entered it from the process gets terminated too - because it lost its terminal. Because in serial communication the technicians traditionally employed the words from telephone communication (where it came from) the termination of a communication was not called an "interruption" or "termination" but a "hangup". So programs got terminated on "hangups" and to program to prevent this was "nohup", the "no-termination-upon-hangup"-program.
But as it may well be that such an orphaned process has no terminal to write to it nohup uses the file nohup.out as a "screen-replacement", redirecting the output there, which would normally go to the screen. If a command has no output whatsoever though nohp.out won't get created.

A: Simple:
nohup python my_service.py >service_log_1.txt 2>&1 &

A: If the output is being produced by some library that you are using and you don't have control over it, you can re-direct the standard output to a file when the program starts. Then you can close and re-open the file periodically to prevent the files to grow forever. You can use a timestamp for the name of the file so it is always diferent. Something like:
import sys
import datetime
current_stdout = None
def reset_stdout():
    global current_stdout
    if current_stdout:
        current_stdout.close()
    sys.stdout = open(
        "{}.log".format(
            datetime.datetime.now().strftime('%Y%m%d%H%M%S')
            ),
        "w")
    current_stdout = sys.stdout
reset_stdout()

# Then call this every day.. week ..
reset_stdout()

If you prefer to reset the file depending on the size of it, you can monitor periodically its size with something like this:
if current_stdout.tell() > 1000000:
    reset_stdout()

But if you do have control over the output that you are sending, I strongly recommend to use the logging library. It has a lot of flexibility on what you can do with the output. The messages sent to the log can be processed by objects called handlers. One of the handlers included in the library do what you want, is called the RotatingFileHandler. From the documentation:
class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)

"You can use the maxBytes and backupCount values to allow the file to
  rollover at a predetermined size. When the size is about to be
  exceeded, the file is closed and a new file is silently opened for
  output. Rollover occurs whenever the current log file is nearly
  maxBytes in length; if maxBytes is zero, rollover never occurs."

So you can do all the logging using something like this:
import logging
import logging.handlers
# Create a logger
log = logging.getLogger('example')
# Set the level of the logger. By doing this all the messages with a "level" of INFO or higher will be
# sent to the log
log.setLevel(logging.INFO)
# Create the handler and set 20 files to rotate and a maximum size of 1MB
handler = logging.handlers.RotatingFileHandler('log',maxBytes = 1000000,backupCount=20)
# Now attach the handler to the logger object
log.addHandler(handler)

# Now you can send your output like:
log.info('text text text text text text text text text')
log.info(....

A: @jujaro 's answer is quite helpful and I tried logging module in my web service. However, there are still some restrictions to use logging in Tornado. See the other question asked.
As a result, I tried crontab in linux to create a cron job at midnight (use crontab -e in linux shell):
59 23 * * * source /home/zfz/cleanlog.sh

This cron job launches my script cleanlog.sh at 23:59 everyday.
The contents of clean.sh:
fn=$(date +%F_service_log.out)
cat /home/zfz/nohup.out >> "/home/zfz/log/$fn"
echo '' > /home/zfz/nohup.out

This script creates a log file with the date of the day ,and echo '' clears the nohup.out in case it grows to large. Here are my log files split from nohup.out by now:
-rw-r--r-- 1 zfz zfz  54474342 May 22 23:59 2013-05-22_service_log.out
-rw-r--r-- 1 zfz zfz  23481121 May 23 23:59 2013-05-23_service_log.out


text:
Q: Use textit in listing How can I use \textit in a listing?
\documentclass[a4paper]{article}

\begin{document}

\begin{lstlisting}[label=test]
Some code.
\textit{This should be italic.}
Some code.
\end{lstlisting}

\end{document}

A: You can emphasize words using the emph and emphstyle keys.
See page 19 in the listings manual.
\documentclass[a4paper]{article}

\usepackage{listings}

\begin{document}

\lstset{emph={world}, emphstyle=\itshape} % the word "world" shall be italic
\begin{lstlisting}[label=test]
   Hello world
\end{lstlisting}

\end{document}

I agree, it is not a good solution for highlighting single lines of code.
I think here is what you are looking for:
\documentclass[a4paper]{article}

\usepackage{listings}
\lstset{escapeinside={(*@}{@*)}}

\begin{document}

\begin{lstlisting}[label=test]
Some code.
(*@\textit{This should be italic.}@*)
Some code.
\end{lstlisting}

\end{document}


text:
Q: Magento 2 - How to get new data after first data migration? I created a fresh magento 2.3.5-p1 shop and migrated the data from an M1 store by using the php bin/magento migrate:data command.
Now one week later new data was added to the M1 shop (two new CMS sites: cat, dog) and some old sites were removed from M2 (donkey, horse).
Can I trigger a migration so that the changes from M1 are getting transfered to M2?
And will this load the deleted CMS sites (donkey, horse) into M2 again?

Output of:
php bin/magento migrate:delta vendor/magento/data-migration-tool/etc/opensource-to-commerce/1.9.4.4/config.xml

[company@company]$ php bin/magento migrate:delta vendor/magento/data-migration-tool/etc/opensource-to-commerce/1.9.4.4/config.xml

[2020-07-15 07:43:37][INFO][mode: delta][stage: delta delivering][step: Customer Attributes Step]: started
...................................................................................................................................
[2020-07-15 07:43:37][INFO][mode: delta][stage: volume check][step: Customer Attributes Step]: started
100% [============================] Remaining Time: < 1 sec
[2020-07-15 07:43:37][WARNING]: Mismatch of entities in the document: customer_entity Source: 2250 Destination: 50
[2020-07-15 07:43:37][WARNING]: Mismatch of entities in the document: customer_entity_int Source: 11767 Destination: 133
[2020-07-15 07:43:37][WARNING]: Mismatch of entities in the document: customer_entity_varchar Source: 3556 Destination: 17
[2020-07-15 07:43:37][WARNING]: Mismatch of entities in the document: customer_address_entity Source: 2643 Destination: 62
[2020-07-15 07:43:37][WARNING]: Mismatch of entities in the document: customer_address_entity_datetime Source: 132 Destination: 1
[2020-07-15 07:43:37][WARNING]: Mismatch of entities in the document: customer_address_entity_varchar Source: 252 Destination: 2
[2020-07-15 07:43:37][WARNING]: Volume Check failed
[2020-07-15 07:43:37][INFO][mode: delta][stage: delta delivering][step: Map Step]: started
...................................................................................................................................
[2020-07-15 07:43:41][INFO][mode: delta][stage: volume check][step: Map Step]: started
100% [============================] Remaining Time: < 1 sec
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_category_entity Source: 56 Destination: 55
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_category_entity_datetime Source: 110 Destination: 94
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_category_entity_decimal Source: 55 Destination: 47
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_category_entity_int Source: 333 Destination: 334
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_category_entity_text Source: 277 Destination: 258
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_category_entity_varchar Source: 441 Destination: 434
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_compare_item Source: 2 Destination: 0
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_entity Source: 6029 Destination: 5929
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_entity_datetime Source: 27986 Destination: 27511
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_entity_decimal Source: 14871 Destination: 14548
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_entity_int Source: 36933 Destination: 36383
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_entity_media_gallery Source: 735 Destination: 734
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_entity_media_gallery_value Source: 735 Destination: 734
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_entity_text Source: 22765 Destination: 22377
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_entity_varchar Source: 78457 Destination: 77130
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_link Source: 953 Destination: 594
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_link_attribute_int Source: 944 Destination: 585
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_option Source: 612 Destination: 584
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_option_price Source: 290 Destination: 280
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_option_title Source: 612 Destination: 584
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_option_type_price Source: 1659 Destination: 1597
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_option_type_title Source: 1659 Destination: 1597
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_option_type_value Source: 1659 Destination: 1597
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_relation Source: 5583 Destination: 5485
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_super_attribute Source: 143 Destination: 139
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_super_attribute_label Source: 143 Destination: 139
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_super_link Source: 5167 Destination: 5069
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: catalog_product_website Source: 6027 Destination: 5927
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: cataloginventory_stock_item Source: 6029 Destination: 5929
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: newsletter_subscriber Source: 2997 Destination: 1806
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: report_compared_product_index Source: 1 Destination: 0
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: report_event Source: 1152406 Destination: 1105350
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: sales_order_tax Source: 13470 Destination: 12764
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: sales_order_tax_item Source: 49810 Destination: 47090
[2020-07-15 07:43:44][WARNING]: Mismatch of entities in the document: wishlist Source: 847 Destination: 5
[2020-07-15 07:43:44][WARNING]: Volume Check failed
[2020-07-15 07:43:44][INFO][mode: delta][stage: delta delivering][step: Log Step]: started
...................................................................................................................................
[2020-07-15 07:43:46][INFO][mode: delta][stage: volume check][step: Log Step]: started
100% [============================] Remaining Time: < 1 sec
[2020-07-15 07:43:52][WARNING]: Mismatch of entities in the document: customer_visitor Source: 3037874 Destination: 2959584
[2020-07-15 07:43:52][WARNING]: Volume Check failed
[2020-07-15 07:43:52][INFO][mode: delta][stage: delta delivering][step: OrderGrids Step]: started
....................................................
[2020-07-15 07:43:52][INFO][mode: delta][stage: volume check][step: OrderGrids Step]: started
100% [============================] Remaining Time: < 1 sec
[2020-07-15 07:43:52][WARNING]: Mismatch of entities in the document: sales_order_grid Source: 13457 Destination: 12744
[2020-07-15 07:43:52][WARNING]: Volume Check failed
[2020-07-15 07:43:52][INFO][mode: delta][stage: delta delivering][step: SalesIncrement Step]: started
.
[2020-07-15 07:43:52][INFO][mode: delta][stage: volume check][step: SalesIncrement Step]: started
100% [============================] Remaining Time: < 1 sec
[2020-07-15 07:43:52][INFO][mode: delta][stage: delta delivering][step: Inventory Step]: started
[2020-07-15 07:43:52][INFO][mode: delta][stage: volume check][step: Inventory Step]: started
100% [============================] Remaining Time: < 1 sec
[2020-07-15 07:43:52][INFO][mode: delta][stage: volume check][step: Inventory Step]: Migration completed successfully
[2020-07-15 07:43:52][INFO][mode: delta][stage: volume check][step: Inventory Step]: Automatic restart in 5 sec. Use CTRL-C to abort^C

A: Magento wrote;
Magento Delta Migration

All other new or updated entities entered through the Admin panel, such as attributes or CMS pages, are not included in the incremental migration and will not be migrated.

Magento Migration Plan
If migration has started, nothing should be entered from the admin panel.
Maybe you can move the database manually for only cms tables.

A: Your new data coming to M1 store after migration is named Data Changes and can be migrated using Magento migration tool. Refer to this document for details: https://devdocs.magento.com/guides/v2.4/migration/migration-migrate-delta.html.


text:
Q: How to create routes in node js application Iam completely stuck and finally came here in hope of someone helping.Iam creating a node js app and got a sample app using express generator commands.Now I need 3 routes mainly
1.localhost:3000
2.localhost:3000/login
3.localhost:3000/home

For these I created 3 html files and placed these inside public/views folder
Basically on running my app it should take me to main page.where it will have button and onclick it takes me to /login page and on successful credentials,it should take me to /home page.
For login I wrote a rest call but I need to use that
Here I need help
1.How to provide routes from my main app.js(server side) and load these files according to the routes we get.
2.From my html I need to call post call,for which I will use ajax.For this I need to have js file where can I add that?
Hope this is clear

A: In express framework you can do it like this
var express=require("express");
var app=express();
app.get("/login",function(request,response){

     response.sendFile("login.html",root:{"./"});
      });