text:
Q: How to pass a value from loop of JSP page to another JSP page? I have recently started working with JSP and I am trying to pass rollno value from one page to another. However, it is always passing the last row rollno.
Below is my first JSP page from where I'm taking values and also feepay page where I retrieve those values. I have tried appending rollno to URL but that didn't work either.
Please help me with this.
<%
  String id=session.getAttribute("rollno").toString();
  int  idd=Integer.parseInt(id);
%>

      NAME
      ROLL NO
      FEE
      FEE PAID
      FEE PENDING
      PAY FEE

    <% while(resultset.next()){ %>

       <%= resultset.getString(1) %>
       <%= resultset.getString(2) %>	<% String rollno=resultset.getString(2).toString(); %>
      <%= resultset.getString(3) %>
      <%= resultset.getString(4) %>
      <%= resultset.getString(5) %>
      <a href="feepaypage.jsp" onclick="<%= session.setAttribute("rollno",resultset.getString(2)) %>">Pay Fee

    <% } %>

A: 1st : your overwriting the session in  while loop so only you always getting last row value .
2nd : Just pass it like query string get parameter like below
 <a href="feepaypage.jsp?rollno=<%=resultset.getString(2) %>" >Pay Fee

3rd : Access the get parameter like below
<%
String id=request.getParameter("rollno").toString();
int  idd=Integer.parseInt(id);
%>


text:
Q: InnoDB, What would cause: "db1/tableABC contains 6 indexes inside InnoDB, which is different from the number of indexes 5 defined in MySQL" MySQL 5.5.24 .
We have InnoDB tables that grew almost by double (from 50GB to 100GB - file-per-table enabled) in a few weeks due to a project we are working on.
The tables were freshly dumped and restored just before that.
Suddenly I noticed this error in error.log a few weeks ago, it has not reocurred:
"Error "db1/tableABC contains 6 indexes inside InnoDB, which is different from the number of indexes 5 defined in MySQL"
Here is the 'show create table';
*************************** 1. row ***************************
       Table: tableABC
Create Table: CREATE TABLE `tableABC` (
  `UID` bigint(20) NOT NULL AUTO_INCREMENT,
  `VERSION` int(11) NOT NULL DEFAULT '0',
  `IMPORT_PAGE_NUMBER` int(11) NOT NULL DEFAULT '0',
  `MODEL_INTEGRATION_IMPORT_INSTANCE_UID` bigint(20) NOT NULL,
  `MODEL_INTEGRATION_IMPORT_FIELD_MAPPING_UID` bigint(20) DEFAULT NULL,
  `MODEL_INTEGRATION_IMPORT_FIELD_UID` bigint(20) DEFAULT NULL,
  `FIELD_TYPE` int(11) NOT NULL,
  `TICKER_CODE` varchar(12) NOT NULL,
  `FIELD_CODE` varchar(255) NOT NULL,
  `ACCOUNT_NAME` varchar(255) DEFAULT NULL,
  `IMPORT_VALUE` longtext NOT NULL,
  `VALUE_DATE` datetime DEFAULT NULL,
  `IS_HISTORIC` tinyint(4) NOT NULL DEFAULT '1',
  `PERIOD_CODE` varchar(4) DEFAULT NULL,
  `YEAR` char(4) DEFAULT NULL,
  `CONSOLIDATION_PRINCIPLE` varchar(255) DEFAULT 'NA',
  `UNIT_MULTIPLIER` double DEFAULT NULL,
  `CURRENCY_ISO` varchar(3) DEFAULT NULL,
  `LINE_NUMBER` bigint(20) DEFAULT '0',
  `COLUMN_NUMBER` bigint(20) DEFAULT '0',
  `PERIOD_START_DATE` datetime DEFAULT NULL,
  `PERIOD_END_DATE` datetime DEFAULT NULL,
  `PARSE_ERROR` varchar(255) DEFAULT NULL,
  `VALIDATE_ERROR` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`UID`),
  KEY `FK_miii_data_miif_mapping` (`MODEL_INTEGRATION_IMPORT_FIELD_MAPPING_UID`),
  KEY `FK_miii_data_miif` (`MODEL_INTEGRATION_IMPORT_FIELD_UID`),
  KEY `FK_MIIIData_MIIInstance` (`MODEL_INTEGRATION_IMPORT_INSTANCE_UID`,`IMPORT_PAGE_NUMBER`),
  KEY `i_ticker` (`MODEL_INTEGRATION_IMPORT_INSTANCE_UID`,`TICKER_CODE`),
  KEY `TICKER_CODE_INDEX` (`TICKER_CODE`),
  CONSTRAINT `FK_MIIInstanceData_MIIInstance` FOREIGN KEY (`MODEL_INTEGRATION_IMPORT_INSTANCE_UID`) REFERENCES `ModelIntegrationImportInstance` (`UID`),
  CONSTRAINT `FK_miii_data_miif` FOREIGN KEY (`MODEL_INTEGRATION_IMPORT_FIELD_UID`) REFERENCES `ModelIntegrationField` (`UID`),
  CONSTRAINT `FK_miii_data_miif_mapping` FOREIGN KEY (`MODEL_INTEGRATION_IMPORT_FIELD_MAPPING_UID`) REFERENCES `ModelIntegrationImportFieldMapping` (`UID`)
) ENGINE=InnoDB AUTO_INCREMENT=83483107 DEFAULT CHARSET=latin1

Any ideas?
Do I need to rebuild the indexes? Would running mysqlcheck -a (analyze table) or mysqlcheck -o (optimize/alter table on innodb) or both do this?

A: You have 6 indexes
  PRIMARY KEY (`UID`),
  KEY `FK_miii_data_miif_mapping` (`MODEL_INTEGRATION_IMPORT_FIELD_MAPPING_UID`),
  KEY `FK_miii_data_miif` (`MODEL_INTEGRATION_IMPORT_FIELD_UID`),
  KEY `FK_MIIIData_MIIInstance` (`MODEL_INTEGRATION_IMPORT_INSTANCE_UID`,`IMPORT_PAGE_NUMBER`),
  KEY `i_ticker` (`MODEL_INTEGRATION_IMPORT_INSTANCE_UID`,`TICKER_CODE`),
  KEY `TICKER_CODE_INDEX` (`TICKER_CODE`),

The PRIMARY KEY is in the gen_clust_index (aka Clustered Index). All secondary index entries include a corresponding PRIMARY KEY entry.
I would mysqldump that table and reload it into a test DB server
Next, I would run CHECKSUM TABLE db1.tableABC; or mysqlchk against db1.tableABC in production and the test DB.
If the checksum values match, you should be OK.
If they do not match or you are not sure, run this on the production server
ALTER TABLE db1.tableABC ENGINE=InnoDB;

This will rebuild the table and its indexes.
If that error ever materializes after this, there may be a data dictionary problem inside ibdata1. Your final solution would be to dump all databases, shutdown mysql, delete ibdata1, ib_logfile0, ib_logfile1, start mysql, reload all data.
I posted this InnoDB Cleanup Process in StackOverflow back on Oct 29, 2010

redpajama_set_name: RedPajamaStackExchange


text:
Q: gerrit admin does not have "Access Database" capability I am trying to access database of my gerrit server with the following command(I am the admin and my username is newbie) -
ssh -p 29418 localhost gerrit gsql
I get the following error :-
fatal: newbie does not have "Access Database" capability.

How to give administrators database access in gerrit ?

A: From the gsql documentation:

Caller must have been granted the Access Database global capability.

Global capabilities are configured in the project.config file, e.g.
[capability]
       accessDatabase = group Administrators


text:
Q: Convert DublinCore To MARC I am trying to convert the following DublinCore XML catalogue:
<?xml version="1.0" encoding="UTF-8"?>
<articlesinDublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">

  <dc:creator>Laura Steinert</dc:creator>
  <dc:creator>Ulrich Hoppe</dc:creator>
  <dc:language>English</dc:language>
  <dc:date>2015-09-16</dc:date>
  <dc:title>Using Network Analytics for the Recommendation of Scientific Papers
  </dc:title>
  <dc:format>PDF</dc:format>
  <dc:publisher>Springer</dc:publisher>
  <dc:type>Text</dc:type>

<dc:contributor>Nicholas Baloian</dc:contributor>
<dc:contributor>Yasser Zorian</dc:contributor>
  <dc:language>English</dc:language>
  <dc:date>2015-09-16</dc:date>
  <dc:title>Collaboration and Technology</dc:title>
  <dc:format>PDF</dc:format>
  <dc:publisher>Springer</dc:publisher>
  <dc:type>Collection</dc:type>

</articlesinDublinCore>

to a MARC catalogue using the official XLST file as follows:

<xsl:template match="/">
    <record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.loc.gov/MARC21/slim
        http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"  >
        <datafield tag="042" ind1=" " ind2=" ">
            <subfield code="a">dc</subfield>
        </datafield>

        <xsl:for-each select="//dc:contributor">
            <datafield tag="720" ind1="0" ind2="0">
                <subfield code="a">
                    <xsl:value-of select="."/>
                </subfield>
                <subfield code="e">collaborator</subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:coverage">
            <datafield tag="500" ind1=" " ind2=" ">
                <subfield code="a">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:creator">
            <datafield tag="720" ind1=" " ind2=" ">
                <subfield code="a">
                    <xsl:value-of select="."/>
                </subfield>
                <subfield code="e">author</subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:date">
            <datafield tag="260" ind1=" " ind2=" ">
                <subfield code="c">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:description">
            <datafield tag="520" ind1=" " ind2=" ">
                <subfield code="a">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:format">
            <datafield tag="856" ind1=" " ind2=" ">
                <subfield code="q">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:identifier">
            <datafield tag="024" ind1="8" ind2=" ">
                <subfield code="a">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:language">
            <datafield tag="546" ind1=" " ind2=" ">
                <subfield code="a">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:publisher">
            <datafield tag="260" ind1=" " ind2=" ">
                <subfield code="b">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:relation">
            <datafield tag="787" ind1="0" ind2=" ">
                <subfield code="n">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:rights">
            <datafield tag="540" ind1=" " ind2=" ">
                <subfield code="a">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:source">
            <datafield tag="786" ind1="0" ind2=" ">
                <subfield code="n">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:subject">
            <datafield tag="653" ind1=" " ind2=" ">
                <subfield code="a">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:title[1]">
            <datafield tag="245" ind1="0" ind2="0">
                <subfield code="a">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:title[position()>1]">
            <datafield tag="246" ind1="3" ind2="3">
                <subfield code="a">
                    <xsl:value-of select="."/>
                </subfield>
            </datafield>
        </xsl:for-each>

        <xsl:for-each select="//dc:type">
            <datafield tag="655" ind1="7" ind2=" ">
                <subfield code="a">
                    <xsl:value-of select="."/>
                </subfield>
                <subfield code="2">local</subfield>
            </datafield>
        </xsl:for-each>
    </record>
