text:
Q: How can I make amsthm and cleveref to work with htlatex? I have the following test.tex document:
\documentclass{article}
\usepackage{hyperref}
\usepackage{amsthm}
\usepackage{cleveref}
\newtheorem{thm}{Theorem}[section]
\newtheorem{rmk}[thm]{Remark}
\begin{document}
\begin{rmk}
.
\end{rmk}
\end{document}

With pdflatex and latex, everything works fine:
D:\Documents\GitHub\book>latex test.tex
This is pdfTeX, Version 3.1415926-2.4-1.40.13 (MiKTeX 2.9 64-bit)
entering extended mode
(D:\Documents\GitHub\book\test.tex
LaTeX2e <2011/06/27>
Babel <v3.8m> and hyphenation patterns for english, afrikaans, ancientgreek, ar
abic, armenian, assamese, basque, bengali, bokmal, bulgarian, catalan, coptic,
croatian, czech, danish, dutch, esperanto, estonian, farsi, finnish, french, ga
lician, german, german-x-2012-05-30, greek, gujarati, hindi, hungarian, iceland
ic, indonesian, interlingua, irish, italian, kannada, kurmanji, latin, latvian,
 lithuanian, malayalam, marathi, mongolian, mongolianlmc, monogreek, ngerman, n
german-x-2012-05-30, nynorsk, oriya, panjabi, pinyin, polish, portuguese, roman
ian, russian, sanskrit, serbian, slovak, slovenian, spanish, swedish, swissgerm
an, tamil, telugu, turkish, turkmen, ukenglish, ukrainian, uppersorbian, usengl
ishmax, welsh, loaded.
("D:\Program Files\MiKTeX 2.9\tex\latex\base\article.cls"
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
("D:\Program Files\MiKTeX 2.9\tex\latex\base\size10.clo"))
("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\hyperref.sty"
("D:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\hobsub-hyperref.sty"
("D:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\hobsub-generic.sty"))
("D:\Program Files\MiKTeX 2.9\tex\latex\graphics\keyval.sty")
(D:\Documents\GitHub\book\ifxetex.sty)
("D:\Program Files\MiKTeX 2.9\tex\latex\oberdiek\auxhook.sty")
("D:\Program Files\MiKTeX 2.9\tex\latex\oberdiek\kvoptions.sty")
("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\pd1enc.def")
("D:\Program Files\MiKTeX 2.9\tex\latex\00miktex\hyperref.cfg")
("D:\Program Files\MiKTeX 2.9\tex\latex\ltxmisc\url.sty"))

Package hyperref Message: Driver (default): hdvips.

("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\hdvips.def"
("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\pdfmark.def"
("D:\Program Files\MiKTeX 2.9\tex\latex\oberdiek\rerunfilecheck.sty")))
("D:\Program Files\MiKTeX 2.9\tex\latex\amscls\amsthm.sty")
(D:\Documents\GitHub\book\cleveref.sty)
No file test.aux.
("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\nameref.sty"
("D:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\gettitlestring.sty"))

Package hyperref Warning: Rerun to get /PageLabels entry.

[1] (D:\Documents\GitHub\book\test.aux)

Package rerunfilecheck Warning: File `test.out' has changed.
(rerunfilecheck)                Rerun to get outlines right
(rerunfilecheck)                or use package `bookmark'.

 )
Output written on test.dvi (1 page, 2332 bytes).
Transcript written on test.log.

D:\Documents\GitHub\book>pdflatex test.tex
This is pdfTeX, Version 3.1415926-2.4-1.40.13 (MiKTeX 2.9 64-bit)
entering extended mode
(D:\Documents\GitHub\book\test.tex
LaTeX2e <2011/06/27>
Babel <v3.8m> and hyphenation patterns for english, afrikaans, ancientgreek, ar
abic, armenian, assamese, basque, bengali, bokmal, bulgarian, catalan, coptic,
croatian, czech, danish, dutch, esperanto, estonian, farsi, finnish, french, ga
lician, german, german-x-2012-05-30, greek, gujarati, hindi, hungarian, iceland
ic, indonesian, interlingua, irish, italian, kannada, kurmanji, latin, latvian,
 lithuanian, malayalam, marathi, mongolian, mongolianlmc, monogreek, ngerman, n
german-x-2012-05-30, nynorsk, oriya, panjabi, pinyin, polish, portuguese, roman
ian, russian, sanskrit, serbian, slovak, slovenian, spanish, swedish, swissgerm
an, tamil, telugu, turkish, turkmen, ukenglish, ukrainian, uppersorbian, usengl
ishmax, welsh, loaded.
("D:\Program Files\MiKTeX 2.9\tex\latex\base\article.cls"
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
("D:\Program Files\MiKTeX 2.9\tex\latex\base\size10.clo"))
("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\hyperref.sty"
("D:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\hobsub-hyperref.sty"
("D:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\hobsub-generic.sty"))
("D:\Program Files\MiKTeX 2.9\tex\latex\graphics\keyval.sty")
(D:\Documents\GitHub\book\ifxetex.sty)
("D:\Program Files\MiKTeX 2.9\tex\latex\oberdiek\auxhook.sty")
("D:\Program Files\MiKTeX 2.9\tex\latex\oberdiek\kvoptions.sty")
("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\pd1enc.def")
("D:\Program Files\MiKTeX 2.9\tex\latex\00miktex\hyperref.cfg")
("D:\Program Files\MiKTeX 2.9\tex\latex\ltxmisc\url.sty"))

Package hyperref Message: Driver (autodetected): hpdftex.

("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\hpdftex.def"
("D:\Program Files\MiKTeX 2.9\tex\latex\oberdiek\rerunfilecheck.sty"))
("D:\Program Files\MiKTeX 2.9\tex\latex\amscls\amsthm.sty")
(D:\Documents\GitHub\book\cleveref.sty) (D:\Documents\GitHub\book\test.aux)
("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\nameref.sty"
("D:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\gettitlestring.sty"))
(D:\Documents\GitHub\book\test.out) (D:\Documents\GitHub\book\test.out)
[1{C:/ProgramData/MiKTeX/2.9/pdftex/config/pdftex.map}]
(D:\Documents\GitHub\book\test.aux) )<D:/Program Files/MiKTeX 2.9/fonts/type1/p
ublic/amsfonts/cm/cmbx10.pfb><D:/Program Files/MiKTeX 2.9/fonts/type1/public/am
sfonts/cm/cmr10.pfb><D:/Program Files/MiKTeX 2.9/fonts/type1/public/amsfonts/cm
/cmti10.pfb>
Output written on test.pdf (1 page, 28695 bytes).
Transcript written on test.log.

D:\Documents\GitHub\book>

However, with htlatex, I get errors:
D:\Documents\GitHub\book>htlatex test.tex