</xsl:template>

The resulting converted file is accumulating all the elements in two articles into one single record as follows (I am quoting just a part of it) :
<?xml version="1.0" encoding="utf-8"?>
<record xmlns="http://www.loc.gov/MARC21/slim"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim              http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd">
<datafield tag="042" ind1=" " ind2=" ">
<subfield code="a">dc</subfield>
</datafield>
<datafield tag="720" ind1="0" ind2="0">
  <subfield code="a">Nicholas Baloian</subfield>
  <subfield code="e">collaborator</subfield>
</datafield>
<datafield tag="720" ind1="0" ind2="0">
  <subfield code="a">Yasser Zorian</subfield>
  <subfield code="e">collaborator</subfield>
</datafield>
</record>

However, what I need is to to convert the collection of  elements in DoublineCore into a collection of  elements in MARC format. Does anybody have an idea how can I edit the XPATH expression in XLST file (second block of code) to get my desired result?
Thanks in advance.


text:
Q: Getting the value of a dropdown menu using jQuery I have added a little drop down menu to a webpage:
function addDropDownMenu() {
        var positionMenu = $(
            "<form class='drop_down_menu'>" +
                "<select name='roles'>" +
                    "<option value='notSelected'>Not Selected</option>"+
                    "<option value='relevant'>Relevant</option>"+
                    "<option value='notRelevant'>Not Relevant</option>" +
                "</select>" +
            "</form>");

        $('#profile-experience .position').prepend(positionMenu)
    }

I am trying to get the value of either Relevant or Not Relevant.
However, when I run this code I keep getting an empty string.
var x = $('.drop_down_menu')[0]
// x is the form
$(x).val()

returns ""
What am I missing? Doing wrong?

A: You could try this:
var selectedValue = $('.drop_down_menu>select').val();

var selectedValue = $('.drop_down_menu>select').val();
console.log('The selected value is: '+ selectedValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='drop_down_menu'>
  <select name='roles'>
  <option value='notSelected'>Not Selected</option>
  <option value='relevant' selected>Relevant</option>
  <option value='notRelevant'>Not Relevant</option>
  </select>
</form>

A: $('.drop_down_menu') statement returns a jquery element with the properties and methods corresponding to it, but $('.drop_down_menu')[0] just returns the HTML DOM element.
You have to use value property in order to obtain the value of select element.

console.log($('select')[0].value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='roles'>
  <option value='notSelected'>Not Selected</option>
  <option value='relevant' selected>Relevant</option>
  <option value='notRelevant'>Not Relevant</option>
  </select>

Your example does not work because you have to use a selector for select element

var x = $('.drop_down_menu > select')[0]
console.log($(x).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='drop_down_menu'>
          <select name='roles'>
              <option value='notSelected'>Not Selected</option>
              <option value='relevant' selected>Relevant</option>
              <option value='notRelevant'>Not Relevant</option>
          </select>
</form>

A: var _val = $("[name='roles']").val();
console.log(_val);


text:
Q: to find basis of homomorphism Compute $Hom(V,W)$ and also determine its dimension over $F$ where $V$ and $W$ are vector spaces over the Field $F$
given that $V=\mathbb R^2, W=\mathbb R^2, F=\mathbb R$
I have done this:
$V=\{v1=(1,0) , v2 = (0,1)\}, W=\{w1=(1,0) , w2 = (0,1)\}$
$V= a(v1)+b(v2)$ where $a,b$ belongs to $F$
then $a(v1)+b(v2) = (x,y)$
implies  $a=x , b =y$.
Now, we need to calculate $T11 ,T12 , T21 ,T22$.
So, $T11(V) = a(w1)=x(1,0)$
similarly, $T12 =a(w2),
T21=b(w1),
T22=b(w2)$.
Is this correct? If not, please help.

A: Hint (building on the comment of Arpit Kansal):
given vector spaces $\mathcal V,\mathcal W$ over a field $F$ with $\dim(\mathcal V)=n,\dim(\mathcal W)=m$ there exists an isomorphism $\operatorname{Hom}(\mathcal V,\mathcal W)\rightarrow F^{m\times n}$. The proof for this relies basically on the fact, that every linear map $\varphi:\mathcal V\rightarrow\mathcal W$ can be identified with a matrix (you can also check out wikipedia for more information on that).


text:
Q: Cannot resolve method 'format (java.lang.string,java.Util.Date)' I get this error:

I am new in android App development. Can any one help me?

A: you have to call the the method through object. It is not a static method.
android.text.format.DateFormat df = new android.text.format.DateFormat();
dateTextView.setText(df.format("dd/MM/yyyy hh:mm:ss", date).toString());

A: Make sure you have the imports:
import java.util.Date;
import android.text.format.DateFormat;

If this fails you may miss some library files or have your Android SDK setup messed up. Maybe you should put more information and be more specific to avoid getting more downvotes.
Greetings!


text:
Q: Codeigniter session flashdata and ajax I'm using codeigniter flashdata to set messages after a redirect. Well if I'm using it without ajax, everything just works fine. If I echo out messages received with flashdata it still works like it should BUT if I refresh with F5 once, I still see that message. Flashdata gets cleared after the second refresh... How can I resolve this?
This is, what my function looks like:
public static function message()
{
    if ( ! empty(self::$message['message']))
    {
        // build message
        $message = '
<button type="button" class="close" data-dismiss="alert">×</button>' . self::$message['heading'] . '' . self::$message['message'] . '
';

        // clear static message array
        self::$message = array();

        // return static message
        return $message;
    }
    else
    {
        if ( class_exists('CI_Session'))
        {
            // get flash message
            $message = self::$CI->session->flashdata('message');

            // clear flash data
            self::$CI->session->set_flashdata('message', null);

            // process flash message
            if ( ! empty($message))
            {
                // slice flashdata into single parts
                $message = explode('::', $message);

                // return flash message
                return '
<button type="button" class="close" data-dismiss="alert">×</button>' . $message[1] . '' . $message[2] . '
';
            }
        }
    }

    return '';
}

A: Form the CI Manual:

If you find that you need to preserve a flashdata variable through an additional request, you can do so using the keep_flashdata() function.
$this->session->keep_flashdata('item');

So you need to modify your AJAX handling method to keep the items you need.


text:
Q: jqGrid with no data - how to set a more prominent 'no data' message? By default, when having no data, jqGrid displays the message 'No records to view' inside a pager. (My grids use the top pager).
The problem is, the message is easy to miss.
I'd like to make the grid display the message below the top header, in the same place where the rows would show up if there was any data. (in the body layer, as defined in the documentation).
Alternatively, though less desirable, I'd be fine with leaving the message where it is, but showing it in a big, fat, red font-face.
The message has css class ui-paging-info applied, but I can't just update that because the sae class is also used for displaying the message 'X records found', when the datasource is not empty, and I don't want that to be big and red :).
From what I've seen in the jqGrid source, the message is set in the function updatepager.
[...]
pgboxes = ts.p.pager || "";
pgboxes += ts.p.toppager ?  (pgboxes ? "," + ts.p.toppager : ts.p.toppager) : "";
[...]
if(pgboxes) {
    [...]
    if (ts.p.viewrecords){
        if(ts.p.reccount === 0) {
            $(".ui-paging-info",pgboxes).html(ts.p.emptyrecords);
        }
        else [...]

I'm guessing that's where I should be injecting some custom logic, but I'm not sure how to do that.
I could just hack the jqGrid source, but I'd rather not -> that would be painful for future jqGrid upgrades.

A: I described in the old answer and this one a way how one can implement your requirements.
The demo uses the current 4.6.0 version of jqGrid and displays

In case of some data need be displayed the grid looks like on another demo

If I correctly understand your question the demos should do what you need.


text:
Q: Client-side Validation in Struts 2 I am new at Java Web. I follow a tutorial about struts 2 at: http://viralpatel.net
I success at create server-side validation, but the client-side do not work. When submit, I notice that a javascript method is not defined. Try viewing source, I see no script is generated.
This is generated HTML source
http://pastebin.com/Lc49jnMs

There is no javascript 'validateForm_customer()' method.
In customer.jsp, I have added validate attrubute:
<s:form action="customer.action" method="post" theme="xhtml" validate="true">

and also added:
 <s:actionerror/>
 <s:fielderror />

and
 <s:head/>

In struts.xml:
<action name="customer" class="mypackage.CustomerAction">
    <result name="success">/success.jsp</result>
    <result name="error">/customer.jsp</result>
</action>

In code, i have extended ActionSupport, and I have CustomerAction-validation.xml file.
Only client-side validation do not work, the server-side validation do work perfectly.
I am using struts 2.1.6. I don't know but the newer vesion also do not work with me. It build success but have some error in dispatcher initialize, so when using taglib "struts-tags", it throw an error
The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. - [unknown location]

caused by
org.apache.struts2.views.gxp.inject.InjectedObjectContainer

class not found!
The struts 2.1.6 seems work good until i try using validation.
What did I do wrong?
Thanks and sorry for my bad English

A: Firstly, I strongly recommend you to use the latest version (for obvious security reasons,), which currently is 2.3.1.1
Then remove struts2-gxp-plugin (it looks like you don't need it), after Then see what happens

A: After a long trial i figured out that the validation doesn't works on welcome page set in the web.xml file, so some redirect must be carried out inside welcome page and redirect it internally to next page. And this redirect is not noticed by the user. Below is a sample code of my workings.
index.jsp
<!--importing jslt library to redirect the page (jar required jstl.jar and standard.jar)  -->
<%@ taglib prefix="j"  uri="http://java.sun.com/jsp/jstl/core" %>

<!--redirection the index page to some action named index see strut.xml file  -->
<j:set var="baseUrl" scope="session" value="http://127.0.0.1:8080/strutsBasic/"/>
<j:redirect url="index" />

struts.xml
<struts>

<constant name="struts.enable.DynamicMethodInvocation"
    value="false" />
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources"
    value="ApplicationResources" />

<package name="default" extends="struts-default" namespace="/">
    <!-- at this point redirect is mapped to login page -->
    <action name="index">
    <result>/login.jsp</result>
    </action>

    <action name="login"
        class="com.pkg.action.LoginAction" method="execute">
        <result name="success">/regform.jsp</result>
        <result name="error">/login.jsp</result>
    </action>

<action name="register"
        class="com.pkg.action.LoginAction" method="register">
        <result name="success1">success.jsp</result>
        <result name="input">regform.jsp</result>
    </action>

</package>

and the rest of the code and validation are same as of @Viral Patel

A: Struts tags are only usable when the request has passed through its servlet filter It seems you missed filter mappings in web.xml for the tags you defined. Make sure they are there.


text:
Q: How to use .env with ES6 module with node js and express application? I need your help on how I can use .env file on this application. here is my problem: I am building an app using ES6 module in my node express app. I am facing a problem while storing my variable in .env file, both these two ways below are giving this error : MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string. did not connect. But when I only use the plain string connect is working, that means that I am not using the dotenv file correctly:
1-
import {} from "dotenv/config.js";
import express from "express";
import mongoose from "mongoose";
import cors from "cors";

const app=express()
...
//DB config
mongoose.connect(process.env.CONNECTION_URL,
    {
      useCreateIndex: true,
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })

app.listen(port,()=>console.log(`server on ${port}`)

2-
import dotenv from "dotenv";
import express from "express";
import mongoose from "mongoose";
import cors from "cors";

dotenv.config();

const app=express()
...
//DB config
mongoose.connect(process.env.CONNECTION_URL,
    {
      useCreateIndex: true,
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })

app.listen(port,()=>console.log(`server on ${port}`)

A: Here is how to use it as ES6 module
import * as dotenv from 'dotenv';
dotenv.config();

A: If you don't need the return value from the dotenv.config() function, you can use this pattern to execute the config function as a side-effect of the import:
import 'dotenv/config';

I recommend this syntax because it improves compatibility with Typescript compilers that are strict about the ESM spec (i.e. SWC) and also provides better compatibility with code-formatting rules that want to re-order your import statements.

A: Path is default to ./root/.
To add path to current directory (Dir), we need this code inside of the file that we want all variables to be imported
import dotenv from 'dotenv'
import path from 'path'

import {fileURLToPath} from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config({ path: path.join(__dirname, '.env') });
// const express = require('express')
import express from 'express';

server.js and .env can should be in the same directory if you don't manipulate the path.join(__dirname.
You can reach the variables process.env.myvariable. Just be sure it works and print all variables: console.log(process.env)
Thanks

A: You are right, you are not fetching the env variables.
I'll tell you how I do it. Just create a .env file with your variables.
Then in your app.js:
const dotenv = require('dotenv');
dotenv.config();

And to use the variable uri you have in the .env
const foo = process.env.uri


text:
Q: delay() or timeout with stop()? $('.file a').live('mouseenter', function() {
    $('#download').stop(true, true).fadeIn('fast');
}).live('mouseleave', function() {
    $('#download').stop(true, true).fadeOut('fast');
});

I want the mouseenter function to have a stop() and a delay of 1 second.
So, if I hover over #download the fadeIn should start after a 1 second delay. If I mouse out meanwhile the fadeIn shouldn't start. Get me?
I don't really know how to do that, any ideas?

A: I was looking for the answer to a similar question, and I found that .animate() could also be used to handle this, and it obeys .stop()
It would look something like this:
$('.file a').live('mouseenter', function() {
    $('#download')
        .stop(true, true)
        .animate({opacity:0}, 1000);            // one second delay
        .animate({opacity:1}, 'fast', 'swing');
}).live('mouseleave', function() {
    $('#download')
        .stop(true, true)
        .animate({opacity:0}, 'slow', 'swing');
});

A: Use a setTimeout function
$('.file a').live('mouseenter', function() {
setTimeout(function(){
    $('#download').stop(true, true).fadeIn('fast');
}, 1000);
}).live('mouseleave', function() {
    $('#download').stop(true, true).fadeOut('fast');
});

setTimeout will execute the code inside the function after the specified miliseconds (in this case 1000).

A: You need to use setTimeout() in this case because of how .delay() works (and your inability to cancel it).
$('.file a').live('mouseenter', function() {
  $.data(this, 'timer', setTimeout(function() {
      $('#download').stop(true, true).fadeIn('fast');
  }, 1000));
}).live('mouseleave', function() {
  clearTimeout($.data(this, 'timer'));
  $('#download').stop(true, true).fadeOut('fast');
});

You can give it a try here.
If you use .delay() it'll dequeue the next animation for the element, regardless of if you cleared that queue earlier.  So you need a timeout that you can cancel, which the above does by manually calling setTimeout() and storing the result with $.data() so you can clear it later, via clearTimeout().

A: you can use this on jquery without using delay event .
$('.file a').hover(function() {
  time = setTimeout(function() {
     $('#download').fadeIn();
  },1000);
},function(){
    clearTimeout(time);
});

1000 is your time that after it $('#download') will fade in .


text:
Q: null id generated for:class com.jpa.project.model.domain.Item Id not generating, how to generate?
@Id
@GenericGenerator(name = "ID_GENERATOR", strategy = "com.ItemIdGenerator")
@GeneratedValue(generator = "ID_GENERATOR")
protected Long id;

ItemIdGenerator
public class ItemIdGenerator implements IdentifierGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object object)
            throws HibernateException {
        String prefix = "item_";
        String generatedId = null;

        Connection connection = sharedSessionContractImplementor.connection();

        try {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement
                    .executeQuery("Select count(id) as id from com.jpa.project.model.domain.Item");
            if (resultSet.next()) {
                int id = resultSet.getInt(1) + 999;
                generatedId = (prefix + String.valueOf(id)).toString();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return generatedId;

    }

}

Exception
FAILED: createTest
javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: null id generated for:class com.jpa.project.model.domain.Item
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:769)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:742)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:747)
    at com.jpa.project.model.domain.test.ItemTest.createTest(ItemTest.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:643)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1128)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
    at org.testng.TestRunner.privateRun(TestRunner.java:782)
    at org.testng.TestRunner.run(TestRunner.java:632)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
    at org.testng.SuiteRunner.run(SuiteRunner.java:268)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1244)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1169)
    at org.testng.TestNG.run(TestNG.java:1064)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
Caused by: org.hibernate.id.IdentifierGenerationException: null id generated for:class com.jpa.project.model.domain.Item
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:762)
    ... 27 more


text:
Q: jQuery Cycle Multiple Slideshows In Succession, Initial Delay? I have a banner with a grid featuring 8 slideshows that I would like to run in succession.
I've got everything working, but for some reason there is a long delay before the first transition starts that I can not figure out.
Here's what i've tried thus far
$(document).ready(function(){

var $banner = $('.banner');

var sets = [".r1-c1", ".r2-c4", ".r1-c6", ".r2-c2", ".r1-c5", ".r1-c3", ".r2-c6", ".r2-c1"];

for(var i = 0; i < sets.length; i++){
    $banner.find(sets[i]).cycle({
        'delay' : 1000 * i,
        'speed' : '1000',
        'timeout' : '7000'
    })
}
});

Thanks for any help,

A: I fixed the issue by changing the methodology.
Instead of trying to run the slideshows at the same time, relying on delays to have them transition in succession, I set all slideshows to activate manually.
Here's the code I used. It uses a "sets" array of unique selectors which contain the slide sets. The transitions will happen in the order given.
var $banner = $('.banner');
var sets = [".r1-c1", ".r2-c4", ".r1-c6", ".r2-c2", ".r1-c5", ".r1-c3", ".r2-c6", ".r2-c1"];
var current = 0;

// setup slideshows

$.each(sets, function(index,value){
    $banner.find(value).cycle({
        'timeout' : 0,
        'speed' : 1000,
        'skipInitializationCallbacks' : true,
        'after' : onAfter
    });
});

// run after slide transition

function onAfter(){
    $banner.find(sets[current++ % sets.length]).cycle('next');
}

// initiate first slideshow

$banner.find(sets[0]).cycle('next');

A: In your above code you have used '1000' and '7000' for speed and timeout respectively.
You need to use number (like 1000 not '1000'). Maybe it's talking time to translate '1000' and '7000' which result initial delay.
Replace following in above code:
'speed' : '1000',
'timeout' : '7000'

by
'speed' : 1000,
'timeout' : 7000


text:
Q: Set default group to Cache in kohana 3.3 After upgrade Kohana framework from 3.2 to 3.3, Cache ask me to put an default group to it.
config/cache.php
return array(
     'default' => array(                    // Driver group
         'driver'         => 'apc',         // using APC driver
         'default_expire' => 3600,          // life time
      ),
);

Before, I used to do like this without the group name:
Cache::instance()->set('key', 'val');

Now, that sends an Exception: Failed to load Kohana Cache group: file.
But, when I set the name group all woks perfect.
Cache::instance('default')->set('key', 'val');

How can I set now in 3.3 a default group without type it always whatever I want to use it?  Maybe is a new upgrade, but, I checked the new features of kohana 3.3 and I don't see any of that.
Hope you can help me.

A: Alright so, here's the deal. Without the cache group supplied, it defaults to file.  So if you -dare- change that, be my guest.  But just set the static instance in bootstrap.php, answer at the bottom.
-- This is from the base cache class. --
public static $default = 'file';

public static function instance($group = NULL)
{
    // If there is no group supplied
    if ($group === NULL)
    {
        // Use the default setting
        $group = Cache::$default;
    }

So in your bootstrap.php set this, though I would name it to APC in your config:
Cache::$default = 'default';


text:
Q: What will GridsearchCV choose if there are multiple estimators having the same score? I'm using RandomForestClassifier in sklearn, and using GridsearchCV for getting best estimator.
I'm wondering when there are many estimators (from simple one to complex one) having the same scores in GridsearchCV, what will be the resulted estimator out of GridsearchCV? The simplest one? or random one?

A: GridSearchCV does not assess the model complexity (though that would be a neat feature). Neither does it choose among the best models randomly.
Instead, GridSearchCV simply performs an np.argmin() on the stored errors. See the corresponding line in the source code.
Now, according to the NumPy docs,

In case of multiple occurrences of the minimum values, the indices corresponding to the first occurrence are returned.

That is, GridSearchCV will always select the first among the best models.


text:
Q: Value of String Variable Doesn't Change I have downloaded a string representation of a stock value (Via Yahoo finance API). However when I try to assign the the value to a String variable, it retains it's previous value and doesn't change. Here's the code.
public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }

    String result = "Default";

    public void wb_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
    {
        result = e.Result;

        //I changed the application title to be sure the required string was in fact downloaded
        ApplicationTitle.Text = e.Result;
    }

    //When I Click a radio button, the tile is created and inialized
    private void radioButton1_Checked(object sender, RoutedEventArgs e)
    {
        WebClient wb = new WebClient();
        wb.DownloadStringAsync(new Uri("http://finance.yahoo.com/d/quotes.csv?s=GOOG&f=a"));
        wb.DownloadStringCompleted += wb_DownloadStringCompleted;

        //string result = DownloadStringCompletedEventArgs.result;
        int newCount = 0;

        // Application Tile is always the first Tile, even if it is not pinned to Start.
        ShellTile TileToFind = ShellTile.ActiveTiles.First();

        // Application should always be found
        if (TileToFind != null)
        {
            // Set the properties to update for the Application Tile.
            // Empty strings for the text values and URIs will result in the property being cleared.
            StandardTileData NewTileData = new StandardTileData
            {
                Title = "Stocks",
                BackgroundImage = new Uri("google_icon.jpg", UriKind.Relative),
                Count = newCount,
                BackTitle = "Google Stock",
                BackBackgroundImage = new Uri("google_icon.jpg", UriKind.Relative),

                //This is where the problem is. The value of result is still "Default"
                BackContent = result.ToString()
            };

            // Update the Application Tile
            TileToFind.Update(NewTileData);
        }
    }
}