D:\Documents\GitHub\book>latex  \makeatletter\def\HCode{\futurelet\HCode\HChar}\
def\HChar{\ifx"\HCode\def\HCode"##1"{\Link##1}\expandafter\HCode\else\expandafte
r\Link\fi}\def\Link#1.a.b.c.{\g@addto@macro\@documentclasshook{\RequirePackage[#
1,html]{tex4ht}}\let\HCode\documentstyle\def\documentstyle{\let\documentstyle\HC
ode\expandafter\def\csname tex4ht\endcsname{#1,html}\def\HCode####1{\documentsty
le[tex4ht,}\@ifnextchar[{\HCode}{\documentstyle[tex4ht]}}}\makeatother\HCode .a.
b.c.\input  test.tex
This is pdfTeX, Version 3.1415926-2.4-1.40.13 (MiKTeX 2.9 64-bit)
entering extended mode
LaTeX2e <2011/06/27>
Babel <v3.8m> and hyphenation patterns for english, afrikaans, ancientgreek, ar
abic, armenian, assamese, basque, bengali, bokmal, bulgarian, catalan, coptic,
croatian, czech, danish, dutch, esperanto, estonian, farsi, finnish, french, ga
lician, german, german-x-2012-05-30, greek, gujarati, hindi, hungarian, iceland
ic, indonesian, interlingua, irish, italian, kannada, kurmanji, latin, latvian,
 lithuanian, malayalam, marathi, mongolian, mongolianlmc, monogreek, ngerman, n
german-x-2012-05-30, nynorsk, oriya, panjabi, pinyin, polish, portuguese, roman
ian, russian, sanskrit, serbian, slovak, slovenian, spanish, swedish, swissgerm
an, tamil, telugu, turkish, turkmen, ukenglish, ukrainian, uppersorbian, usengl
ishmax, welsh, loaded.
(D:\Documents\GitHub\book\test.tex
("D:\Program Files\MiKTeX 2.9\tex\latex\base\article.cls"
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
("D:\Program Files\MiKTeX 2.9\tex\latex\base\size10.clo"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\tex4ht.sty")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\usepackage.4ht")
("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\hyperref.sty"
("D:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\hobsub-hyperref.sty"
("D:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\hobsub-generic.sty"))
("D:\Program Files\MiKTeX 2.9\tex\latex\graphics\keyval.sty")
(D:\Documents\GitHub\book\ifxetex.sty)
("D:\Program Files\MiKTeX 2.9\tex\latex\oberdiek\auxhook.sty"

Package auxhook Warning: Cannot patch \document,
(auxhook)                using \AtBeginDocument instead.

) ("D:\Program Files\MiKTeX 2.9\tex\latex\oberdiek\kvoptions.sty")
("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\pd1enc.def")
("D:\Program Files\MiKTeX 2.9\tex\latex\00miktex\hyperref.cfg")
("D:\Program Files\MiKTeX 2.9\tex\latex\ltxmisc\url.sty")

Package hyperref Message: Stopped early.

)

Package hyperref Message: Driver: htex4ht.

("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\htex4ht.def")
("D:\Program Files\MiKTeX 2.9\tex\latex\amscls\amsthm.sty")
(D:\Documents\GitHub\book\cleveref.sty)
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\tex4ht.4ht"
::::::::::::::::::::::::::::::::::::::::::
 TeX4ht info is available in the log file
::::::::::::::::::::::::::::::::::::::::::
) ("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\tex4ht.sty"
("D:\Program Files\MiKTeX 2.9\tex\latex\graphics\color.sty"
("D:\Program Files\MiKTeX 2.9\tex\latex\00miktex\color.cfg")
("D:\Program Files\MiKTeX 2.9\tex\latex\graphics\dvips.def")
("D:\Program Files\MiKTeX 2.9\tex\latex\graphics\dvipsnam.def"))
--- needs --- tex4ht test ---
(D:\Documents\GitHub\book\test.tmp)
l.1437 --- TeX4ht warning --- No file test.xref ---
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\latex.4ht"
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\fontmath.4ht"
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\article.4ht"
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\hyperref.4ht"
("D:\Program Files\MiKTeX 2.9\tex\latex\hyperref\nameref.sty"
("D:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\gettitlestring.sty"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\nameref.4ht"
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\pd1enc.4ht"
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\url.4ht"
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\amsthm.4ht"
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\color.4ht"
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\dvips.4ht"
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\dvipsnam.4ht"
("D:\Program Files\MiKTeX 2.9\tex\latex\graphics\dvipsnam.def")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4.4ht")
("D:\Program Files\MiKTeX 2.9\tex\generic\tex4ht\html4-math.4ht"))
No file test.aux.
! Argument of \eorem:syle has an extra }.
<inserted text>
                \par
l.8 \begin{rmk}

?

What went wrong, and how do I fix it?

A: The solution is to use \AtBeginDocument{\usepackage{cleveref}}, to ensure that it is loaded after various packages.


text:
Q: How to remove google analytics cookies? With the new Cookie law i'm trying to find a way i can remove all cookie from my site with a PHP script.  I have got a script which works but it doesn't remove google analytics cookie.
How can I remove google analytics cookie?
foreach($_COOKIE as $key => $value) {
      setcookie($key, '', time()-1000);
      setcookie($key, '', time()-1000, '/');
  }

A: You need to pass the domain in as the 5th paramater...
 setcookie($key, '', time()-1000, '/', '.domain.com');

A: You cant remove a cookie on a clients browser that belongs to a different domain .google, but you could give the user a choice in adding the analytics code.
First step would be use PHP to check for the dnt header [example function], many browsers already support this + AVG has this as a browser plugin, if its there then default dont add the js code.
Or if the dnt header is not set then you can prompt the user about your tracking/analytic cookies, then store there choice in a cookie or a session.

A: usually firefox shows you whether the cookie was set under www.yourdomain.com or domain.com. In my case the google analytics cookies had been set for domain.com.
This code did the job, deleting all 3 Google-related cookies:
foreach ( $_COOKIE as $key => $value ){
if($_POST[$key]==1){
unset($_COOKIE[$key]);
if($key=='language'  || $key=='currency'){
setcookie($key, null, -1, '/', 'www.mydomain.com');
}else if($key=='_ga' || $key=='_gid' || $key == '_gat_gtag_UA_whatever_1' ){
setcookie($key, null, -1, '/', '.mydomain.com');
}else{
foreach ( $_COOKIE as $key => $value ){
if($_POST[$key]==1){
unset($_COOKIE[$key]);
if($key=='language'  || $key=='currency'){
        setcookie($key, null, -1, '/', 'www.mydomain.com');
}else if($key=='_ga' || $key=='_gid' || $key == '_gat_gtag_UA_whatever_1' ){
        setcookie($key, null, -1, '/', '.mydomain.com');
}else{
        setcookie($key, null, -1, '/');
}
$n++;
}
}

I let this run as a form action where I list all cookies stored currently in a client's browser and let him select which one he wants to delete. Those selected come in as $_POST[$key]==1 and are then handled by the script. The not-selected stay alive. This is for an online shop under OpenCart.
Needless to say, replace 'mydomain.com' by your's and 'whatever' in the tracking cookie by your google account numbers.

A: foreach($_COOKIE as $key => $value) {
    setcookie($key, '', time()-1000, '/', '.domain.com');
}

The above example doesn't work for me - all other cookies are removed leaving only the GA ones. Anyone know why this might be or a better method?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delete text after "more" tag (PHP) How to delete text after !--more-- tag?
I tried:
function addMore($text) {
    $text = preg_replace('/!--more--(.*)/', ' ', $text);
    return $text;
}

Thanks in advance.

A: Just delete the string, replacing it with the !--more--:
$text = preg_replace('/!--more--.*/', '!--more--', $text);

A: $text = "plain to you howhings of the great explorer of the truth.!--more-- plain to you how allt the truth,/";
echo $short = substr($text, 0, strpos( $text, '!--more--'));

Output:
http://codepad.org/atXzthBc

A: YOu can use explode function or simply substr as below :
$text = substr($text, 0, strpos($text, '!-more-'));

A: Add the 's' modifier to make the preg work even on break lines:
function addMore($text) {
    $text = preg_replace('/!--more--(.*)/s', ' ', $text);
    return $text;
}

look here:
http://php.net/manual/en/reference.pcre.pattern.modifiers.php

A: function addMore($text) {
$newtext=explode("!--more--",$text);

return $newtext[0];
}


text:
Q: Dynamic Populate Text Field in APEX I am trying to do an auto population of a form text-field in APEX using another database table as follows:
Table 1: TSTPAY (FORM Write)
ID (Sequence)
EMP_ID
BU_ID
AMOUNT

Table 2: EMBU
EMP | A
BU  | BU_A

Basically I am looking for the APEX form to behave in such a way that when the user inputs 'A' into the the EMP_ID text field, it will trigger an action to pre-populate the BU_ID to BU_A.
The action I've created does not appear to be resolving any value for :P7_EMPID. I can see the action working where I've hard coded in the 'Where' value into my SQL statement (i.e. SELECT BU FROM BUEMP A WHERE A.EMP = 'A')
Any advice would be greatly appreciated!
Full implementation details below:
Using some resources I've built a dynamic action to trigger on change of the P7_EMPID.
-Sequence:10
-When Event: Change, Selection type items: P7_EMPID, EVENT SCOPE STATIC
SET VALUE
-Action: set value, set type: SQL statement, page items to submit: P7_BU, escape special characters: no, supress change event: no, affected elements: items, affected element item: P7_BU, fire when event result is true, fire on page load: true, wait for result: true.
The SQL query used is:
SELECT A.BU
FROM BUEMP A
WHERE A.EMP = :P7_EMPID

A: It seems you are submitting P7_BU while your code requires P7_EMPID.
try submitting P7_EMPID instead..


text:
Q: An attempt to retrieve content from returned the HTTP status code 502. Please check the URL and try again When twilio is trying to access my REST API URL via POST for an incoming SMS I am seeing the error.
 "An attempt to retrieve content from returned the HTTP status code 502. Please check the URL and try again.

What is this error and how to fix it?
Is the error coming from my server or Twilio side?
Am I missing something on my side?
Looking at Twilio web site as given here:
http://www.twilio.com/docs/errors/11200
it says something about we need to set the Content-Header. So how do I do that?
New to web Api and twiml.
Edited:
This is what I have currently under my webapi.config
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

My route config has
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

I added the following in Global.asax
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

       GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");
        GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddUriPathExtensionMapping("json", "application/json");

        BundleConfig.RegisterBundles(BundleTable.Bundles);

     }

If I add {action}.ext in my webapi.config I am getting 404 error.
So now what did I miss :-(

A: Twilo evangelist here.
So Web API determines how to serialize the data returned from an endpoint (JSON, XML, etc) by looking at the Accept header in the incoming request.  It will also set the Content-Type header based on the format of data it returns.  The problem is that Twilio's web hook requests don't include an Accept header, and if there is no Accept header Web API defaults to returning JSON.
Twilio expects TwiML (our XML-based language) in response to to its request, so if your Web API endpoint is returning JSON Twilio and setting the Content-Type header in the response to application/json, Twilio says thats bad.
There are a couple different ways you can tell Web API to format the response as XML.  The first is to remove the JSON formatter as an option available to Web API.  This SO post shows you how to remove the json media type formatter from the collection of available formatters:
Disable JSON Support in ASP.NET MVC Web API
Another option is to tell Web API to use a file extension as the way to determine which formatter to use, instead of the Accept header by using the AddUriPathExtensionMapping method:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");

That line tells Web API to treat any request to its endpoints that have a .xml extension to as a request for a text/xml media type response.
If you do this, you have to update your Web API route as well to allow for the extension:
api/{controller}/{action}.{ext}/{id}

Hope that helps.


text:
Q: OpenCV SVM - How to change Mat object to appropriate dimensions? So I am trying to build an SVM for Image classification and have successfully trained the SVM. Now the next step is to use the predict function to get the results. However when I tend to do this an Assertion Error comes up which is as follows:
OpenCV Error: Assertion failed (samples.cols == var_count && samples.type() == CV_32F) in predict

As I understand this is due to the fact that my sample matrix which is passed as an argument to the predict function is not of the appropriate size.
I did a svm->getVarCount() to learn that the number of variables expected is 2. That means the number of columns in my matrix which is passed should be 2. However I am unable to complete this final step with the following code I have written:
Ptr<SVM> svm = SVM::create();
svm->setType(ml::SVM::C_SVC);
svm->setKernel(ml::SVM::POLY);
svm->setGamma(3);
svm->setDegree(3);
svm->train(trainDataFormatted);
svm->save(saveFile);
Mat sampleMat_temp = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
Mat sampleMat;
sampleMat_temp.convertTo(sampleMat,CV_32F);
//Throws an error here because of the mismatch in dimensions
//float response = svm->predict(sampleMat_temp);
std::cout << "Result:" << svm->getVarCount() << std::endl;
std::cout << "Cols:" << sampleMat.cols;
svm->predict(sampleMat);

Here the 'svm' variable has been trained. I tried using reshape on sampleMat but to no avail. Any help would be much appreciated. Thanks!


text:
Q: Django doesn't accept my form hi i have a  in template a form generated by a modelForm :
    <body>
    <form action="/traitermodificationentrant.html/" method="POST" class="form-horizontal" >

    <legend> Modification du courrier numero {{ cemodifier.id}} </legend>
    <table>
        {{form}}

    </table>
    <input type="hidden" value="{{ cemodifier.id}}" name="id">
    <input type="submit" value="modifier"  />

</form>
    </body>
    </html>

and when i cliked in the button submit the treatment is processed by the view
def traiter_modif_entrant(request):
if request.method == 'POST':
    form = Form_modif_courrier_Entrant(request.POST)
    if form.is_valid():
        ident = form.cleaned_data['id']
        c = Courrier_Entrant.objects.get(id=ident)
        c.reference   = form.cleaned_data['reference']
        c.objet = form.cleaned_data['objet']
        c.categorie =form.clneaned_data['categorie']
        c.expediteur = form.cleaned_data['expediteur']
        c.save()
        HttpResponseRedirect('/')
else :
    form =Form_modif_courrier_Entrant()
return render_to_response('index.html', RequestContext(request,{}) )

and my problem is the form is always not valid
thanks in advance!

A: Maybe try this:
ident = int(form.cleaned_data['id'])

or if that doesn't work, then try "pk" instead:
c = Courrier_Entrant.objects.get(pk=ident)

A: You haven't actually passed the form to the template, so it will never show and neither will the errors. The last line of the view should be:
return render_to_response('index.html', RequestContext(request,{'form': form}))

or, better, using the render shortcut:
return render(request, 'index.html', {'form': form})


text:
Q: Encrypting DB with multi user access I am working on a project that will be sold to government entities. Because they will be storing sensitive lists of employees, they do not want us to have access to their DB.
I am not an encryption specialist, but I was thinking of encrypting the DB the app uses in such a way that we do not have access to it, but many users in their organisation (users they gave permissions to) must be able to read the data from their app.
How does that work? I read about public/private keys, symmetric/asymmetric encryption, but I'm having a hard time understanding how all of that fits in.


text:
Q: Sock picking without replacement (Probability) Question:
The chance of picking a red sock out of a drawer of infinite socks is $1\over3$
and the chance of picking a blue sock is $2\over3$
What's the chance that if I pick $20$ socks out of these, $19$ are blue?
Attempt:
I tried to find the probability of $P(\text{Blue} = 19 \text{ & Red} = 1)$ and multiplying it by the number of ways this could happen.
So,
$${P(\text{Blue} = 19 \text{ & Red} = 1)} = {2\over3}^{19} \cdot {1\over3}^1 = 0.00001504$$
Permutations: $\frac{20!}{19!} = 20$
Solution $= 20*0.00001504.$
I know this is wrong because I tried the above procedure with $P(\text{Blue} = 6 \text{ & Red} = 3)$, which intuitively should work out to 1, but did not get the result.
What am I missing here?

A: Your method is correct. Something is wrong with what you're saying here:

I tried the above procedure with P(Blue = 6 & Red = 3), which
  intuitively should work out to 1

You seem to be saying that if you take 9 socks then, since the probability of getting blue is 2/3, 2/3 of your 9 picks should be blue with probability 1.
This is not correct. If you pick 9 socks you can get any number of blues with non-zero probability. The expected number of blue socks will be 6. Which means if you pick 9 different socks infinitely many times, the average number of blue socks you get will be 6. You should look up expected value.


text:
Q: Video codec: determine type of macroblock In my video codec I have two types of frames: a frame can either be a ref frame (something like JPEG) or a delta frame. Delta frame is also like JPEG but done on difference of current and previous frames.
Now I want to define ref/delta info not per frame but per each macroblock (16x16 pixels). To do so I need to determine whether a macroblock should be a ref or a delta macroblock. What should I base this decision on? Ideally I want to pick the one the gives better compression but how can I decide this in a smart way without actually compressing the macroblock in both modes and then picking one producing better compression ratio?
The only way I can think of right now is to compute the sum of pixels differences within the macroblock and, if that sum is bigger than some threshold, classify the macroblock as ref. Delta otherwise.  But that doesn't sound like a robust solution.


text:
Q: How do I change the default color (#267114) of region when I use only one parameter Country in geochart I use a geochart same like this link
jsfiddle.net
code .
I use only one parameter City or country for data-set in geochart , I am unable to change his default data fill region color .
I want to change only circle color they are currently #267114 some thing like green .

A: Better you can give the full information (OR) Check with this site,
https://developers.google.com/chart/interactive/docs/gallery/geochart

A: var options = {
    defaultColor: '#F9CB1C'
}
It's not in the documentation for some reason. #hth


text:
Q: Association Exclude Based on Field I'm looking for the best Ruby way to accomplish this.
I have a Person that has_many Feeds through Subscriptions. So we can do things like Person.feeds, and it gets all the feeds a person is subscribed to.
Problem is, subscriptions are either authorized or deauthorized. What is the best way to make Person.feeds respect the Authorized status bit on the Subscription model?
So we can do something like Person.feeds.where(:status => authorized).

A: You can call this with a command like the following:
@person.feeds.joins(:subscription).where(subscriptions: { status: 'authorized' })

N.B. the joins takes the association's format, singular in this case, while where takes the table name, typically pluralised.
What this does in order is:

*

*Loads the feeds belonging to a person

*Joins these feeds to their subscription

*Queries the subscriptions table to return only the feeds where the subscription is active

To refactor this, I'd include a couple of methods in the relevant models:
# feed.rb
scope :active, -> { joins(:subscription).where(subscriptions: { status: 'authorized' }) }

# person.rb
def active_feeds
  feeds.active
end

Then, you can just call @person.active_feeds to get the results you want from anywhere in your code base.
(There's also the added bonus of Feed.active being available anywhere should you wish to display active feeds outside of a user's scope.)
Hope that helps - let me know if you've any questions.


text:
Q: What does apc.preload_path do in the APC settings? Just curious. It's undocumented in the manual here.
Maybe someone who is familiar with the APC source code can explain?

A: It specifies a directory from which APC loads cache data on startup. In a large setup (think 100+ servers), this would allow you to forgo compiling php files. You could also supply your own compilations if you were somehow smarter than APC and the php compiler, or other kinds of default data.
Apart from this one occurence, it's unused. Unless you have one of the problems described above, you should not set it.

A: At the moment of writing this option is broken because of a bug in the APC source code
which will not allow you to properly preload the cache.
Inside 'main_apc.c' in the method called 'static int apc_load_data(const char *data_file TSRMLS_DC)', the length of the key of the value that needs to be stored is determined with the following line :
key_len = strlen(key);

If I am correct this is only the length of the string itself without the null-terminator
However, "_apc_store" seems to want the length of the key string including the terminator.
If I change the line above to :
key_len = strlen(key)+1;

then the preload function works as expected.
You can also notice that 1 character is missing when looking at the user cache entries apc.php. But if you try to use that as a key then APC will not return the contents so that didn't work as a workaround.


text:
Q: How to use case_when to apply different functions in dplyr What I am thinking might be naive. But I want to split the rows [1:3] of df based on the second "_", using tidyr::extract()
library(tidyr)
library(dplyr)

extract(col1, into = c("col1", "col2"), "^(.*?_.*?)_(.*)$")

and the rows of df [4:6] based on the first "_"
extract(col1, into = c("col1", "col2"), "^(.*?)_(.*)$")

I am thinking of something like
df %>%
  mutate(n=row_number())
mutate(col2=case_when
  (n<=3 ~ extract(col1, into = c("col1", "col2"), "^(.*?_.*?)_(.*)$"),
  n>3 ~ extract(col1, into = c("col1", "col2"), "^(.*?)_(.*)$")
)

Of course, this is screamingly wrong but is it possible in some way?
Example data:
df=tibble(col1 = c("2397_A_run379_CTTGTACT_S119_L004_R1_001",
                   "3779_A_run535_TTATAGCC_S91_L003_R1_001",
                   "4958_BV_run685_GCGTACGT_S89_L005_R1_001",
                   "5126AA_S27_L004_R1_001",
                   "5126AF_S32_L004_R1_001",
"5126AL_S38_L004_R1_001"))

df
#> # A tibble: 6 × 1
#>   col1
#>   <chr>
#> 1 2397_A_run379_CTTGTACT_S119_L004_R1_001
#> 2 3779_A_run535_TTATAGCC_S91_L003_R1_001
#> 3 4958_BV_run685_GCGTACGT_S89_L005_R1_001
#> 4 5126AA_S27_L004_R1_001
#> 5 5126AF_S32_L004_R1_001
#> 6 5126AL_S38_L004_R1_001

Created on 2022-11-17 with reprex v2.0.2

A: tidyr::extract() takes and returns a dataframe, and will be tricky to use inside mutate(). I would instead use something like stringr::str_match():
library(dplyr)
library(stringr)

df %>%
  mutate(
    row = row_number(),
    col2 = case_when(
      row < 4 ~ str_match(col1, ".+?_.+?_(.+)")[, 2],
      row < 7 ~ str_match(col1, ".+?_(.+)")[, 2]
    )
  )

# A tibble: 6 × 3
  col1                                      row col2
  <chr>                                   <int> <chr>
1 2397_A_run379_CTTGTACT_S119_L004_R1_001     1 run379_CTTGTACT_S119_L004_R1_001
2 3779_A_run535_TTATAGCC_S91_L003_R1_001      2 run535_TTATAGCC_S91_L003_R1_001
3 4958_BV_run685_GCGTACGT_S89_L005_R1_001     3 run685_GCGTACGT_S89_L005_R1_001
4 5126AA_S27_L004_R1_001                      4 S27_L004_R1_001
5 5126AF_S32_L004_R1_001                      5 S32_L004_R1_001
6 5126AL_S38_L004_R1_001                      6 S38_L004_R1_001

A: If the pattern is to extract the substring by matching the _ the precedes one or more letters followed by digits,
library(dplyr)
library(stringr)
df %>%
  mutate(col2 = str_extract(col1, "(?<=_)[A-Za-z]+\\d+.*"))

-output
# A tibble: 6 × 2
  col1                                    col2
  <chr>                                   <chr>
1 2397_A_run379_CTTGTACT_S119_L004_R1_001 run379_CTTGTACT_S119_L004_R1_001
2 3779_A_run535_TTATAGCC_S91_L003_R1_001  run535_TTATAGCC_S91_L003_R1_001
3 4958_BV_run685_GCGTACGT_S89_L005_R1_001 run685_GCGTACGT_S89_L005_R1_001
4 5126AA_S27_L004_R1_001                  S27_L004_R1_001
5 5126AF_S32_L004_R1_001                  S32_L004_R1_001
6 5126AL_S38_L004_R1_001                  S38_L004_R1_001

Or use separate
library(tidyr)
separate(df, col1, into = c("col1", "col2"),
    sep = "(?<=[A-Z])_(?=[A-Za-z]+\\d+)", extra = "merge")

-output
# A tibble: 6 × 2
  col1    col2
  <chr>   <chr>
1 2397_A  run379_CTTGTACT_S119_L004_R1_001
2 3779_A  run535_TTATAGCC_S91_L003_R1_001
3 4958_BV run685_GCGTACGT_S89_L005_R1_001
4 5126AA  S27_L004_R1_001
5 5126AF  S32_L004_R1_001
6 5126AL  S38_L004_R1_001


text:
Q: how to fix 'AttributeError: module 'IPython' has no attribute 'utils'' while imporing my own module I have made my own class in python, but while making an object it gives strange error "AttributeError: module 'IPython' has no attribute 'utils'". This error is coming from the import statement in the init function in my module. I am importing from moviepy.
I have tried writing the import statement outside the class. I am trying to make an importable package for my personal use.
class video_reader_writer:
def __init__(self,video_file):
    from moviepy.editor import ImageSequenceClip // error here
    from moviepy.audio.AudioClip import AudioArrayClip
    import numpy as np
    ...

This is the stack trace :
    from moviepy.editor import ImageSequenceClip
  File "C:\Users\sagar\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\editor.py", line 49, in <module>
    from .video.io.html_tools import ipython_display
  File "C:\Users\sagar\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\video\io\html_tools.py", line 20, in <module>
    from IPython.display import HTML
  File "C:\Users\sagar\AppData\Local\Programs\Python\Python36\lib\site-packages\IPython\__init__.py", line 54, in <module>
    from .core.application import Application
  File "C:\Users\sagar\AppData\Local\Programs\Python\Python36\lib\site-packages\IPython\core\application.py", line 25, in <module>
    from IPython.core import release, crashhandler
  File "C:\Users\sagar\AppData\Local\Programs\Python\Python36\lib\site-packages\IPython\core\crashhandler.py", line 27, in <module>
    from IPython.core import ultratb
  File "C:\Users\sagar\AppData\Local\Programs\Python\Python36\lib\site-packages\IPython\core\ultratb.py", line 128, in <module>
    import IPython.utils.colorable as colorable
AttributeError: module 'IPython' has no attribute 'utils'


text:
Q: Express User is not defined Hi I've been working through this tutorial and have run into a problem.
In my edit.jade file I have this -
form(method="POST", action="/users/")
    input(type="hidden", name="_method", value="PUT")
p Name:
    input#name(type="text", name="name", value="#{user.name}")
p Email:
    input#email(type="email", name="email", value="#{user.email}")
p Age:
    input#age(type="number", name="age", value="#{user.age}")
p: button(type="submit") Update

I call the view with this code -
app.param('name', function (req, res, next, name){
Users.find({ name: name }, function (err, docs) {
    req.user = docs[0];
    next();
});
});
app.get('/users/:name/edit', function (req, res){
res.render("users/edit", { user: req.user });
});

However, when rendering the edit.jade file, this error is thrown -
ReferenceError: edit.jade:6
4|      input(type="hidden", name="_method", value="PUT")
5|  p Name:
> 6|        input#name(type="text", name="name", value="#{user.name}")
7|  p Email:
8|      input#email(type="email", name="email", value="#{user.email}")
9|  p Age:

user is not defined
at eval (eval at <anonymous> (/usr/local/lib/node_modules/jade/lib/jade.js:171:8),<anonymous>:32:99)
at /usr/local/lib/node_modules/jade/lib/jade.js:172:35
at /usr/local/lib/node_modules/jade/bin/jade:154:17
at /usr/local/lib/node_modules/jade/node_modules/mkdirp/index.js:38:26
at Object.oncomplete (fs.js:107:15)

This makes no sense to me. It does render the page with the correct values in the fields, but I can't submit the form. Ideas?

A: By using:
app.param('name', function (req, res, next, name){
  //...
});

You are mapping a parameter name to a user retrieved from the DB. You are currently extracting this parameter from your URLs:
app.get('/users/:name/edit', function (req, res){
  // ...
});

The :name token tells Express that it should invoke the code above and retrieve a user that will get saved in the request address.
The form in your template, however, makes a request to /users/, and no user is specified.
So, either you generate the correct URL for your form:
form(method="POST", action="/users/#{user.name}/xxx")

Or the method will fail.
I don't know the specifics of the tutorial, but I guess there should be another request handler that saves these parameters into the DB.


text:
Q: getting Exception: redis.clients.jedis.exceptions.JedisDataException: ERR Unsupported CONFIG parameter: notify-keyspace-events I am trying to use Redis for the session in a spring boot application using dependencies like:
<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-redis</artifactId>
       <version>1.5.9.RELEASE</version>
</dependency>
<dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
</dependency>

And the code for that like :
package com.dci.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;

@Configuration
@EnableRedisHttpSession
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {

}

This is another class for Redis connection and RestTemplate
@Configuration
@ComponentScan("com.dci")
public class RedisConfig {

        @Bean
        JedisConnectionFactory jedisConnectionFactory() {
            JedisConnectionFactory factory = new JedisConnectionFactory();
            return factory;
        }

        @Bean
        public RedisTemplate<String, Object> redisTemplate() {
            final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
            template.setConnectionFactory(jedisConnectionFactory());
            template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
            return template;
        }
    }


text:
Q: GroupBy in LINQ query, with many-to-many relational
I need to group by and see only 2 rows and at first row.cell[5] want to see ПН, СР, ПТ
How should i do concat, or what i need to do in general?
 var n = from dog in dbGarbageRemoval.ДоговорSet
                    join zakazchik in dbGarbageRemoval.ЗаказчикSet
                    on dog.КодЗаказчика equals zakazchik.КодЗаказчика into zak
                    join dogovor in dbGarbageRemoval.ДоговорыПереодичныхУслугSet
                    on dog.КодДоговора equals dogovor.КодДоговора into dogperiod
                    join dogovor2 in dbGarbageRemoval.ДоговорыБезПереодичностиУслугSet
                    on dog.КодДоговора equals dogovor2.КодДоговора into dognoperiod
                    from j1 in zak.DefaultIfEmpty()
                    from dp in dogperiod.DefaultIfEmpty()
                    join dni in dbGarbageRemoval.ДоговорыДниНеделиSet
                    on dp.КодДоговора equals dni.КодДоговора into dni2
                    from dni3 in dni2.DefaultIfEmpty()
                    from dp2 in dognoperiod.DefaultIfEmpty()
                    select new
                    {
                        dog.КодДоговора,
                        dog.СтоимостьЗаказа,
                        dog.ДатаЗаключенияДоговора,
                        j1.Фамилия,
                        j1.Имя,
                        j1.Отчество,
                        time = dp2 == null ? ?????????????????? :
                        dp2.ДатаВызова.Day <=9 && dp2.ДатаВызова.Month<=9 ?
                        "0"+dp2.ДатаВызова.Day+":"+ "0" + dp2.ДатаВызова.Month + ":" + dp2.ДатаВызова.Year + " " + dp2.ВремяВызова.ToString() :
                        dp2.ДатаВызова.Day <= 9 && dp2.ДатаВызова.Month > 9 ?
                        "0" + dp2.ДатаВызова.Day + ":" + dp2.ДатаВызова.Month + ":" + dp2.ДатаВызова.Year + " " + dp2.ВремяВызова.ToString() :
                        dp2.ДатаВызова.Day > 9 && dp2.ДатаВызова.Month <= 9 ?
                        dp2.ДатаВызова.Day + ":" + "0" + dp2.ДатаВызова.Month + ":" + dp2.ДатаВызова.Year + " " + dp2.ВремяВызова.ToString() :
                        dp2.ДатаВызова.Day + ":" +dp2.ДатаВызова.Month + ":" + dp2.ДатаВызова.Year + " " + dp2.ВремяВызова.ToString()
                    };

A: private string someMethod(string z)
    {
        int num;
        string allDays = z;
        if (Int32.TryParse(z.ToString(), out num))
        {
            allDays = "";
            var linq = from day in dbGarbageRemoval.ДоговорыДниНеделиSet
                       join days in dbGarbageRemoval.ДеньНеделиSet
                       on day.КодДняНедели equals days.КодДняНедели
                       where day.КодДоговора == num
                       select new
                       {
                           days.НазваниеДняНедели
                       };
            foreach (var dayweek in linq)
                allDays += dayweek.НазваниеДняНедели + ",";
            allDays = allDays.Substring(0, allDays.Length - 1);

        }
        return allDays;
    }
var n = (from dog in dbGarbageRemoval.ДоговорSet
                     join zakazchik in dbGarbageRemoval.ЗаказчикSet
                     on dog.КодЗаказчика equals zakazchik.КодЗаказчика into zak
                     join dogovor in dbGarbageRemoval.ДоговорыПереодичныхУслугSet
                     on dog.КодДоговора equals dogovor.КодДоговора into dogperiod
                     join dogovor2 in dbGarbageRemoval.ДоговорыБезПереодичностиУслугSet
                     on dog.КодДоговора equals dogovor2.КодДоговора into dognoperiod
                     from j1 in zak.DefaultIfEmpty()
                     from dp in dogperiod.DefaultIfEmpty()
                     from dp2 in dognoperiod.DefaultIfEmpty()
                     select new
                     {
                         dog.КодДоговора,
                         dog.СтоимостьЗаказа,
                         dog.ДатаЗаключенияДоговора,
                         j1.Фамилия,
                         j1.Имя,
                         j1.Отчество,
                         time = dp2 == null ? dog.КодДоговора.ToString() :
                          dp2.ДатаВызова.Day <= 9 && dp2.ДатаВызова.Month <= 9 ?
                          "0" + dp2.ДатаВызова.Day + ":" + "0" + dp2.ДатаВызова.Month + ":" + dp2.ДатаВызова.Year + " " + dp2.ВремяВызова.ToString() :
                          dp2.ДатаВызова.Day <= 9 && dp2.ДатаВызова.Month > 9 ?
                          "0" + dp2.ДатаВызова.Day + ":" + dp2.ДатаВызова.Month + ":" + dp2.ДатаВызова.Year + " " + dp2.ВремяВызова.ToString() :
                          dp2.ДатаВызова.Day > 9 && dp2.ДатаВызова.Month <= 9 ?
                          dp2.ДатаВызова.Day + ":" + "0" + dp2.ДатаВызова.Month + ":" + dp2.ДатаВызова.Year + " " + dp2.ВремяВызова.ToString() :
                          dp2.ДатаВызова.Day + ":" + dp2.ДатаВызова.Month + ":" + dp2.ДатаВызова.Year + " " + dp2.ВремяВызова.ToString()
                     }).AsEnumerable().Select(x => new {x.КодДоговора, x.СтоимостьЗаказа, x.ДатаЗаключенияДоговора, x.Фамилия, x.Имя, x.Отчество, S = someMethod(x.time).ToString() });
            dgvKnig.DataSource = n.ToList();


text:
Q: Kernel driver not installed (rc=-1908) -- Again After I read the solution in VBox on 14.04: Kernel driver not installed (rc=-1908)
I got following error after install ...
No suitable module for running kernel found
invoke-rc.d: initscript virtualbox, action "restart" failed.

What can I do?

A: Worked for me with below commands for Ubuntu 14.04
Download the virtual box https://www.virtualbox.org/wiki/Linux_Downloads
Remove dkms, since I installed several times this helped.
sudo apt-get remove --purge virtualbox-dkms
sudo dpkg -i Downloads/virtualbox-5.0_5.0.8-103449-Ubuntu-trusty_amd64.deb
sudo /etc/init.d/vboxdrv setup


text:
Q: Java non-static method addInv(int) cannot be referenced from a static context I know this error very well however this is the once time I'm stumped. I know that I can't call non-static variables from main method but this is confusing. Maybe you can help? That error is show on addInv(1); line...
Code:
import java.io.*;
import java.util.*;
import javax.swing.*;

public class item
{
    public static int attack, defense;
    public static ArrayList<String> arr;
public static String name, desc, typeOf, attackAdd, defenseAdd, canSell, canEat,earnedCoins,canEquip;

    String stats[];

        public static void main(String args[])
        {

            addInv(1);

        }

public void addInv(int e) {

String iname = getItem(1)[0];

String idesc = getItem(1)[1];
int itypeOf = Integer.parseInt(getItem(1)[2]);
int iattackAdd = Integer.parseInt(getItem(1)[3]);
int idefenseAdd = Integer.parseInt(getItem(1)[4]);
boolean icanSell = Boolean.parseBoolean(getItem(1)[5]);
boolean icanEat = Boolean.parseBoolean(getItem(1)[6]);
int iearnedCoins = Integer.parseInt(getItem(1)[7]);

attack = attack + iattackAdd;
defense = defense + idefenseAdd;
System.out.println("You picked up: " + iname);
arr.add("dan");
System.out.println("Description: " + idesc);

}

            // Types of Items
            // 0 - Weapon
            // 1 - Food
            // 2 - Reg Item
            // 3 - Helmet
            // 4 - Armor Legs
            // 5 - Chest Armor
            // 6 - Shield

        public String[] getItem(int e) {

        String[] stats = new String[7];

            String name = "Null";
            String desc = "None";
            String typeOf = "0";
            String attackAdd = "0";
            String defenseAdd = "0";
            String canSell = "true";
            String canEat = "false";
            String earnedCoins = "0";

            if (e == 1) {

        name = "Pickaxe";
        desc = "Can be used to mine with.";
        typeOf = "2";
        attackAdd = "2";
        earnedCoins = "5";
        }

      return new String[] { name, desc, typeOf, attackAdd, defenseAdd, canSell, canEat, earnedCoins};

    }

}

Thanks.

A: You can't call a non static method from a static method. So either make addInv static:
public class Item {
    ...

    public static void main(String args[]) {
        addInv(1);
    }

    public static void addInv(int e) {
        ...
    }

    public static String[] getItem(int e) {
        ...
    }
}

But making all these methods static may not be an appropriate design, you might prefer using an Item instance in your main:
public class Item {
    ...

    public static void main(String args[]) {
        Item item = new Item();
        item.addInv(1);
    }

}

By the way, I don't mean to be rude but you should seriously work on your (awful) code formatting and conventions, both for readers and for you.
See also

*

*Code Conventions for the Java Programming Language

*How to Write Doc Comments for the Javadoc Tool

A: static in Java means that it is a class variable or method, meaning that the method or variable is shared across all instances of the class. This also implies that you do not need to instantiate the class to call the method. NOTE: Unless you have a good reason to make things static it is generally not a good idea, because it makes a bunch of global variables and functions.
The proper way to address this is to create an instance of your class in the main and then call the method on the instance.
NOTE2: static variables run into issues if you have multiple threads and this means you need to synchronize the reads and writes across these Threads.
I would look at this: http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/java/javaOO/classvars.html
EDIT: Here is the code without the statics, that seems to work.
import java.util.ArrayList;

public class Item
{
    public int attack, defense;
    public ArrayList<String> arr = new ArrayList<String>();
    public String name, desc, typeOf, attackAdd, defenseAdd, canSell,
            canEat, earnedCoins, canEquip;

    String stats[];

    public static void main(String args[])
    {
        Item anItem = new Item();
        anItem.addInv(1);
    }

    public void addInv(int e)
    {
        String iname = getItem(1)[0];
        String idesc = getItem(1)[1];

        // Never read
        //int itypeOf = Integer.parseInt(getItem(1)[2]);
        int iattackAdd = Integer.parseInt(getItem(1)[3]);
        int idefenseAdd = Integer.parseInt(getItem(1)[4]);
        // Never read
        //boolean icanSell = Boolean.parseBoolean(getItem(1)[5]);
        // Never Read
        //boolean icanEat = Boolean.parseBoolean(getItem(1)[6]);
        // Never Read
        //int iearnedCoins = Integer.parseInt(getItem(1)[7]);

        attack = attack + iattackAdd;
        defense = defense + idefenseAdd;
        System.out.println("You picked up: " + iname);
        arr.add("dan");
        System.out.println("Description: " + idesc);

    }

    // Types of Items
    // 0 - Weapon
    // 1 - Food
    // 2 - Reg Item
    // 3 - Helmet
    // 4 - Armor Legs
    // 5 - Chest Armor
    // 6 - Shield

    public String[] getItem(int e)
    {
        // Never read
        // String[] stats = new String[7];
        String name = "Null";
        String desc = "None";
        String typeOf = "0";
        String attackAdd = "0";
        String defenseAdd = "0";
        String canSell = "true";
        String canEat = "false";
        String earnedCoins = "0";

        if (e == 1) {

            name = "Pickaxe";
            desc = "Can be used to mine with.";
            typeOf = "2";
            attackAdd = "2";
            earnedCoins = "5";
        }

        return new String[] { name, desc, typeOf, attackAdd, defenseAdd,
                canSell, canEat, earnedCoins };
    }
}

A:     public static void main(String args[])
    {
        item it = new item();
        it.addInv(1);
    }

A: You cannot call a method in the main, that is not associated with an object like that.
You needed to call:
item.addInv(1);
which means that your  public void addInt(int e) would need to be static:
public static void addInt(int e)

This means that your implementation of that method will need to be changed, because you are mixing some concepts there.
Basicly, static methods are methods that belong to the class they are in, and so they are not particular to any object of that class. Such methods can be called using the class name followed by a dot and the method name, and their implementation should not use specific object values, since those methods themselves are not associated with any particular objects from the class.
Hope that helps


text:
Q: How do we pronounce this symbol: $\nabla \phi$ I would like to know how to pronounce in English this symbol: $\nabla \phi$.
It is something phi  ... ?

A: The inversed delta is called Nabla. So Nabla phi. See also http://en.wikipedia.org/wiki/Nabla_symbol

A: it's actually del operator, https://en.wikipedia.org/wiki/Del
so it is del phi, in mathematics.
nabla article points to that for mathematical usage https://en.wikipedia.org/wiki/Nabla_symbol


text:
Q: Run upstart after all other init scripts have started I'm running a CentOS6 instance and have an upstart job that depends on sshd to already be running. However when I boot up the box that job fails to start, I'm guessing because sshd isn't actually running yet. Is there a way I can delay upstart jobs from starting until all normal init scripts have started?

A: I ended up figuring this out. CentOS6 uses upstart as its init program, but one of the scripts it initializes in /etc/init is rc.conf, which starts up the old-school rc scripts. So if you need your program to start AFTER those you can put:

start on started rc
stop on stopped rc

in your upstart script and you should be good to go.

A: You can check process sshd with pidfile /var/run/sshd.pid in your script to make sure it is running.
  if [ -f /var/run/says.pid]; then
     "do what you want with your script"
  fi

You can put logic inside where you can sleep after check for sshd if the pid is not there yet.

A: Just add your script to the /etc/rc.d/rc.local. Your script will be executed after all the other init scripts.


text:
Q: Degenerate, non-degenerate DC-DC converter Can anyone define what a degenerate DC-DC converter is?
This article mentions a "non-degenerate DC-DC converter" but did not explain it clearly (to me).
Also from the article:

Since only non-degenerate converters are of practical importance, this property implies that in a synthesis of voltaget+voltage converter topologies we should consider only even-order networks with the same number of capacitors and inductors.

Why are only non-degenerate converters of practical importance?

A: In certain fields, though not usually in engineering, the term "degenerate" is used to mean a case of a general class that is also a case of a simpler, more specific class. For instance, in mathematics, a circle could be considered a degenerate ellipse, since most of the mathematics for dealing with ellipses is unnecessarily complicated (though does still work) when talking about circles.
Here, it's saying that a DC-DC converter with a degenerate filter is not of interest. Take for instance this filter:

simulate this circuit – Schematic created using CircuitLab
The one on the left can be trivially simplified to the one on the right, so despite containing three reactive components (which in general would mean a third-order filter), it is actually only a second-order filter and can be analyzed as such.


text:
Q: How to Update and Insert database at same time using php in eclipse Following is my eclipse part code and php file. I want to insert and update the database tables in one php file when disapprove button is clicked. My insert query executes just fine but it don't update the table with column name status. How do I do that?
Eclipse code part
JAVA
{
    // somecode here
    btndisapp=(Button)findViewById(R.id.btndisapp);
    btndisapp.setOnClickListener(new View.OnClickListener(){
    InputStream is=null;
    @Override
    public void onClick(View arg0){
        // TODO Auto-generated method stub
        //String phone=Integer.toString();
        String name=""+tvname.getText().toString();
        String purpose=""+tvpurpose.getText().toString();
        String tfrom=""+tvtfrom.getText().toString();
        String job=""+tvjob.getText().toString();
        String tto=""+tvtto.getText().toString();
        String dfrom=""+tvdfrom.getText().toString();
        String dto=""+tvdto.getText().toString();
        List<NameValuePair>nameValuePairs=new ArrayList<NameValuePair>(7);
        nameValuePairs.add(new BasicNameValuePair("name",name));
        nameValuePairs.add(new BasicNameValuePair("purpose",purpose));
        nameValuePairs.add(new BasicNameValuePair("tfrom",tfrom));
        nameValuePairs.add(new BasicNameValuePair("job",job));
        nameValuePairs.add(new BasicNameValuePair("tto",tto));
        nameValuePairs.add(new BasicNameValuePair("dfrom",dfrom));
        nameValuePairs.add(new BasicNameValuePair("dto",dto));
        //nameValuePairs.add(new BasicNameValuePair("item",item));

        try{
              HttpClient httpClient=new DefaultHttpClient();

            HttpPost httpPost=new HttpPost("http://10.0.2.2/test/adddisappod.php");
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();

            //nameValuePairs.add(new BasicNameValuePair("id",id));

            HttpResponse response=httpClient.execute(httpPost);
            HttpEntity entity=response.getEntity();
            is=entity.getContent();
            String msg="Dispproved";
            Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
        }
        catch(ClientProtocolException e)
        {
            Log.e("ClientProtocol","Log_tag");
            e.printStackTrace();
        }
        catch(IOException e)
        {
            Log.e("Log_tag","IOException");
            e.printStackTrace();

        }
  }

 });
}

PHP File
<?php
<error_reporting(E_ALL ^ E_DEPRECATED);
$con=mysql_connect('localhost','root','');
if(!$con)
{
  die('Could not connect: '. mysql_error());
}
mysql_select_db("test",$con);

$name=$_POST['name'];
$job=$_POST['job'];
$purpose=$_POST['purpose'];
$dfrom=$_POST['dfrom'];
$tfrom=$_POST['tfrom'];
$dto=$_POST['dto'];
$tto=$_POST['tto'];
$ename=$_GET['name'];

mysql_query("insert into odattended
               (ename, ejob, selectjob, purpose, datefrom,
                dateto, timefrom, timetill, status)
             values('{$name}', '{$job}', '{$job}', '{$purpose}',
                    '{$dfrom}', '{$dto}', '{$tfrom}', '{$tto}',
                    'disapproved')"
           );
mysql_query("update od
               SET status='disapproved'
             where ename='."$name."'");

mysql_close();
?>

A: Check your syntax. correct update query:
mysql_query("update od SET status='disapproved' where ename='$name'");


text:
Q: React wrapper to return child on  component Is it possible in React to conditionally render a  inside a  using this kind of component?
import PropTypes from 'prop-types'
import { useApplication } from 'ice-components'

const canEdit = (currentUser) => {
    if (currentUser.settings.canEditSpecRec.value === 'False' || !currentUser.location.isSpecimenReceptionType) {
        return false
    }
    return true
}

const Permissions = ({ children }) => {
    const { currentUser } = useApplication()
    if (!canEdit(currentUser)) {
        return null
    }
    return children
}
Permissions.propTypes = {
    children: PropTypes.node,
}
export { Permissions as default, canEdit }

And the route is made in this way:
<Switch>
   <Route exact path component={component_1} />
   <Route path='/anotherPath' component={component_2} />
<Switch>

I tried to wrap the Permissions component around a single Route component but it breaks. Any ideas?

A: A good way to conditionally render a Route is the one provided by the section Auth of the react-router documentation:
https://reacttraining.com/react-router/web/example/auth-workflow
What's different in your application is that you're not authorizing based on authentication but on some user permission, you could do something like this:
function PrivateRoute({ children, ...rest }) {
  return (
    <Route
      {...rest}
      render={({ location }) =>
        canEdit(currentUser) ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: "/",
            }}
          />
        )
      }
    />
  );
}

Wrapping the Route in a PrivateRoute component that will return your route if user has permission to or something else if not (maybe a redirect).
export default function AuthExample() {
  return (
    <Router>
      <div>

        <Switch>
          <Route path="/public">
            <PublicPage />
          </Route>
          <Route path="/login">
            <LoginPage />
          </Route>
          <PrivateRoute path="/protected">
            <ProtectedPage />
          </PrivateRoute>
        </Switch>
      </div>
    </Router>
  );
}


text:
Q: Jquery Unobtrusive Validation 'Cannot read property 'type' of undefined' I am using jQuery Unobtrusive Validation in my MVC application.  When posting back, the validation works as-prescribed.  However, there are valid reasons for me to prevent a post-back client-side.
I am following the prescribed approach seen across multiple sites...and I have tried many different combinations.  However, I still keep getting the following error:
"Cannot read property 'type' of undefined"

MY JAVASCRIPT LOOKS LIKE:
The error happens when I call 'showErrors'...
function onValidateCity(e){

    // Checks the value of my Kendo Combobox
    var value = this.value();
    if (value && this.selectedIndex === -1) {

        // Yes, it reaches this part
        var validator = $('#CityId').validate();
        validator.showErrors({"CityId": "My custom error message!"});
    }
}

MY MVC HELPER CREATES THE FOLLOWING HTML:

        <input name="CityId_input" class="k-input form-control" type="text" autocomplete="off" title="" maxlength="524288" role="combobox" aria-expanded="false" placeholder="-- Select City --" tabindex="0" aria-disabled="false" aria-readonly="false" aria-autocomplete="list" aria-owns="CityId_listbox" aria-busy="false" style="width: 100%;" />

            select

    <input autocomplete="off" class="form-control" data-val="true" data-val-required="The City field is required." id="CityId" name="CityId" type="text" value=  "28dbddea-660d-4bbb-b063-f926b1153866" data-role="combobox" aria-disabled="false"
aria-readonly="false" novalidate="novalidate" style="display: none;" />

MVC (VALIDATION) HELPER LOOKS LIKE:
@Html.ValidationMessageFor(model => model.CityId, "", new { @class = "text-danger" })

A: When you initialize validator, do it against the element that contains CityId input nested inside, not the input element itself. It can be a form or a div or a span.
Here's simplified code working in fiddle, I did it against span:
http://jsfiddle.net/o0qhcbbL/1/
$('#button').click(function (e) {
    onValidateCity(e)
})

function onValidateCity(e) {

    var validator = $('#xx').validate();

    validator.showErrors({
        "CityId": "My custom error message!"
    });
}

html:

    <input id="CityId" name="CityId" type="text" />

select


text:
Q: Libraries that use $ similar to jquery Are there any JS libraries that use $ in the same way as Jquery uses it? I searched all over the internet to my capabilities and i couldn't find any use cases where there is a possibility for conflict over the usage of $ in jquery.

A: There really are quite a few. MooTools is one example, but there are many others as well. The $ character is used so frequently in JS shorthand because it very commonly has special significance in other programming languages, but is free from such associations in JS. So library developers will often use the $ character as a shortcut to their library.
This really isn't a big deal if you're writing well formatted JS. Any time you write a block of JS that relies heavily on a partiular library that uses a common shortcut, you should wrap it in an Immediately Invoked Function Expression that gives you full access to the shortcut while simultaneously preventing both conflicts and scope issues.
(function ($) {
    // use the $ within this function with impunity.
    // there is no danger of it conflicting with another library here.
    $('body').doStuff();
})(jQuery);


text:
Q: Why do I keep getting this 'no module named utils' error? I tried importing factor_analyzer in Jupyter notebook. But I got this error that says 'no module named utils' I recently switched from Python 3 to 2; never had this issue with Python 3. How do I fix this? - Samuel Duraivel

A: It seems the utils module is not installed on the system.  Try installing it with pip :
python -m pip install utils

A: i also faced same problem (import error)while trying to import different modules in python 3.7,so what i did is i just uninstalled the python 3.7 and installed new version of python which is 3.8 and i can able to import my modules without errors,so try using latest version....

A: utils.py and utils folder could be utilities code written for specific purpose. So it is advised to copy it from the repo to the root of your project folder.


text:
Q: How to import external .hpp file? i want to achieve this :
I have some definitions in a .h header, for example :
#define myVariable 0x01

This .h file is placed somewhere on my PC for example in C:\MyProgram, MyProgram.exe is in the same folder. I want to be able to change directly myVariable and this change would be effective even if i don't recompile the .exe, like the h file is external to this exe and not internal/compiled in it.
What is the simplest way to achieve this ? Thanks !

A: This is not how header files work. Really simplified: when you compile your program the lines with #include gets replaced with the actual contents of the header file, it is just copied in. So what's in there is there to stay.
What you need is to read a file with for example std::ifstream where the file is located somewhere the program is allowed to read it.


text:
Q: CSS: Why does reducing the font size of an adjacent inline element increase the overall leading? I have an element that contains two span tags that each contain some text. The container element sets a font size, then the font size on the second span tag is set to a lower size. When the second span is reduced in font size, the space between the line and the next block element is increased. This occurs in both WebKit and Gecko.
The p container element has { margin-bottom: 0; padding-bottom: 10px; } and its following sibling has { margin-top: -5px; }
The following image illustrates the situation and contains a snapshot of the relevant part of the document structure in FireBug.

Why is the spacing beneath the p tag increasing after reducing the font size of the second span tag?

A: My guess is that you have a (relatively) large line-height being inherited by that decimal span (perhaps 32px?), and when you reduce the font size down to 18px, you get a situation where the baseline of the decimal glyphs match up with the nondecimal glyphs, but the line must still take up the full specified line-height.  Thus, extra space is added below the baseline.
Add a line-height rule and I bet this goes away:
.box .value > .decimal { line-height: 18px; }


text:
Q: NSManagedObject subclass does not confirm to protocol I have NSManagedObject sublclass and i want them to confirm to my custom protocol JSONInitializable
There is my protocol:
protocol JSONInitializable {
  static func getAllEntities <T: NSManagedObject>(persistenceController:  PersistenceController) -> [T]
}

And my NSManagedObject sublclass function that causes error:
class CDShipment: NSManagedObject, JSONInitializable {
class func getAllEntities(persistenceController: PersistenceController) -> [CDShipment] {
  let request = NSFetchRequest(entityName: "CDShipment")
  let sorter = NSSortDescriptor(key: "managedNumber", ascending: true)
  request.sortDescriptors = [sorter]
  do {
    let results = try persistenceController.mainMoc?.executeFetchRequest(request) as! [CDShipment]
    return results
} catch {
    print("Error while getting all CDShipments")
  return []
 }
}
}

Error:

*

*Protocol requires function 'getAllEntities' with type ' (PersistenceController) -> [T]' (aka '<τ_1_0> PersistenceController -> Array<τ_1_0>')

*Candidate has non-matching type ' (PersistenceController) -> [T]' (aka '<τ_0_0> PersistenceController -> Array<τ_0_0>')
I can't understand, what the problem.


text:
Q: Object that comes in Spring @RequestBody is not working I have an object that has a list of another object inside it.
@Entity
@Table(name = "PEDIDO")
public class Pedido implements Serializable {

    private static final long serialVersionUID = -6787191900085416567L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JsonFormat(pattern = "dd/MM/yyyy HH:mm")
    private Date instante;

    @OneToOne(cascade = CascadeType.ALL, mappedBy = "pedido")
    private Pagamento pagamento;

    @ManyToOne
    @JoinColumn(name = "CLIENTE_ID")
    private Cliente cliente;

    @ManyToOne
    @JoinColumn(name = "ENDERECO_DE_ENTREGA_ID")
    private Endereco enderecoDeEntrega;

    @OneToMany(mappedBy = "id.pedido")
    private Set<ItemPedido> itens = new HashSet<>();

    //Getters and Setters
}

I also have a POST method to add the Object:
@PostMapping
public ResponseEntity<Void> insert(@Valid @RequestBody Pedido obj) {
    URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(pedidoService.insert(obj).getId()).toUri();
    return ResponseEntity.created(uri).build();
}

My POST request stays like this:
{
   "cliente":{
      "id":1
   },
   "enderecoDeEntrega":{
      "id":1
   },
   "pagamento":{
      "numeroDeParcelas":10,
      "@type":"pagamentoComCartao"
   },
   "itens":[
      {
         "quantidade":2,
         "produto":{
            "id":1
         }
      },
     {
         "quantidade":2,
         "produto":{
            "id":3
         }
      },
      {
         "quantidade":1,
         "produto":{
            "id":2
         }
      }
   ]
}

The problem is that when the request arrives from the server side, HashSet arrives with only one item, even if I send several items.
Has anyone ever experienced this?


text:
Q: Network devices behind switch are not seen on the wifi network Setup:
I have a new mesh network but am using my old router as a switch to use an Ethernet connection for certain devices including my TV (LG C1), my HTPC (Ubuntu 22.04.2 LTS) and my Nintendo Switch, set up as follows:
Internet -> Modem -> ASUS ZenWiFi AX Mini AX1800 base unit -> D-Link DIR-842 (old router) -> other devices
Certain features that used to work when everything was connected to a single router are no longer functioning, specifically, those that require my phone to see the device by being on the same network.
Example 1.
My LG ThinkQ Android app is unable to connect to the TV while the TV is connected by Ethernet but is able to connect while the TV is on wifi.
Example 2.
The KDE Connect app no longer is able to connect my phone with my HTPC.  The PC does not have wifi, so I am unable to connect that way, but, again, back when the PC was connected to the primary (i.e. only) router, this feature worked a treat.
The issue seems to be that devices behind the switch are not visible on the same network as those on the wifi network.  This seems to be confirmed by the fact that the ASUS Router app I use to manage the network shows the D-Link but not any device behind it (as far as I can tell.  There are a lot of devices on the network that I haven't identified yet.).
The Asus base has one Ethernet line in and only one Ethernet line out, so I can only send an Ethernet cable out to one device, hence the need for a switch.
How can I configure my network to have devices behind the switch visible to devices on the rest of the network?

Edit: Looking at the D-Link's manual here, I can't find anything about switch mode, bridge mode, or AP mode.  I disabled DHCP, but that seems to have broken the web GUI, so I've reset the router and am back where I started.
Having learned a bit from the answers so far, I am currently attempting a solution based on this post.  I will update if that succeeds or fails.

Edit 2: Success.
The other superuser post on how to use DIR-842 as an access point provided the solution.  I believe my mistake was interpreting WAN as the data-in port and LAN as the data-out port.  In the end, I did connect the Asus to a D-Link LAN port, not WAN. I apologize for the confusion and am grateful for the help.


text:
Q: Class App\Http\Middleware\CORS does not exist There are lots of result but nothing worked for me. It works in local development but doesn't work in a live server and give Class App\Http\Middleware\CORS does not exist error..
I am following these instructions and using this class.. Please see it..
https://gist.github.com/technoknol/1a35ca4b150215f491d5c807940bd4ef

A: Sorry guys, I think this may help others. I had the file with name Cors.php and class name CORS and this was the problem. I have changed this file name  to CORS.php and it worked fine. It seems a live server is case sensitive while the local development case insensitive.


text:
Q: What for is IsSchemaBound view's setting in SQL Server? What is the difference for a view if it is schema bounded or not?

A: If a view is schema bound, it means that the underlying schemas cannot change. It actually prevents it from doing so.
Schema binding also allows you to index a view. You can see the importance of a static schema when applying indices.
Keep in mind that a schema binding can only take place within a database--you can't schema bind a view to another database or another server. This is entirely for data integrity reasons--you're not always guaranteed to have access to that database or server, so therefore, you cannot prevent any and all changes to the schema.
Moreover, you can't drop a table that's schema bound. This will obviously muck up its schema, so is therefore prevented.
While I keep saying, "schema," I mean the table design. This includes the columns and their data types. You cannot change a column from int to bigint on a schema bound table. Nor can you change a column's name from id to tblID. This prevention is meant solely to uphold the integrity of the view.

A: You cannot index a view which is not schema bound.
A schema bound view is a part of schema dependency chains.
You cannot drop or alter a table which is referenced by a schema bound view, but can do it on a plain view (which will just throw a runtime error when referenced).

A:
The main benefit of SCHEMA BINDING is
  to avoid any accidental drop or change
  of an object that is referenced by
  other objects

Using schema binding to improve SQL Server UDF performance

A: There is a great explanation on the WITH SCHEMABINDING option int the Microsoft® SQL Server ®
2012 T-SQL Fundamentals by Itzik Ben-Gan, and in the Exam 70-461: Querying Microsoft SQL Server 2012 by Dejan Sarka, Itzik Ben-Gan, and more authors.
Here's an example when you try to drop an object or a column from an object created with the WITH SCHEMABINDING option:
Create a simple view using the WITH SCHEMABINDING option, than try to alter it e.g.:
ALTER TABLE Table DROP COLUMN Column1;

You'll get the following error:
Msg 5074, Level 16, State 1, Line 1
The object 'SomeObject' is dependent on column 'Column1'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE DROP COLUMN Column1 failed because one or more objects access this column.
If you had a view without the SCHEMABINDING option, this change would be allowed but it may lead to errors at run time if you query an object with a dropped object or a column.
The SCHEMABINDING option also has some preferences as it doesn't support the SELECT * syntax and you have to use qualified names (two-name convention).
Hope this helps


text:
Q: KeyError: 0 from Python I am trying to follow chapter 3 of Hands-On Machine Learning with Scikit-Learn and TensorFlow for classification of MNIST data. The command runs as follows in Jupyter notebook:
>>> from sklearn.datasets import fetch_openml
>>> mnist = fetch_openml('mnist_784', version=1)
>>> mnist.keys()
dict_keys(['data', 'target', 'feature_names', 'DESCR', 'details',
'categories', 'url'])

>>> X, y = mnist["data"], mnist["target"]
>>> X.shape
(70000, 784)
>>> y.shape
(70000,)

The following command throws error
>>> some_digit = X[0]

Error message:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3360             try:
-> 3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:

~/anaconda3/lib/python3.7/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

~/anaconda3/lib/python3.7/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-43-348a6e96ae02> in <module>
----> 1 some_digit = X[0]

~/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in __getitem__(self, key)
   3456             if self.columns.nlevels > 1:
   3457                 return self._getitem_multilevel(key)
-> 3458             indexer = self.columns.get_loc(key)
   3459             if is_integer(indexer):
   3460                 indexer = [indexer]

~/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:
-> 3363                 raise KeyError(key) from err
   3364
   3365         if is_scalar(key) and isna(key) and not self.hasnans:

KeyError: 0

It is hard for me understand what the actual error is as I have not come across similar one for such a simple assignment. What is causing the issue?

A: X is a dataframe so if you use X[0], it means you are looking for a column named "0". If you want the first row (index) of your dataframe, you have to use .loc or .iloc. In your case both methods are equivalent (only) because the index is numeric, start from 0 and continuous:
# Extract the first row as a Series
>>> X.loc[0]
pixel1      0.0
pixel2      0.0
pixel3      0.0
pixel4      0.0
pixel5      0.0
           ...
pixel780    0.0
pixel781    0.0
pixel782    0.0
pixel783    0.0
pixel784    0.0
Name: 0, Length: 784, dtype: float64

# Extract a pixel by label
>>> X.loc[0, 'pixel7']
0.0

# Extract the same pixel by position
>>> X.iloc[0, 6]
0.0

Update

Probably iloc would be more appropriate here

If you want to use iloc, prefer use numpy instead of pandas and convert data and target columns as array:
X, y = mnist["data"].to_numpy(), mnist["target"].to_numpy()


text:
Q: Prove that $5\cos A+3\cos\left(A+\frac{\pi}{3}\right)+3$ lies between $-4$ and $10$ After much of solving, I arrive at the expression
$$\frac{1}{2}\left[13 \cos A-3\sqrt{3}\sin A +6\right].$$
I can't conclude anything from this.
Please help. Hints are welcome.

A: Hint: By the Cauchy-Schwarz inequality,
$$ \left| 13\cos A-3\sqrt{3}\sin A\right| \leq \sqrt{13^2+27} = 14. $$

A: $\frac{1}{2}\left[13 \cos A-3\sqrt{3}\sin A +6\right]$
with $ \left| 13\cos A-3\sqrt{3}\sin A\right| \leq \sqrt{196} = 14 $
u get to:
$\frac{1}{2}\left[13 \cos A-3\sqrt{3}\sin A +6\right] \leq \frac{1}{2}\left[14 +6\right] = 10$


text:
Q: Duplicate classes when building app with firebase-firestore and google-cloud-language - android I'm getting duplicate class errors when I try to build android app that use firebase-firestore and google-cloud-language.

Duplicate class com.google.api.Advice found in modules classes.jar (com.google.firebase:protolite-well-known-types:16.0.1) and proto-google-common-protos-1.15.0.jar (com.google.api.grpc:proto-google-common-protos:1.15.0)
Duplicate class com.google.api.Advice$1 found in modules classes.jar (com.google.firebase:protolite-well-known-types:16.0.1) and proto-google-common-protos-1.15.0.jar (com.google.api.grpc:proto-google-common-protos:1.15.0)
Duplicate class com.google.api.Advice$Builder found in modules classes.jar (com.google.firebase:protolite-well-known-types:16.0.1) and proto-google-common-protos-1.15.0.jar (com.google.api.grpc:proto-google-common-protos:1.15.0)
Duplicate class com.google.api.AdviceOrBuilder found in modules classes.jar (com.google.firebase:protolite-well-known-types:16.0.1) and proto-google-common-protos-1.15.0.jar (com.google.api.grpc:proto-google-common-protos:1.15.0)
...
Duplicate class com.google.type.TimeOfDayProto found in modules classes.jar (com.google.firebase:protolite-well-known-types:16.0.1) and proto-google-common-protos-1.15.0.jar (com.google.api.grpc:proto-google-common-protos:1.15.0)

My build.gradle looks like follow:
...

dependencies {
    ...

    implementation 'com.google.firebase:firebase-ml-vision:20.0.0'
    implementation 'com.google.firebase:firebase-firestore:19.0.0'

    implementation 'io.grpc:grpc-okhttp:1.19.0'
    implementation'com.google.cloud:google-cloud-language:1.76.0'
}

How can I solve the issuse ?


text:
Q: How can I add a identification value to a modal box to identify which particular div the modal is being opened from I have three divs each looking like this

Stripe

Limit : 50- 50000 USD

 Charge - 0 USD+ 0%

                                            <button type="button" data-id="str"
                                                data-base_symbol="" class=" btn deposit cmn-btn w-100" data-toggle="modal"
                                                data-target="#exampleModal">
                                                Deposit</button>

i have identified and differentiated each of the 3 divs using data-id now when the deposit button is clicked it opens up this modal below,

                    Input Deposit Amount

                        ×

                <form action=" {{ route('deposit_request') }}" method="post" class="register">
                   @csrf

                            <input type="hidden" name="method_code" class="edit-method-code" value="">
                            <x-jet-validation-errors class="mb-4" />
                            @include('flash-message')

                            Enter Amount:

                                <input id="amount" type="text" class="form-control form-control-lg" name="usdamt"
                                    placeholder="0.00" required="" autocomplete="off">

                                    USD

                        <button type="button" class="btn btn-md btn-danger" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn-md cmn-btn">Next</button>

                </form>

now my question is how do I get the data-id variable to the hidden input in the modal to be able to identify which particular payment method was/is been used to open the modal, I suppose it can be done with Ajax or JavaScript, but not being so diverse in this areas I can seem to get it sorted out and is there a better way to differentiate the divs without using data-id

A: Bootstrap provides events of their modals.
The event I used here is show.bs.modal. The event details has a property called relatedTarget which tells you what prompted the modal event.
From that element you can extract the data-id attribute.

$('#exampleModal').on('show.bs.modal', function (e) {
  var data_id = $(e.relatedTarget).data('id');
  console.log(data_id);
})

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<button type="button" class="btn btn-primary" data-id="MAGIC" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        ...

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

A: There could be multiple solutions, but you could implement event delegation here.
Move the click event handler up to the parent div element containing all these buttons.
In your event listener, you could do something like this:
let selectedPaymentMethod = "";

const paymentClickHandler = (event) => {
  // get the element
  const buttonClicked = event.target;
  // there are several to check if it's button, i'm using classList
  if (buttonClicked && buttonClicked.classList.contains("btn")) {
    // there are multiple ways to handle this
    // if (buttonClicked.classList.contains('stripe')) payingUsingStripe();
    // if (buttonClicked.dataset.paymentmethod === 'stripe') payingUsingStripe();
    // I would do something like below
    setPaymentMethod(buttonClicked.dataset.paymentmethod);
    displayModal();
  }
};

function setPaymentMethod(paymentMethod) {
  // do some checks to ensure valid value and then
  selectedPaymentMethod = paymentMethod;
}

CodeSandbox to demonstrate above.
Hope it helps.


text:
Q: Get width and height of display assign it to static integer I am new to android developing please help me in this problem.
static Display display=((WindowManager)context
       .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
static int height=display.getHeight();
static int width=display.getWidth();

This shows error so give me solution.

11-26 17:40:17.806: ERROR/AndroidRuntime(422):
  java.lang.ExceptionInInitializerError

A: try with this
Display display = getWindowManager().getDefaultDisplay();
public static int width = display.getWidth();
public static int height = display.getHeight();

A: you can Try this for Get Height-width and dpi
DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        width = displayMetrics.widthPixels;
        height = displayMetrics.heightPixels;
        dpi = displayMetrics.densityDpi;


text:
Q: Laravel 5 - Switch from HTTP to HTTPS I have recently created a laravel project, and I am facing issues with it since I am trying to get it setup with SSL (Cloudflare).
What is the best way to redirect the user to the secured enviroment correctly in laravel 5?
Also, my CSS and JS are not beeing loaded in due to the fact that http is not allowed and my browser blocks the files from beeing loaded because they could be potential harmfull. (Which is not the case though, to be clear)
Can someone get me off the right track?

A: Redirecting your site users to a secure url (https://) should NOT be the job of the framework. This type of behavior should be handled on the DNS and A record level.

A: Redirecting from HTTP to HTTPS should be handled by the webserver.
Your assets are probably blocked because they are unencrypted (HTTP) on an encrypted site (HTTPS). You can solve that by using protocol relative URLs:
<script src="//ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>

Note the // instead of http:// or https://. This will cause your assets to be fetched using the same protocol as the site.
Laravel has a helper function for secure assets: secure_asset()
http://laravel.com/docs/5.1/helpers#method-secure-asset


text:
Q: C# - Add chart in Word I am working on a VSTO add-in which should be compatible with all version of Word.
I have written following code which adds a chart in Word file.
private void AddToNewChart()
{
     // add chart
    Word.Chart chart;
    Word.InlineShape inlineShape;
    string chartType = ((ComboBoxItem)cmbChartType.SelectedItem).Content.ToString();

    if (chartType.Equals("Pie Chart"))
        inlineShape = currDoc.InlineShapes.AddChart(Core.XlChartType.xlPie, Type.Missing);
    else
        inlineShape = currDoc.InlineShapes.AddChart(Core.XlChartType.xlColumnClustered, Type.Missing);

    inlineShape.AlternativeText = newChartName + "__TabularChart";
    chart = inlineShape.Chart;

    // get references
    dynamic chartWB = chart.ChartData.Workbook;
    dynamic chartTable = chartWB.Sheets[1].ListObjects("Table1");
    chartTable.DataBodyRange.ClearContents();
    dynamic chartRange = chartTable.Range.Resize[2, 2];

    // update data
    chartTable.Resize(chartRange);
    chartRange.Cells[chartRange.Rows.Count, 1] = namedRange;
    chartRange.Cells[chartRange.Rows.Count, 2] = excelValue;
    chartRange.Cells[chartRange.Rows.Count, 9] = string.Format("{0}->{1}->{2}", fileId, worksheet, namedRange);

    this.FillChartDropdown();

    chartWB.Close(1);
    chartWB.Application.Quit();
    chartWB.Application = null;
}

This works perfectly for Office 2010,
but in Office 2013 the Excel process is not terminated at end so so the Word freezes up completely after the chart is added.
So what should I do to terminate Excel process at end?


text:
Q: Multiple left joins, how to output in php I have 3 tables I need to join.  The contracts table is the main table, the 'jobs' and 'companies' table are extra info that can be associated to the contracts table.
so, since I want all entries from my 'contracts' table, and the 'jobs' and 'companies' data only if it exists, I wrote the query like this....
$sql = "SELECT * FROM contracts
        LEFT JOIN jobs ON contracts.job_id = jobs.id
        LEFT JOIN companies ON contracts.company_id = companies.id
        ORDER BY contracts.end_date";

Now how would I output this in PHP?  I tried this but kept getting an undefined error "Notice: Undefined index: contracts.id"...
$sql_result = mysql_query($sql,$connection) or die ("Fail.");

if(mysql_num_rows($sql_result) > 0){

    while($row = mysql_fetch_array($sql_result))
    {
       $contract_id = stripslashes($row['contracts.id']);
       $job_number = stripslashes($row['jobs.job_number']);
       $company_name = stripslashes($row['companies.name']);
    ?>
        <tr id="<?=$contract_id?>">
           <?=$job_number?>
           <?=$company_name?>

    <?
    }
}else{
    echo "No records found";
}

Any help is appreciated.

A: The column names will not be prefixed like this - and with each table having a column called "id" you could be in trouble. You should explicitly identify the columns you want returned rather than using "select *", and you then just retrieve the column by name un prefixed (e.g. $row['job_number']).

A: The below would solve you problem.
$sql = "SELECT contracts.id AS contract_id, jobs.job_number, companies.name FROM contracts
        LEFT JOIN jobs ON contracts.job_id = jobs.id
        LEFT JOIN companies ON contracts.company_id = companies.id
        ORDER BY contracts.end_date";

Your problem is likely to be realted to the fact you are using two tables with the field id this is why you should select them as an alias using the mysql as clause.
You may also want to look into using a naming convention for your fields and sticking with it. For example, check out the theory of Hungarian Notation, this would stop issues like this from arrissing.


text:
Q: SVG animate starts without being started I have an  inside a  that starts without the variables being started:
<rect height={5} width={5}>
    <animate
        attributeName="height"
        from={5} to={10} dur="2s"
        begin={start ? "0s": "indefinite}/></rect>

The component is inside a SVG which rerenders to change the 'start' variable to start the animation. However, the animation starts immediately regardless of when I choose to rerender it. So if I press it as soon as I render the page it's on then it will work properly. However, if I rerender the component after 2 seconds, the animation will jump to the end value. If I start the animation 1 second after rendering the page the component is on then the animation will play from the middle. What is going on?!
Thanks

A: begin and end times, if used without a reference to some other clock, always reference the beginning of the document. So instead of setting the value to 0s, you should use some other reference. Several possibilities come to mind:

*

*Start on click or some other event. The begin value takes the form of <id of event target element>.<event name>:
 <rect id="grafic" height={5} width={5}>
   <animate id="animation" attributeName="height"
            from={5} to={10} dur="2s" begin="grafic.click"/>
 </rect>

*Start from some other code. The begin value stays at indefinite:
 <rect id="grafic" height={5} width={5}>
   <animate id="animation" attributeName="height"
            from={5} to={10} dur="2s" begin="indefinite"/>
 </rect>

but the animation is started by API call:
 document.getElementById('animation').beginElement();

*For a more React-like feeling, define a wallckock value of "right now" at the time of setting the attribute:
 const rightnow = () => new Date().toLocaleTimeString()

 <rect id="grafic" height={5} width={5}>
   <animate id="animation" attributeName="height"
            from={5} to={10} dur="2s"
            begin={start ? `wallclock(${rightnow()})` : "indefinite"/>
 </rect>


text:
Q: get all images from post content wordpress using regular expression I need to get all images from the post content of wordpress post.
I am using
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);

It works fine for single image but for multiple images, it does not work.

A: You shouldn't use greedy dot-star or greedy dot-plus. They will eat up all characters immediately and may leave no opportunity for another match:
<img.+?src=([\'"])([^\'"]+)\1


text:
Q: Creating averaged time-bins from an existing dataframe I have the following dataframe called 'EasyScaled';
str(EasyScaled)
'data.frame':   675045 obs. of  3 variables:
$ Trial           : chr  "1_easy.wav" "1_easy.wav" "1_easy.wav" "1_easy.wav" ...
$ TrialTime       : num  3000 3001 3002 3003 3004 ...
$ PupilBaseCorrect: num  0.784 0.781 0.78 0.778 0.777 ...

The 'TrialTime' numeric variable denotes the time of each data point (3000 = 3000ms, 3001 = 3001 ms, etc.), 'PupilBaseCorrect' is my dependent variable, and the 'Trial' variable refers to the experimental trial.
I would like to create a new object which firstly divides my data into 3 time-bins (TimeBin1 = 3000-8000ms, TimeBin2 = 8001-13000ms, TimeBin3 = 13001 - 18000ms) and then calculate an average value for each timebin (for each trial) so that I would end up with something that looks like this (with the value given reflecting 'PupilBaseCorrect');
 Trial        TimeBin1     TimeBin2     TimeBin3
 1_easy       0.784        0.876        0.767
 34_easy      0.781        0.872        0.765
 35_easy      0.78         0.871        0.762
 ...etc       ...etc       ...etc       ....etc

I have tried using cut(), ddply() and some of the suggestions on this blog http://lamages.blogspot.co.uk/2012/01/say-it-in-r-with-by-apply-and-friends.html but haven't been able to find the correct code. I also tried this;
EasyTimeBin <- aggregate(PupilBaseCorrect ~ Trial + TrialTime[3000:8000, 8001:1300,1301:1800], data=EasyScaled, mean)

But got the following error;
Error in TrialTime[3000:8000, 8001:1300, 1301:1800] :
incorrect number of dimensions

Any suggestions or advice would be much appreciated.

A: Good use of cut and ddply are correct, but here's some vanilla R chicken scratch that will do what you need.
# Generate example data
EasyScaled <- data.frame(
  Trial = paste0(c(sapply(1:3, function(x) rep(x, 9))), "_easy.wav"),
  TrialTime = c(sapply(seq_len(9)-1, function(x) (floor(x/3))*5000 + x%%3 + 3000)),
  PupilBaseCorrect = rnorm(27, 0.78, 0.1)
)

# group means of PupilBaseCorrect by Trial + filename
tmp <- tapply(EasyScaled$PupilBaseCorrect,
    paste0(EasyScaled$Trial, ',',
           as.integer((EasyScaled$TrialTime - 3000)/5000)+1), mean)

# melt & recast the array manually into a dataframe
EasyTimeBin <- do.call(data.frame,
   append(list(row.names = NULL,
               Trial = gsub('.wav,.*','',names(tmp)[3*seq_len(length(tmp)/3)])),
     structure(lapply(seq_len(3),
         function(x) tmp[3*(seq_len(length(tmp)/3)-1) + x]
       ), .Names = paste0("TimeBin", seq_len(3))
     )
   )
)

print(EasyTimeBin)
#  Trial   TimeBin1  TimeBin2  TimeBin3
# 1 1_easy 0.7471973 0.7850524 0.8939581
# 2 2_easy 0.8096973 0.8390587 0.7757359
# 3 3_easy 0.8151430 0.7855042 0.8081268