I am trying to display the result in a live tile and it shows the value "Default" instead of the stock value "548.47"

A: You need to update your live tiles after the download has finished - in other words, from within the wb_DownloadStringCompleted handler.
public void wb_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
{
    //this can probably be a local variable
    result = e.Result;

    //update live tile here.
}

Your current code is launching an async task and then update the tile right away. Because the task hasn't finished yet, result is still set to the default value.


text:
Q: Are there any changes or additions to NTFS in Windows 8? With Vista came a number of improvements like self healing and symbolic links. Even though these might be OS improvements, they're functionally file system changes.
For Windows 8 have there been any such changes?

A: There have been various changes made to the chkdsk and NTFS health model. Here's an overview:

*

*Online self-healing: The NTFS self-healing feature was introduced in Windows Vista (and in Windows Server 2008) to reduce the need to run chkdsk. Self-healing is a feature built into NTFS that fixes certain classes of corruptions encountered during normal operation, and can make these fixes while still online. In Windows 8 the number of issues that can be handled online has been increased and this has reduced any further need for chkdsk.

*Online verification: Some corruptions are intermittent due to memory issues and may not be a result of an actual corruption on the disk; so a new service to Windows 8 has been added, called the spot verification service. It is triggered by the file system driver and it verifies that there is actual corruption on the disk before moving the file system along in the health model. This new service runs in the background and does not affect the normal functioning of the system; it does nothing unless the file system driver triggers it to verify a corruption.

*Online identification and logging: When an issue is verified, this triggers an online scan of the file system, which runs as a maintenance task in the file system. In Windows 8, scheduled tasks that are for the maintenance of the computer run only when appropriate (during idle time, etc.). This scan can run as a background task while other programs continue to run in the foreground. As the file system is scanned, all issues that are found are logged for later correction.

*Precise and rapid correction: At the user or administrator's convenience, the volume can be taken offline, and the corruptions logged in the previous step can be fixed. The downtime from this operation, called "Spotfix," takes only seconds, and on Windows Server 8 systems with cluster shared volumes, this downtime has been eliminated completely. With this new model, chkdsk offline run time is now directly proportional to the number of corruptions, rather than being proportional to the number of files as in the old model.
There have been various other changes made to implement better manageability as well, and the new file system health model basically works like this:

Check the Source for more details, 'cos otherwise it's just gonna end up as a complete copy-paste job, and with articles like these it's really difficult to reword everything.

A:
The NTFS.sys version (i.e. NTFS v5.0 introduced with Windows 2000)
  should not be confused with the on-disk NTFS format version (v3.1
  since Windows XP).[12] The NTFS v3.1 on-disk format is unchanged from
  the introduction of Windows XP and is used in Windows Server 2003,
  Windows Server 2008, Windows Vista, and Windows 7. The confusion
  arises when no differentiation is made when features are implemented
  into the NTFS.sys driver within the Windows OS rather than in the NTFS
  on-disk format. An incident of this was when Microsoft detailed new
  features within NTFS in Windows 2000 and they called it NTFS v5.0, yet
  it is the NTFS.sys driver that is at that version and the on-disk
  format is only at v3.0.[9]

http://en.wikipedia.org/wiki/NTFS#Versions

A: I'm sorry I'm not in a position to provide a precise answer to this question, but I'm getting a very strong feeling that the way Win 8 sees an NTFS volume is different to how Win 7 sees the same volume.
I wish there was something official from MS but I haven't seen anything yet.
From personal experience, I have noticed on a number of occasions, if I mount Windows 8 disks/partitions under Windows 7 to carry out e.g. an offline malware scan (sometimes requiring file permissions to be modified to gain access), Windows 8 then finds issues with the file system on the partition when it mounts/accesses it again. Why is this? I have seen a number of similar reports from users dual booting Windows 8 with Win7 or Linux.
I was previously led to believe it only happened with OS volumes using the new Win 8 fast boot feature, but today I saw it happen with a data drive. Previously in use with Win 8, after connecting it to a Win 7 machine, Win 7 said while booting that the volume needed to be checked for consistency. Fearing data loss from others' experiences, I skipped the scan and let Win 7 boot with it still attached. I was able to make a backup of all files and then proceeded to run a disk check from within Win 7. Oddly, it reported no issues. I rebooted just in case and still no issues were now flagged. So either Win 7 did some kind of spot fix itself while booted, or there's something else odd going on.


text:
Q: Generate rows before and after selected row from jsonb column I want to ask for help because I can't solve this problem.
I have this result which is correct. But it is the result of real physical data that are in the table.
SELECT row_number() OVER (ORDER BY PR."Priority") AS "LOS", "SpeedLessThan", "SpeedAtLeast"
 FROM "ProjectRules" PR
 WHERE PR."ProjectId" = 500
   AND PR."Group" = 1;

Well, the problem is, now I have a different structure where the physical line is JSON. And the result of this query is this.
SELECT row_number() OVER (ORDER BY MQ."Id") AS "LOS", "LevelOfServiceConfig"
 FROM "ProjectMqs" MQ
 WHERE MQ."ProjectId" = 500 AND "Id" = 1;

I need to generate a result that will be exactly the same as the result above. So this one row is split into 3 rows and its value is either less to zero or more to 999.
SELECT "Id" as "LOS", "LevelOfServiceConfig" ->> 'Danger' AS "Danger", "LevelOfServiceConfig" ->> 'TrafficJam' AS "TrafficJam"
FROM "ProjectMqs"
WHERE "ProjectId" = 500
  AND NULLIF(regexp_replace("Name", '\D','','g'), '')::numeric = 1;

I don't know what to do with this query to get the result.

A: You already know how to create one row, just use UNION ALL or a similar construct to create the three rows:
SELECT ROW_NUMBER() OVER (ORDER BY v.SpeedAtLeast) AS LOS, v.*
FROM t
CROSS JOIN LATERAL (VALUES
    (999, (t.LevelOfServiceConfig->>'Danger')::int),
    ((t.LevelOfServiceConfig->>'Danger')::int, (t.LevelOfServiceConfig->>'TrafficJam')::int),
    ((t.LevelOfServiceConfig->>'TrafficJam')::int, 0)
) AS v(SpeedLessThan, SpeedAtLeast)
ORDER BY LOS


text:
Q: localmedia access restricted until user interacts with the page in firefox I have given allow permission for Microphone in my domain. We are using our domain in multiple tabs. I am able to acquire local media (Microphone) when I am accessing in the same tab. But I am not able to acquire local media for WebRTC in the other tab(same domain) without visiting the tab .Only after visiting the tab localmedia access is acquired.
Is it intentionally done for Security & Privacy? . Is there any way to solve my problem ?
Reason: To restrict resources being used for WebRTC session. We are keeping WebRTC session in single tab for our domain and using only that resource for all the tabs to make calls.
Tried setting microphone-allow as iframe attribute . But it didnt solve the problem . It is working fine in GoogleChrome browser though. If I open a new tab(T1) and initiate webrtc in it and make webrtc call from another tab (T2)without ever visiting the  tab T1 , call is connected in chrome but not in firefox unless i visit T1 .
Note : It is not asking permission for allowing  microphone in the domain , it acquires it automatically . Just that it acquires only after i visit the tab .I have given microphone access permission to my domain already.

A:
Is it intentionally done for Security & Privacy?

Yes, this is intentional to prevent background tabs from turning on the camera or mic willy nilly, to spy on users. Because that's creepy. I believe Safari works the same way.
The getUsermedia specification recently made this a requirement:

*

*Step 6.1. "The User Agent MUST wait to proceed to the next step until the current settings object's responsible document is fully active and has focus."*

So I would expect Chrome to follow suit soon.

Is there any way to solve my problem ?

That would very much defeat the assurance.
Users can rest assured that only the currently focused tab can turn on the camera or microphone.

If I open a new tab(T1) and initiate webrtc in it and make webrtc call from another tab (T2)without ever visiting the tab T1 , call is connected in chrome but not in firefox unless i visit T1.

That's an RTCPeerConnection connection problem, which is separate from getUserMedia.
The workaround is to not block connection establishment on mic access.
There's no reason you can't connect first and add the mic later.
Or get mic ahead of time, and connect later. Basically, the two actions don't need to coincide or block each other.


text:
Q: Blocking IO call in Vue When I click on a button, it stays "clicked" until the executed method finishes.
<button :disabled="!query.length" @click="callExternal">Check</button>

methods: {
    callExternal() {
        var request = require("request-promise");
        var options = {
            method: 'GET',
            url: `https://external.url/${this.query}`,
            json: true,
            headers: {
                'content-type': 'application/json',
                'Authorization': 'Bearer xyv'
            }
        };

        request(options).then(response => {
            console.log(response);
            this.country = response;
            this.error = false;
        }).catch(err => {
            this.country = '';
            this.error = true;
        })
    }
}

I tried the same with axios, but have problems with CORS. With request and request-promise it works. (No clue why!)
What should I do, that the button immediately switch back and don't "freeze"?
Do I have to use async / await?


text:
Q: C# Label in Button I have created a button with below code.There is a label created on the bottom left corner of the button.The code works fine but the button has no response when the user clicks on the label, please help.
Custom Button:
public class CustomButton : System.Windows.Forms.Button
{
    private System.Windows.Forms.Label lb = new System.Windows.Forms.Label();
    public CustomButton(){
        this.Width = 120;
        this.Height = 65;
        this.Font = new System.Drawing.Font(this.Font.FontFamily, 24);
        lb = new System.Windows.Forms.Label();
        lb.Font = new System.Drawing.Font(lb.Font.FontFamily, 9);
        lb.Location = new System.Drawing.Point(4,35);
        lb.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
        lb.BackColor = System.Drawing.Color.Transparent;
        lb.Width = 70;
        this.Controls.Add(lb);
    }

    public System.Windows.Forms.Label getLb()
    {
        return lb;
    }

    public System.Windows.Forms.Button get_btn()
    {
        return this;
    }
}

WinForm:
public CustomButton[,] bt = new CustomButton[13,32];

public FormClient()
{
    bt[0, 0] = new CustomButton();
    bt[0, 0].Click += new EventHandler(button_Click);
}

public void button_Click(object sender, EventArgs e)
{
    //my code//
}

A: You could invoke the onClick event of the button whenever the label is clicked. Therefore I'd modify your custom button like that:
public class CustomButton : System.Windows.Forms.Button
{
    private System.Windows.Forms.Label lb = new System.Windows.Forms.Label ();

    public CustomButton ()
    {
        this.Width = 120;
        this.Height = 65;
        this.Font = new System.Drawing.Font (this.Font.FontFamily, 24);
        lb = new System.Windows.Forms.Label ();
        lb.Font = new System.Drawing.Font (lb.Font.FontFamily, 9);
        lb.Location = new System.Drawing.Point (4, 35);
        lb.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
        lb.BackColor = System.Drawing.Color.Transparent;
        lb.Width = 70;
        lb.Click += (sender, args) => InvokeOnClick (this, args); //Add this line
        this.Controls.Add (lb);
    }

    public System.Windows.Forms.Label getLb ()
    {
        return lb;
    }

    public System.Windows.Forms.Button get_btn ()
    {
        return this;
    }
}

Now everytime the label is clicked, the click event of the button will get fired as well. However, you won't get that nice animation when you hover over your label, therefore you'd have to create a custom label which makes this effect.


text:
Q: Permutation/Combination with license plates Question, with a California license plate, it has #LLL### where L = Alphabet.  I know with the combination is 10^4 * 10^3 for all possible solution.  How about if I excluded a certain word, such as "FSS", where any combination of car license plate would not include the word "FSS".
How do I go upon this? I can still use the letters, but the three can't be together.  Its throwing me for a loop. Do I use permutation to exclude the repetition word?  Any help is appreciated.
EDIT- the # = digits.  So from 0-9, there are ten possibilities, sorry didn't clarify

A: There are only so many ways you can have FSS in a string of seven characters.
FSS####
#FSS###
##FSS##
###FSS#
####FSS

So there are five different license plates with the string FSS in them. If there is no constraint on the four numbers, that means you have 9,999 different license plates for each position of "FSS".
You would want to subtract 9,999 * 5 from you total answer to get the plates allowed.
Edit:
So you want all permutations of 0-9 in the first, fifth, sixth, and seventh positions. And all permutations of A-Z of the second, third and fourth positions, except for F in the second, S in the third and S in the fourth, right? If so, it would be 10*25*25*25*10*10*10, or 10^4 * 25^3. Did I get your problem right?


text:
Q: Disable incoming emails for a specific virtual user I've just setup a mail server with mysql virtual users.
I want to use an account for sending notifications/registrations emails from my website
I found no options for disabling incoming emails, so my first thing is to set the user quota to 0.
Tried to send a mail and I got:
Mar 28 19:24:23 mail postfix/smtpd[4977]: NOQUEUE: reject: RCPT from mail-wg0-f42.google.com[74.125.82.42]: 450 4.7.1 <notifications@mysite.net>: Recipient address rejected: Policy Rejection- Please try later.; from=<someone@gmail.com> to=<notifications@mysite.net> proto=ESMTP helo=<mail-wg0-f42.google.com>
Mar 28 19:24:23 mail postfix/smtpd[4977]: disconnect from mail-wg0-f42.google.com[74.125.82.42]

Seems to work but the message is Policy Rejection- Please try later.
It's the right way to do that ?

A: To reject a specific e-mail address/account do the following:
first have a look at your main.cf
look for

smtpd_recipient_restrictions

add

check_recipient_access hash:/opt/local/etc/postfix/filtered_domains

to the list of options
in my case the configuration parameter would look like the following:

smtpd_recipient_restrictions =
          permit_mynetworks,
          permit_sasl_authenticated,
          reject_unlisted_recipient,
          reject_non_fqdn_recipient,
          reject_unauth_destination,
          reject_unknown_recipient_domain,
          check_recipient_access hash:/etc/postfix/filtered_domains

then edit /etc/postfix/filtered_domains for your needs
for example :

user@myexample.com REJECTanotheruser@virtualdomain.org REJECT

then build the table for postfix

postmap filtered_domains

You are done.
user@myexample.com and anotheruser@virtualdomain.org are now beeing rejected. So there's no need to set the user quota to zero anymore.
As you use MySQL virtual tables it would be easy to change your virtual users table. For example add a flag 'disabled' and change the table format for filtered_domains to mysql, and define the according query which delivers the appropriate email address when the 'disabled' flag is set.


text:
Q: Проблема отображения html кода элемента при парсинге html странице Начал изучать парсинг. Как тестовый проект хочу парсить данные с сайта.
По ссылке на профиль магазина хочу программно получить данные о количестве заказов и отзывов. Думал это легко, но как оказалось нет.
При выполнении кода (Пока что получаю весь html):
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

URL_TEMPLATE = "https://kazanexpress.ru/appleplace"
r = requests.get(URL_TEMPLATE)
print(r.status_code)
print(r.text)

получаю совсем не тот html, что видел в коде элемента, а что-то вроде этого:

<!DOCTYPE html><meta charset=utf-8><meta http-equiv=X-UA-Compatible content="IE=edge"><meta name=viewport content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1"><meta http-equiv=content-language content=ru><meta http-equiv=Cache-control content="no-cache, no-store, must-revalidate"><meta http-equiv=Pragma content=no-cache><meta name=description content="Маркетплейс доступных цен с бесплатной доставкой за 1 день"><meta name=keywords content="маркетплейс, интернет-магазин, доставка на следующий день, низкие цены, купить дешево, быстрая доставка, лучшие цены"><meta id=prerender-status-code name=prerender-status-code content=200><meta id=prerender-header name=prerender-header content=""><title>Выгодные покупки быстрее чем за сутки</title><link rel=icon type=image/png sizes=32x32 href=/static/img/icons/favicon-32.png><link rel=icon type=image/png sizes=16x16 href=/static/img/icons/favicon-16.png><meta name=ROBOTS content="INDEX, FOLLOW"><meta property=og:url content=""><meta property=og:title content=""><meta property=og:description content=""><meta property=og:image itemprop=image content=""><meta property=og:image:secure_url content=""><meta property=og:type content=website><meta property=product:brand content=""><meta property=product:availability content=""><meta property=product:condition content=new><meta property=product:price:amount content=""><meta property=product:retailer_item_id content=""><meta property=product:price:currency content=RUB><link rel=canonical href=https://kazanexpress.ru/ ><link itemprop=thumbnailUrl href=url_image><meta name=twitter:image content=""><meta name=apple-itunes-app content="app-id=1438104323"><meta name=facebook-domain-verification content=rb1tipol8glrbndktmbkyom0xaqomi><meta name=google-site-verification content=ffMsQuJJt9A3n3pN6FcpIKq8UcuWj1gvjMdvqLxEwMI><meta name=google-site-verification content=QrVT-SLKbPGSA5shhmMLeS9ilfJ-V7IoNDb3pxgHvt4><meta name=google-site-verification content=_Jd4DyFIJ-LlvrfYl7nq9VsJGU0Dl-fSewUtb8xFY1M><meta name=google-site-verification content=22lwQj3aZEg4S0p9e0z4t561wEmGC5q1u3yxbu7qAC8><meta name=google-site-verification content=R674rCopA_NzCaJ7A72UfmTkpXBUyudgh0a4u_JznQE><meta name=google-site-verification content=86eWgZxBzwHcvvnNMA8WPOAxjOOesyMvyQBzz3BW3BQ><meta name=mailru-verification content=2be7cbd6459741ed><meta name=yandex-verification content=1737294911c38a7a><meta name=yandex-verification content=c1a636f058f5aae4><meta name=yandex-verification content=12e93a30f6213678><meta name=mailru-verification content=67628f3035f4dc15><meta name=theme-color content=#E53935><meta name=apple-mobile-web-app-capable content=yes><meta name=apple-mobile-web-app-status-bar-style content=white><meta name=apple-mobile-web-app-title content=KazanExpress><link rel=apple-touch-icon href=/static/img/icons/apple-touch-icon.png><link rel=mask-icon href=/static/img/icons/safari-pinned-tab.svg color=#e53935><meta name=msapplication-TileImage content=/static/img/icons/mstile-144x144.png><meta name=msapplication-TileColor content=#FFF><link rel=stylesheet href=/static/css/styleoff.css><link rel=stylesheet href=/static/css/fonts.css><link rel=stylesheet href=/static/css/typebase.css><link rel=stylesheet href=/static/css/helpers.css><app></app>
<svg id=Layer_1 data-name="Layer 1" xmlns=http://www.w3.org/2000/svg viewBox="0 0 76.73 76.88" style="width: 36px;height: 36px;"><defs></defs><title>KazanExpress</title><path class=cls-1 d=M56.06,53.61H47.74L35.36,37.88h0L47.51,23.27h8.31L45.94,35.15H76.73a38.44,38.44,0,1,0,0,6.58h-30Zm-23.12,0H26.36V23.27h6.58V53.61Z></path></svg>
Пожалуйста, включите JavaScript, чтобы воспользоваться сайтом!

<link rel=stylesheet href="https://fonts.googleapis.com/css?family=Roboto:400,500,700&subset=cyrillic" preload>


text:
Q: iOS: Can users read the data stored in Core Data I'm writing an iOS app and want to use Core Data to persist some data locally for performance and UX. I would like to know if what stored in Core Data can be read and accessed by the users. If so, is it possible to make it unreadable for users. Is there a risk to store other users' Firebase user ids in Core Data.
Thanks for considering my question.

A: Data stored in core data is encrypted with device passcode. so technically it can be read by user.
This question related you your question.
https://security.stackexchange.com/questions/147312/is-data-stored-in-core-data-on-ios-secure


text:
Q: Proving double sum $\sum _{a=1}^{\infty }\sum _{b=1}^{\infty }\frac{\left(-1\right)^{a+b}}{\left(a^2+b^2\right)^s} $ I have see this formula in Wolframe Alpha Double series's documentation, but what is the procces of proving?
$$\sum _{a=1}^{\infty }\sum _{b=1}^{\infty }\frac{\left(-1\right)^{a+b}}{\left(a^2+b^2\right)^s}=\eta \left(2s\right)-\eta \left(s\right)\beta \left(s\right)
$$
Where
$$ \beta \left(s\right)=\sum _{n=1}^{\infty }\frac{\left(-1\right)^{n-1}}{\left(2n-1\right)^s}$$
$$\eta \left(s\right)=\sum _{n=1}^{\infty }\frac{\left(-1\right)^{n-1}}{n^s}$$


text:
Q: Local sections of Hopf fibration $(S^3,\pi,S^2)$ In the lecture we showed the local triviality of the Hopf fibration $(S^3,\pi,S^2)$ as a principal-$S^1$-bundle by constructing local sections
$$s_1:S^2\setminus\{\infty\}\cong\mathbb{C}\to S^3,\qquad s_1(z):=\frac{1}{\sqrt{1+\lvert z\rvert^2}}\left(z,1\right)$$ and $$s_2:S^2\setminus\{0\}\to S^3,\qquad s_2(z):=\frac{1}{\sqrt{1+\lvert z\rvert^2}}(\lvert z\rvert,\lvert z\rvert).$$
At least that is what I have written in my notes, but in general $s_2(z)\notin S^3$. So, what is a correct section $s_2$?

A: We want $s_{1}$ and $s_{2}$ to be compatible with each other under "inversion," i.e. $z\mapsto 1/z$, so the right formula for $s_{2}(z)$ would be just $s_{1}(1/z)=\frac{1}{\sqrt{1+|z|^{2}}}(\frac{|z|}{z},|z|)$.


text:
Q: web.xml for jstl I tried codes with jstl. The exception is

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

I am using eclipse. I added jstl.jar and standard.jar. What should I give in web.xml now? I don't know what to give in <taglib>.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<c:forEach var = "userName" items = "${name}">
<tr>
<td>${userName}</td>

 </tr>
 </c:forEach>

</body>
</html>

A: This can happen if you either downloaded the ancient JSTL 1.0 which has a different URI, or you placed the JAR's in the wrong place (i.e. not in /WEB-INF/lib or anywhere in webapp's runtime classpath).
Ensure that you download the right version and put the JAR(s) in /WEB-INF/lib. For a webapplication whose web.xml is declared as Servlet 2.5, you need to download just JSTL 1.2 as jstl-1.2.jar. For a Servlet 2.4 webapplication, you need to download JSTL 1.1 as jstl.jar and standard.jar.
You don't need to extract the JAR's. You also don't need to modify the web.xml as some poor online tutorials suggest. Just drop JAR(s) in runtime classpath, declare the taglib in JSP and that's it.

A: There is no need to make an entry of jstl.jar or standard.jar inside web.xml if the jars are kept in the lib directory inside WEB-INF.
The container by default looks into the lib directory of WEB-INF

A: You shouldn't have to add the taglib elements to web.xml. The standard & jstl jars are interrogated via the service mechanism in the container.
Make sure the jars are exported with the web-app and located under WEB-INF/lib and you should be fine.


text:
Q: c# read pst file and extract .msg file on web application my project is create a web application which used mvc+api architecture
I don't know how to realize this function on web application, which is read the pst files that users uploaded and extract them on the server and return all the .msg files' list to the client
I am totally a beginner on this kind of project, so please help me out, thank you.

A: The [MS-PST]: Outlook Personal Folders (.pst) File Format section in MSDN specifies the Outlook Personal Folders File Format, which provides the necessary technical information required to read and write the contents of a Personal Folders File. Each Personal Folders File represents a Message store that contains an arbitrary hierarchy of Folder objects, which contains Message objects, which can contain Attachment objects. Information about Folder objects, Message objects, and Attachment objects are stored in properties, which collectively contain all of the information about the particular item.
There are third-party libraries available for reading .PST files, but you'll really have to search those yourself and evaluate them according to your criteria. For example - NMapi - C# MAPI Library.

A: If you can control the server environment, you can install Outlook on that machine to have the MAPI system (Microsoft fully supports installing Outlook on a server, but not actually running it as a user or using the Outlook Object Model).  You can then use Extended MAPI (C++ or Delphi) to create a temporary profile and add/configure the "MSUPST MS" MAPI service to access a PST file.
If C++ and Extended MAPI are not an option, you can use Redemption (I am its author) and its RDOSesssion.LogonPstStore method to read the messages inside the PST file.


text:
Q: session variables timeout in asp.net app In my web app I'm using some session variables, which are set when I login:
e.g. Session("user_id") = reader("user_id")
I use this through my app.
When the session variable times out, this throws errors mainly when connecting to the database as session("user_id") is required for some queries.
How can I set my session variables so that once they are timed out to go to the login page or how can at least increase the length of time the are available?

A: I'm guessing you're using Forms Authentication. The trick here is to ensure that your Forms Authentication expires before the session does.
I wrote about this in this answer here:

How to redirect to LogIn page when Session is expired (ASP.NET 3.5 FormsAuthen)

For example:
Configure your Forms Authentication - this sets the timeout to 60 minutes:
<authentication mode="Forms">
    <forms defaultUrl="~/Default.aspx"
        loginUrl="~/Login.aspx"
        slidingExpiration="true"
        timeout="60" />
</authentication>

Extend Session expiry to a longer time:
<sessionState
    mode="InProc"
    cookieless="false"
    timeout="70"/>

In your Login.aspx code behind you could also do a Session.Clear(); to remove stale session data before assigning session values.

A: In the past I've used a base page or master page on every page (making an exception for the login page) that reads a session token to see if a user is logged in currently.
If it ever reads a null it saves the current url and redirects to the login page.
After logging in it reads the saved url and redirects the user back to the requested page.
Increasing the session timeout value is a setting in IIS.

A:
How can I set my session variables so that once they are timed out to go to the login page

Check if they are = null do a Response.Redirect("Home.aspx");

or how can at least increase the
  length of time the are available?

Its in the web.config within the sessionState element

A: I think a lot of people wrap their session calls to provide a "lazy load" pattern.  Something like this:
class SessionHelper
{
    public static string GetUserId()
    {
        string userId = (string)System.Web.HttpContext.Current.Session["UserId"];

        if( userId == null )
        {
           userId = reader("UserId");
           System.Web.HttpContext.Current.Session["UserId"] = userId;
        }

        return userId;
    }
}


text:
Q: Can a single OS installation on an SSD be shared between a desktop and a laptop? I recently purchased an SSD and was wondering if there was an Operating System that allows you to swap between two different machines essentially sharing one partition? Perhaps multiple hardware profiles? In this case the machines are my laptop and desktop.
It would be great to take advantage of the performance of my desktop and then when I need to be mobile just put the SSD into my laptop and go. I don't believe Windows plays nice with this concept for reason of licensing, i.e. major hardware changes triggering reactivation, etc.
Denser, faster, more affordable, and smaller storage could make this a viable option for end users without relying on "cloud" technologies for syncing apps and files. I prefer to have literal, physical control over my information.

A: Most standard Linux distros will allow you to do this - provided they are the same architecture (eg Both are Intel 32bit or 64bit machines).
Linux typically packs all the common drivers you might need as modules as part of the intitial boot process, and there is no "system lock in" to check if the hardware is the same as previous boots.
I have, on multiple occassions, pulled drives out of 1 system, plugged them into another and everything just worked.   In fairness, I do try and keep my hardware fairly standard (intel chipset motherboards with intel CPU) which makes it that much simpler, but certainly this can work on more diverse hardware.
My distro of choice is Ubuntu, but I'm confident Redhat based installs will do the same thing - anything where you don't need to compile a custom kernel should work.

A: You could run a live Linux iso like Linux Mint, Ubuntu, Debian, or Knoppix (it's more like a live-dvd-only and says "Knoppix is not a Linux distribution like for example Debian, openSUSE, Ubuntu or others", but has many "install" options), there are many others that can run live also, most with persistence to save changes.
Copying one of their iso's onto your SSD drive and using grub to launch it (similar to instructions here) should work, if you have unusual hardware that isn't detected properly in a "regular" Linux install as DrMoishePippik's answer suggests.

A: Of the several reasons this cannot work with Windows that come to mind, the most pressing and impossible to work around is Windows Product Activation.

*

*Every time you move your Windows installation to new hardware you will trigger product activation.

*Very soon you will run out of grace re-activations and have to call Microsoft to get your product key reactivated.

*And very soon after that you'll be told you've reached the end of the road.

A: FreeBSD does this pretty easily, but since you have Windows & Windows-only apps, that's probably moot. I think the first thing to discover is if your OS is really hitting the disk. Mine doesn't--the apps do. So, install them onto an NTFS SSD if you can (depending on how they store stuff). You could even redirect your user folder to it for settings/data.

A: I actually do this quite frequently when travelling using:

*

*a Samsung 840 pro 250 GB SSD

swapped between

*

*Mac Pro 3.1 (2008) running OSX version 10.9 (Mavericks)

*Macbook Pro 2010

To accommodate the 2.5" HDD in the 3.5" Mac Pro drive bays I use a Icy Dock EZConvert 2.5-Inch to 3.5-Inch SATA SSD / Hard Drive Converter.  It pulls out within seconds (after powering off the Mac Pro of course) and the SSD slides out of the Icy Dock housing without screws or other attachments.
The swap takes ~5 minutes - the slowest part is removing / reinstalling the screws from the back of the Macbook Pro to get at the SSD.
Since the SSD used in the desktop + laptop is the boot drive, it contains the OS - the only inconvenience I've encountered is having to re-enter all my iTunes, messaging/FaceTime and some email passwords each time the drive changes hardware.
The issue you may have to replicate this with more modern machines is that the SSDs in the latest Apple laptops are not removable.  On a positive note, the older gear I'm describing is rather cheap  these days.
The reason I unfortunately have to do this is because I've set up a local LAMP server on which i've built all my sites, apps, version control and databases.  Having a local LAMP on the drive also means I can work without interruption while travelling in places without a reliable (and/or secure) network.
While version control could make it possible to switch between machines without swapping drives, all the uncommitted changes are not present on the cloud - as well as differences in database structure and data.  I'm still hoping for a day when hand-off between machines is as painless as checking your email in the cloud.

A: It sounds like author of the question requires Windows.  The only legal solution I know of that allows you to use the same Windows installation on different hardware is Windows to Go.
However, Windows to Go is only available for Windows 8 Enterprise, which isn't available to normal consumers.

A: I have, several times, moved a hard disk installation of Ubuntu from one computer to another, and it just worked. It even worked when i moved from an Intel processor to AMD, and, just yesterday, i removed my Nvidia card from one computer and enabled the on-board Intel VGA, and the OS including GUI started just like nothing had happened at all. So unless you have some very special hardware requirements, Ubuntu should just work fine for you.
Personally, i prefer XUbuntu, especially on my (6 year old) laptop, since it has lower hardware requirements, but it doesn't really make a difference if both your computers are quite new.
Since you need some windows Software as well, i'd just recommend installing VirtualBox on your Ubuntu installation, and installing Windows as a VM within Virtualbox. This should take care of all "Hardware A is different from Hardware B" issues nicely. (Last month, i moved a Windows Server 2008 Virtual Machine from an AMD Host running Windows 7 to an Intel Host running Ubuntu, again without Windows reconfiguring anything, so you shouldn't have any problems there either). I'm no expert on the Windows EULA and its enforcability in various jurisdictions, but as this leaves you with one installation that can never be run on more than one computer, you'll probably be fine.
You might have some problems if you're planning to run 3d-intense games within your Windows VM, but everything else should run fine there.

A: It depends on which OS you are using, Linux based OS'es have no trouble whit this, unless the new hardware configuration have a device with no drivers available, specially with the GPU (At least on the already installed OS). I have a USB hard drive with an emergency Ubuntu installed on it and most of the computers I've plugged it booted successfully, the ones who didn't was because of resources limitation (RAM, CPU and so).
With Windows is another story, Vista and earlier versions installs can be moved to another hardware configuration only if the platform is the same (AMD x86, AMD64, Intel x86_64) but sometimes it can trigger the "Pending activation" state (I used to move my HDD from Laptop to another and this happened only once), and you could have trouble reactivating the licence. If Windows can find the drivers it will install them automatically, if not you will have to install them but just one time.
If you're using Mac OS (Say, a Macbook Pro and a Mac Mini) this can be done fairly easy, if both PC's support the installed OS version, you will need to press the alt key when the computer turns on for the first time you move the SSD, but after that it will boot directly.

A: If the drive isn't the primary boot drive, this works much better. Some laptops can take two hard disks, possibly at the cost of removing the optical drive. You can then use the SSD for only the speed-critical applications and data.
(You can move the entire profile at the cost of more hassle: https://serverfault.com/questions/8187/whats-the-best-way-to-move-c-users-to-d-users-under-vista-w7 )

A: If you bought a laptop it seems likely it has a windows license attached to it. If your desktop also has one, why not try to install Windows twice on the same ssd in a dual boot configuration? If it works then you will just boot to the appropriate install. You could even make a third partition just for data so you don't have to hunt around as much for files you are working on.
The only problem I see with a virtualbox type solution is you will lose 3d acceleration which is judging from your program needs list, is going to be important.


text:
Q: Batch processing renaming I need to duplicate file many times I have a list of product numbers that need to be used as part of the new file name -- so example;

*

*original file called photo.main.jpg

*I need to copy the photo.main.jpg file many times (I am hoping to put the names to substitute in a file to read)

*I have product names say 123, 456, 789, 345, 221 in the file and the product name must replace the word "photo" in the file.

*this scenario i would want 5 new files called 123.main.jpg, 456.main.jpg, 789.main.jpg, 345.main.jpg and 221.main.jpg
I am hoping to do in Windows command prompt -- can someone help?

A: While this can be done in a cmd shell, PowerShell provides access to
regex processing that can make it very flexible.
The $replpat regex can be anything that provides what the
regex in the Copy-Item command needs. Using $matches is not required.
$orgfile = 'photo.main.jpg'
$prodfile = '.\prodlist.txt'
$replpat = '[^\.]*(.*)'

$ismatch = $orgfile -match $replpat
$filebase = $matches[1]

Get-Content -PSPath $prodfile |
    ForEach-Object {
        Copy-Item -Path $orgfile -Destination "$_$filebase" -WhatIf
    }


text:
Q: UIWebView path depends on previous pressed button Xcode I have a ViewController (A), containing n buttons. all buttons map to other ViewController(B) containing a WebView to show a different PDF.
Instead of creating n ViewController, I would know how to change path according to which button was pressed.

my wrong tries:
1- use tags of buttons in ClassB viewDidLoad:(id) sender (I add sender)
([sender tag] == 1)
//Action

2- access public variable from other class
in class A.h
@interface ClassA : UIViewController
{
    @public
    NSString *path;//was var
}
@property (readwrite, nonatomic) NSString* path;

ClassA.m
- (IBAction)button1:(UIButton *)sender{
    path=[[NSBundle mainBundle]
                    pathForResource:@"filename" ofType:@"pdf"];
}

in class B:
ClassB *obj ;
NSURL *url= [NSURL fileURLWithPath:obj->path];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[_webview loadRequest:request];
[_webview setScalesPageToFit:YES];

A: You have to do something like:
//implement prepareForSegue at the ViewController with the buttons
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"button1Segue"]) {
        DesitnationController *controller = (DesitnationController *)segue.destinationViewController;
        //set some public variable to know which button called the view
        //or directly set a URL or do whatever you need to do. Example:
        controler.pdfUrl = @"http://www.pdfsite.com/pdfForButton1.pdf";
    }
}

in the destination ViewController just use the variable you have set.
If you are not working with segues, you can create, push the UIViewController and set the variable in the IBAction method.

A: in your ClassA.m
 - (IBAction)button1:(UIButton *)sender{
           path=[[NSBundle mainBundle]
                pathForResource:@"filename" ofType:@"pdf"];

        [self performSegueWithIdentifier:@"yourIdentifierName" sender:self];
  }

 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender       {
if([segue.identifier isEqualToString:@"yourIdentifierName"]) {
    classB *clsB =segue.destinationViewController;
    clsB.typeofSelect=path;

   }
}

in your class B.h
@property (nonatomic, weak) NSString *typeofSelect;

in your Class B.m
@synthesize typeofSelect;

-(void)viewDidAppear:(BOOL)animated
{

[super viewDidAppear:animated];

if (typeofSelect )
{
  NSURL *url= [NSURL fileURLWithPath: typeofSelect];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[_webview loadRequest:request];
[_webview setScalesPageToFit:YES];
 }
else
 {
  // no path found;
  }
}

A: If you can differ which url you want to show depending upon a numeric digit, then using tag is an ideal option.
First declare a simple property in ViewController(B) like this:
@property (strong, nonatomic) NSInteger tagValue;

Then simply, provide all your buttons with specific tags and connect all the buttons to the same IBAction. Let's consider your IBAction is buttonPressed:, your code will be something like:
- (IBAction)buttonPressed:(UIButton *)sender{
    [self performSegueWithIdentifier:@"loadNextPage" sender:sender];
}

Lastly, in your prepareForSegue: method, do the following:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"loadNextPage"]) {
       UIButton *button = (UIButton *)sender;
ViewControllerB *controller = segue.destinationViewController;
controller.tagValue = [button tag];
 }
}


text:
Q: Why are the days in the .inline style UIDatePicker not being localised when applying a locale to the datpicker? I am setting the locale of a UIDatePicker outlet to be Arabic and the preferred style to be inline as follows:
picker.locale = Locale(identifier: "ar_AE")
picker.preferredDatePickerStyle = .inline

The localisation is being applied to the month and year drop-down selection but not to the days of the calendar as shown in the screenshot below:

A: Set your locale to the picker.calendar.locale also, then you can get the weekdays in your desired locale
picker.locale = Locale(identifier: "ar_AE")
picker.calendar.locale = Locale(identifier: "ar_AE")
picker.preferredDatePickerStyle = .inline


text:
Q: Send only JSON error instead of html in node.js Whenever a user registers in the app with invalid details like phone-number or email I want to throw an error as JSON object but it is displaying the html in the postman response.
The register route:
exports.register = async (req, res) => {
  try {
    var isValidated = await userService.validateInDatabase(req);
    if (!isValidated)
      return res
        .status(409)
        .json({ error: "Phone number or email is already registered" });

    var user = await userService.create(req.body);
    var token = await sendVerification(user);
    return res.status(201).json({ user, token });
  } catch (e) {
    return res.status(400).json({ message: e.message });
  }
};

The validate function:
const validate = (schema) => (req, res, next) => {
  const validSchema = pick(schema, ["params", "query", "body"]);
  const object = pick(req, Object.keys(validSchema));
  const { value, error } = Joi.compile(validSchema)
    .prefs({ errors: { label: "key" }, abortEarly: false })
    .validate(object);

  if (error) {
    const errorMessage = error.details
      .map((details) => details.message)
      .join(", ");
    return next(new ApiError(httpStatus.BAD_REQUEST, errorMessage));
  }
  Object.assign(req, value);
  return next();
};

The API endpoint for user registration:
router
  .route("/register")
  .post(validate(userValidation.createUser), User.register);

The error:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Error</title>

Error: "phoneNumber" length must be at least 10 characters long...

The apiError function:
class ApiError extends Error {
  constructor(statusCode, message, isOperational = true, stack = "") {
    super(message);
    this.statusCode = statusCode;
    this.isOperational = isOperational;
    if (stack) {
      this.stack = stack;
    } else {
      Error.captureStackTrace(this, this.constructor);
    }
  }
}

A: By passing an error to the next callback, it gets passed to Express's error handling middleware, which in turn will render an HTML error page.
If you want to return validation errors as JSON, return a response directly from validate instead:
// not this:
return next(new ApiError(httpStatus.BAD_REQUEST, errorMessage));

// but this:
return res.status(400).json({ message: errorMessage });

Alternatively, if you want to streamline error handling in your app overall, you can use a custom error handling middleware which could, for instance, always return a JSON response in case an ApiError was thrown:
app.use((err, req, res, next) => {
  if (err instanceof ApiError) {
    return res.status(err.statusCode).json({ message: err.message })
  }
  // pass the error to the default error handler
  return next(err);
});

A: I had same issue. I moved middleware implementation line below the routes.
Before
// middleware for error
app.use(errorMiddleWare);
app.use('/api/v1', products);

After
app.use('/api/v1', products);
// middleware for error
app.use(errorMiddleWare);


text:
Q: How to download files using Springboot @RestController via ajax I have an Springboot rest controller to download a file. I am trying to access the endpoint using the browser and able to see the response in the xhr.response. However, i want to force the file download which i am not able to achieve.
The code is as follows :
Rest based endpoint (Springboot):
    @GetMapping(value = "download/{id}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE, consumes = "*/*")
public ResponseEntity<InputStreamResource> getFile(@PathVariable("id") Long contractId) {

    Contract contract;
    contract = this.contractRepository.findOne(contractId);
    System.out.println(contract.getPath()); // test
    InputStreamResource resource    = null;
    HttpHeaders         respHeaders = new HttpHeaders();

    if (contract != null) {

        try {
            File            file            = new File(contract.getPath());
            FileInputStream fileInputStream = new FileInputStream(file);
            resource = new InputStreamResource(fileInputStream);
            System.out.println(resource.exists());//test

            respHeaders.add("Content-Type", URLConnection.guessContentTypeFromStream(fileInputStream));
            respHeaders.add("Cache-Control", "no-cache, no-store, must-revalidate");
            respHeaders.add("Pragma", "no-cache");
            respHeaders.add("Expires", "0");
            respHeaders.add("Content-Disposition", "attachment;filename=" + file.getName());
            respHeaders.add("Content-Transfer-Encoding", "Binary");
            respHeaders.setContentLength(file.length());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return new ResponseEntity<InputStreamResource>(
            this.companyService.downloadContract(contractId),
            respHeaders,
            HttpStatus.OK
    );

}

My xhr request is as follows

 var xhr = new XMLHttpRequest();
 xhr.open("GET", http.getHRTargetURL() + "download/" + id, true);
 xhr.setRequestHeader("X-Auth-Token", http.getToken());
 xhr.setRequestHeader("Accept", "application/octet-stream");
 xhr.setRequestHeader("Content-Type", "application/octet-stream");

 xhr.onreadystatechange = function () {
     if (xhr.readyState == 4 && xhr.response != "0") {
         console.log(xhr)
         console.log("Downloaded file");
     } else {
        console.log("error downloading document")
     }
  }
xhr.send();

I am able to get the response from the endpoint . I can see the file contents in the xhr response on the browser

My problem is how can I force this response to popup file save wizard on the browser.

A: You could try like this.
xhr.onreadystatechange = function () {
     if (xhr.readyState == 4 && xhr.response != "0") {
         console.log(xhr)
        var windowUrl = window.URL || window.webkitURL;
        var url = windowUrl.createObjectURL(xhr);
        anchor.prop('href', url);
        anchor.prop('download', "filename");
        anchor.get(0).click();
        windowUrl.revokeObjectURL(url);
         console.log("Downloaded file");
     } else {
        console.log("error downloading document")
     }
  }
xhr.send();

A: Well as I figured out that problem was with the frontend and had nothing to do with backend as Springboot was sending the proper response back.
Building on the answer provided by Dinesh above i modified my answer as follows
download(id, name){

    var xhr = new XMLHttpRequest();
    xhr.open("GET", http.getHRTargetURL() + "download/" + id, true);
    xhr.setRequestHeader("X-Auth-Token", http.getToken());
    xhr.setRequestHeader("Content-Type", "application/octet-stream");
    xhr.responseType       = "blob";

    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style    = "display: none";
        var url    = window.URL.createObjectURL(new Blob([xhr.response], {type: "octet/stream"}));
        a.href     = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
      } else {
        console.log("error downloading document")
      }
    }
    xhr.send();

  }


text:
Q: How to have different return values in each describe block for a service mock with angular testbed and jest? When testing components or services, I would like to test different scenarios: the service returns one kind of object, it returns an error, it returns a different kind of object, etc. But I'm having issues making this happen with jest and angular.
This is what I have:
describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let rootElement: DebugElement;

  const mockdata = {
    name: 'Foo',
    surname: 'Bar',
  };

  let mockServiceInstance: { [key: string]: jest.Mock } = {
    getName: jest.fn(),
    getSurname: jest.fn(),
  };

  let mockService: jest.Mock;

  beforeEach(() => {
    // These values are always used throughout the test suite
    // no matter what.
    mockServiceInstance.getNamee.mockReturnValue('');
    mockServiceInstance.getSurname.mockReturnValue('');

    mockService = jest
      .fn()
      .mockReturnValue(mockServiceInstance);
  });

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      providers: [
        {
          provide: MyService,
          useClass: mockService,
        },
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    rootElement = fixture.debugElement;
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  describe('when there is a name and surname', () => {
    beforeEach(() => {
      // These values are never returned.
      mockServiceInstance.getName.mockReturnValue('Foo')
      mockServiceInstance.getSurname.mockReturnValue('Bar');

      TestBed.overrideProvider(MyService, {
        useFactory: mockService,
      });
    });

    it("should show the name", () => {
      const expected = 'Foo';

      const actual = rootElement.query(By.css('#name'))
        .nativeElement.textContent;

      expect(actual).toBe(expected);
    });

    it("should show the surname", () => {
      const expected = 'Bar';

      const actual = rootElement.query(By.css('#surname'))
        .nativeElement.textContent;

      expect(actual).toBe(expected);
    });
  });

  describe('when there is a name and no surname', () => {
    beforeEach(() => {
      // These values are never returned.
      mockServiceInstance.getName.mockReturnValue('Foo')
      mockServiceInstance.getSurname.mockReturnValue('');

      TestBed.overrideProvider(MyService, {
        useFactory: mockService,
      });
    });

    it("should show the name", () => {
      const expected = 'Foo';

      const actual = rootElement.query(By.css('#name'))
        .nativeElement.textContent;

      expect(actual).toBe(expected);
    });

    it("should not show the surname", () => {
      const expected = '';

      const actual = rootElement.query(By.css('#surname'))
        .nativeElement.textContent;

      expect(actual).toBe(expected);
    });
  });
});

My problem is that whatever override I set for the return values is never run, it runs the implementation from the topmost beforeEach instead, every time.
I suspect this doesn't work because the mock service is injected and instantiated once and then reused... But I thought Testbed.overrideProvider would inject the new instance and use these values instead. I have also tried useValue instead of useFactory in the options but no difference.
I have also considered using the parameters the mock is called with to return different values but that isn't as elegant since it all has to be defined in one place for every scenarion; and there are cases where I can't directly control the arguments the mocked service is called with from the test.
How can I elegantly achieve selective overrides for the service's mock functions return values to test different scenarios within the same test suite?


text:
Q: (JQuery) modify array I have this code where a table is made from an array (myList) and you can delete a specific row and the table will rebuilt itself with the new list. This works fine for the first time on my computer (but not on the snippet), but when you try again, it just doesn't work.

$( document ).ready(function() {
    createTable(myList, myList.length);
});

$('.btn').click( function(){
  var rowOn = $(this).closest("tr").index();
 myList.splice(rowOn, 1);
 createTable(myList, myList.length);
});

col1	col2

PS: this is a simplified sample of the code, I really need to rebuild the entire table in my case so just hidding the row will not work.
Thanks!

A: You need to create a dynamic event delegation, because you recreate your buttons and so your listeners get lost otherwise when recreateing the table.
$('table').on('click', '.btn', function() { /* ... */ });

var myList = ["a", "b", "c", "d", "e"];

function createTable(list, nb){
    $('#myTab > tbody > tr').remove();

    for (var i = 0; i < nb; i++) {
        var str = '<button class="btn">Delete</button>	';
        $('#myTab > tbody').append('
'+str+''+list[i]+'
');
    }
};

$(function() {
    createTable(myList, myList.length);
});

$('table').on('click', '.btn', function() {
    var rowOn = $(this).closest("tr").index();
    myList.splice(rowOn, 1);
    createTable(myList, myList.length);
});

col1	col2

Beside this, why do you want to recreate the table every time? You could only remove the clicked row.

var myList = ["a", "b", "c", "d", "e"];

$(function() {
    $('#myTab > tbody > tr').remove();

    for (var i = 0; i < myList.length; i++) {
        var str = '<button class="btn">Delete</button>	';
        $('#myTab > tbody').append('
'+str+''+myList[i]+'
');
    }
});

$('table').on('click', '.btn', function() {
    var row = $(this).closest("tr");
    myList.splice(row.index(), 1);
    row.remove();
});

col1	col2


text:
Q: Warnings about dynamic inline CSS in Blazor Not sure if this should be fixed in Blazor or Visual Studio, but I have a Razor page with an inline CSS section that contains styles generated based on some logic, so it has to be dynamic and inline. This makes Visual Studio show a warning CSS039 about Unexpected character sequence in property value.
@{ var styles = new List<string>(); }

Questions

*

*Blazor: is it possible to have dynamic CSS in a separate file?

*Visual Studio: trying to suppress this warning in .editorconfig file, why it's not going away?

root = true

[*]
indent_style = space

[*.cs]
dotnet_diagnostic.CSS039.severity = none

[*.razor]
dotnet_diagnostic.CSS039.severity = none

[*.css]
dotnet_diagnostic.CSS039.severity = none

A: This seems to get rid of the warning.

If for some reason you had a more complicated code block that required the @() you could also just compute the string as a local variable in the above code block and then reference it directly in you style.
E.g.
@{
    var styles = new List<string>() {"MyBackground.png"};
    var backgroundImage = string.Join(",", styles);
 }

A: I don't recommend doing it this way.  The reason to define styles with class names is for readability, reusability and so on-- things that don't apply if you're dynamically generating style attributes.
Therefore, it's fine to just use inline style attributes wherever you'd have used your class:

@code {
    string styleattributes = "background-color: black; width:50%;";
}


text:
Q: In App Purchase product screen doesn't populate for Apple Review Team, but DOES populate in my simulators and physical device in test My iOS app was rejected by Apple, with the reason being they couldn't get my In-App Purchase to work. To start the IAP, I have buttons for the user to click, and the review team said when they tapped the buttons:

they were unresponsive and the in-app purchase product payment screen did not populate.

This is very confusing as I've tested it in multiple simulators, as well as my physical iPad — the payment screen populates every time, and I'm able to complete the test transaction and complete the IAP.
I've been searching for what the issue may be and it's especially difficult when I can't actually replicate the issue myself. I can only think of a couple of possibilities, I'd appreciate if anyone can offer any advice / confirm or rule them out:

*

*I followed this tutorial when setting up my IAP. When following it I set up a Configuration.storekit file — should I have set my StoreKit Configuration back to "None" before submitting to Apple?

*In another tutorial, they said to add "In-App Purchase" on the Signing & Capabilities page (see screenshot). I hadn't done this before I submitted, might this be why the review team couldn't get it to work?
Are there any other reasons why they might not be able to use my IAP?