text:
Q: adjusting the drawn object in map automatically using leaflet 'Geojson' property 'getbound' I am using leaflet in my project for displaying objects and elements in map (Open source map). I have drawn some objects in my map using Geojson styles
While using Geojson with the leaflet js implementation I am not able to use getBounds option properties.
But normally if I am not using Geojson and its features I am able to use this option getBounds mentioned below.
var group = new L.featureGroup([marker, circle, polygon, rectangle]);
//alert(group);
map.fitBounds(group.getBounds());

My set view code:
var map = L.map('map').setView([39.75621, -104.99404], 13);

Whenever a page loaded it should find the objects and draw elements (trace components) and adjust its Zooming.
Jsfiddle


text:
Q: form.validate_on_submit() doesn't work(nothing happen when I submit a form) I'm creating a posting blog function for social media website and I'm stuck on a problem: when I click on the "Post" button(on create_post.html), nothing happens.
In my blog_posts/views.py, when form.validate_on_submit(), the data the users filled in should be saved and then he or she will be redirected through a route toward index.html.
However, by running the website, nothing happened. Strangely, there is no error that happened.
Here is code for my blog_post/views.py:
@blog_posts.route('/create', methods=['GET', 'POST'])
@login_required
def create_post():
    form = BlogPostForm()

    if form.validate_on_submit():

        blog_validated = BlogPost(problem_name=form.problem_name.data,
                                  text=form.text.data,
                                  user_id=current_user.id
                                  )
        db.session.add(blog_validated)
        db.session.commit()
        flash('Blog Post Created')
        return redirect(url_for('core.index'))

    return render_template('create_post.html', form=form)

Here is my code for my forms.py that have the form I use for my template (create_post.html):
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField
from wtforms.validators import DataRequired

class BlogPostForm(FlaskForm):
    problem_name = StringField('Problem Name', validators=[DataRequired()])
    text = TextAreaField('Text', validators=[DataRequired()])
    problem_submit = SubmitField("Post")

Here is my code for the template(create_post.html):
{% extends "base.html" %}

{% block content %}

<form method="POST" >
    {{ form.hidden_tag() }}
    {{ form.problem_name.label(class="form-control-label") }} {{ form.problem_name(class="form-group form-control") }}

    {{ form.text.label }} {{ form.text(class="form-group form-control") }}

    {{ form.problem_submit.label(class="btn btn-secondary")}}
</form>

{% endblock %}

Here is my code for my model.py(database) incase you need to know something:
class BlogPost(db.Model):

    users = db.relationship(User)

    blog_id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer,db.ForeignKey('users.id'), nullable=False) #users.id  is taken from the tablename(users) and id in its table
    date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)  #Automatically post the time of the post
    problem_name = db.Column(db.String(140), nullable=False)
    text = db.Column(db.Text, nullable=False)

    def __init__(self, text, problem_name, user_id):
        self.text = text
        self.problem_name = problem_name
        self.user_id = user_id

    def __repr__(self):
        return f"Post ID: {self.post_id} -- Date:{self.date}---{self.problem_name}"

This is the terminal when I click the post button:

P.s/ After I looked at my code, I think that there is a high possibility I didn't connect my views with my database(BlogPost.db.Model). I'm a student and no one in my school can help me(even my computer science teacher). If you could help me, I would greatly appreciate!! Thank you!!
And if you need more information, please ask me!

A: I solved the bug!!!!!!!! {{form.problem_submit.label(class="btn btn-secondary")}} should had been {{form.problem_submit(class="btn btn-secondary")}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delphi -- Show images without download
Possible Duplicate:
How to get images from URL in Delphi

I'm using Delphi 2010,with some functions i can download and show JPG or PNG pictures in cximage or image object in a form, but i'm trying to do without download the picture to hard drive,i was wondering is that possible ? I searched via google & stackoverflow but couldn't find, all samples are about the download the file.
For example,i added an cximage1 to my form and want to show an picture from an url like "http://www.someaddress.com/pictures/001.JPG".
Thanks for all helps,and sorry for bad English :)

A: You can use this function (compiled and tested using Delphi 2010) to download a file over HTTP and store it in a TBitMap. It'll read all file types that have a registered support in Delphi's TGraphic hiearachy, and will auto-detect BMP, GIF, JPG and PNG file formats:
USES Graphics, IdHTTP, PngImage, jpeg, GIFImg;

FUNCTION DownloadImage(CONST URL : STRING ; ImageType : TGraphicClass = NIL) : TBitMap;
  VAR
    HTTP        : TIdHttp;
    S           : TStream;
    IMG         : TGraphic;
    STR         : AnsiString;

  BEGIN
    HTTP:=TIdHttp.Create(NIL);
    TRY
      S:=TMemoryStream.Create;
      TRY
        HTTP.Get(URL,S);
        IF NOT Assigned(ImageType) THEN BEGIN
          S.Position:=0;
          SetLength(STR,5);
          S.Read(STR[1],LENGTH(STR));
          IF COPY(STR,1,2)='BM' THEN
            ImageType:=TBitMap
          ELSE IF COPY(STR,1,3)='GIF' THEN
            ImageType:=TGIFImage
          ELSE IF COPY(STR,2,3)='PNG' THEN
            ImageType:=TPngImage
          ELSE IF (ORD(STR[1])=$FF) AND (ORD(STR[2])=$D8) THEN
            ImageType:=TJPEGImage
        END;
        IF NOT Assigned(ImageType) THEN RAISE EInvalidImage.Create('Unrecognized file format!');
        IMG:=ImageType.Create;
        TRY
          S.Position:=0;
          IMG.LoadFromStream(S);
          Result:=TBitMap.Create;
          TRY
            Result.Assign(IMG)
          EXCEPT
            Result.Free;
            RAISE
          END
        FINALLY
          IMG.Free
        END
      FINALLY
        S.Free
      END
    FINALLY
      HTTP.Free
    END
  END;

If you already know the file type, you can specify it as the 2nd parameter as either TGifImage, TPngImage, TJPegImage or TBitMap. If not, the routine will try to auto-detect it among these four types. If you use a custom-graphic type, you'll need to specify it as the 2nd parameter or update the auto-detection logic to detect it.
So, if you want to use it to display a downloaded image in a TImage without saving it to disc, you can use it thus:
  VAR
    BMP : TBitMap;

  BEGIN
    BMP:=DownloadImage('http://domain.com/image.jpg');
    TRY
      Image1.Picture.Assign(BMP)
    FINALLY
      BMP.Free
    END
  END;


text:
Q: TypeError: add(): argument 'other' (position 1) must be Tensor, not numpy.ndarray I am testing a ResNet-34 trained_model using Pytorch and fastai on a linux system with the latest anaconda3. To run it as a batch job, I commented out the gui related lines. It started to run for a few hrs, then stopped in the Validation step, the error message is as below.
...
^M100%|█████████▉| 452/453 [1:07:07<00:08,  8.75s/it,
loss=1.23]^[[A^[[A^[[A

^MValidation:   0%|          | 0/40 [00:00<?, ?it/s]^[[A^[[A^[[ATraceback
(most recent call last):
  File "./resnet34_pretrained_PNG_nogui_2.py", line 279, in <module>
    learner.fit(lr,1,callbacks=[f1_callback])
  File "/project/6000192/jemmyhu/resnet_png/fastai/learner.py", line 302,
in fit
    return self.fit_gen(self.model, self.data, layer_opt, n_cycle,
**kwargs)
  File "/project/6000192/jemmyhu/resnet_png/fastai/learner.py", line 249,
in fit_gen
    swa_eval_freq=swa_eval_freq, **kwargs)
  File "/project/6000192/jemmyhu/resnet_png/fastai/model.py", line 162, in
fit
    vals = validate(model_stepper, cur_data.val_dl, metrics, epoch,
seq_first=seq_first, validate_skip = validate_skip)
  File "/project/6000192/jemmyhu/resnet_png/fastai/model.py", line 241, in
validate
    res.append([to_np(f(datafy(preds), datafy(y))) for f in metrics])
  File "/project/6000192/jemmyhu/resnet_png/fastai/model.py", line 241, in
<listcomp>
    res.append([to_np(f(datafy(preds), datafy(y))) for f in metrics])
  File "./resnet34_pretrained_PNG_nogui_2.py", line 237, in __call__
    self.TP += (preds*targs).float().sum(dim=0)
TypeError: add(): argument 'other' (position 1) must be Tensor, not
numpy.ndarray

The link for the original code is
https://www.kaggle.com/iafoss/pretrained-resnet34-with-rgby-0-460-public-lb
lines 279 and 237 in my copy are shown below:
226 class F1:
227     __name__ = 'F1 macro'
228     def __init__(self,n=28):
229         self.n = n
230         self.TP = np.zeros(self.n)
231         self.FP = np.zeros(self.n)
232         self.FN = np.zeros(self.n)
233
234     def __call__(self,preds,targs,th=0.0):
235         preds = (preds > th).int()
236         targs = targs.int()
237         self.TP += (preds*targs).float().sum(dim=0)
238         self.FP += (preds > targs).float().sum(dim=0)
239         self.FN += (preds < targs).float().sum(dim=0)
240         score = (2.0*self.TP/(2.0*self.TP + self.FP + self.FN + 1e-6)).mean()
241         return score

276 lr = 0.5e-2
277 with warnings.catch_warnings():
278     warnings.simplefilter("ignore")
279     learner.fit(lr,1,callbacks=[f1_callback])

Could anyone have a clue for the issue?
Many thanks,
Jemmy

A: Ok, the error seems be for the latest pytorch-1.0.0, when degrade pytorch to pytorch-0.4.1, the code seems work (passed the error lines at this point). Still have no idea to make the code work with pytorch-1.0.0

A: I have had the same issue with this Kaggle kernel. My workarounds are the following:
1st option: In the F1 __call__ method convert preds and targs from pytorch tensors to numpy arrays;
2nd option: Initialise TP/FP/FN with pytorch tensors instead of numpy arrays, i.e. replace np.zeros(self.n) with torch.zeros(1, self.n).
Basically, the main idea - all variables should be of the same type.

A: Check your input data parameter.
Make sure it is in 123123 not in [123123]


text:
Q: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security] I am developing my first application in spring security. My applicationContext-security.xml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  -  Namespace-based OpenID configuration
  -->

<b:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:b="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <http>
        <intercept-url pattern="/**" access="ROLE_USER"/>
        <intercept-url pattern="/index.xhtml*" filters="none"/>
        <logout/>
        <openid-login login-page="/index.xhtml" authentication-failure-url="/index.xhtml?login_error=true">
            <attribute-exchange>
                <openid-attribute name="email" type="http://schema.openid.net/contact/email" required="true" count="2"/>
                <openid-attribute name="name" type="http://schema.openid.net/namePerson/friendly" />
            </attribute-exchange>
        </openid-login>
        <remember-me token-repository-ref="tokenRepo"/>
    </http>

    <b:bean id="tokenRepo"
            class="org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl" />

    <authentication-manager alias="authenticationManager"/>

    <user-service id="userService">
        <user name="http://user.myopenid.com/" authorities="ROLE_SUPERVISOR,ROLE_USER" />
    </user-service>

</b:beans>

and Web.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

    <display-name>Spring Security OpenID Demo Application</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext-security.xml
        </param-value>
    </context-param>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/log4j.properties</param-value>
    </context-param>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>openid.root</param-value>
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
     <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Clean and Build of the application is successful, but when I try to deploy the application jetty 7 gives me following error:

SEVERE: Context initialization failed
  org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]
  Offending resource: ServletContext resource [/WEB-INF/applicationContext-security.xml]
  at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
  at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
  at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)

Tried everything but can't solve this error. Any help would be appreciated.
EDIT
I tried added 3.0.2 version of the Spring-Security and got this:

Context initialization failed
  org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 13 in XML document from ServletContext resource [/WEB-INF/applicationContext-security.xml] is invalid;
  nested exception is org.xml.sax.SAXParseException; lineNumber: 13; columnNumber: 11; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'http'.
      at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
      at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334

A: You need a spring-security-config.jar on your classpath.
The exception means that the security: xml namescape cannot be handled by spring "parsers". They are implementations of the NamespaceHandler interface, so you need a handler that knows how to process <security: tags. That's the SecurityNamespaceHandler located in spring-security-config

A: I had the same problem. The only thing that solved it was merge the content of META-INF/spring.handler and META-INF/spring.schemas of each spring jar file into same file names under my META-INF project.
This two threads explain it better:

*

*maven assembly plugin and spring namespace handlers

*Thread: unable to locate Spring NamespaceHandler for XML schema namespace

A: In my case, this was caused by custom manifest entries added by the maven-jar-plugin.
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <archive>
            <index>true</index>
            <manifest>
                <addClasspath>true</addClasspath>
            </manifest>
            <manifestEntries>
                <git>${buildNumber}</git>
                <build-time>${timestamp}</build-time>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>

Removing the following entries fixed the problem
<index>true</index>
<manifest>
    <addClasspath>true</addClasspath>
</manifest>


text:
Q: Python 3.6 Bittrex API INVALID_SIGNATURE I am not a developer by trade, so please go easy on me.
I have been working on a Bittrex API as a way of teaching myself Python and API's. I managed to get it working in PHP with a lot of Stack Overflow searches before switching to Python 3.6. Now I am stuck again on a portion that requires hashing and signatures.
My functional PHP code:
<?php

$apikey='...';
$apisecret='...';
$nonce=time();
$uri='https://bittrex.com/api/v1.1/account/getbalance?
$apikey='.$apikey.'&nonce='.$nonce.'&currency=BTC';
$sign=hash_hmac('sha512',$uri,$apisecret);
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$execResult = curl_exec($ch);
$data=curl_exec($ch);

echo $data

?>

Python equivalent:
import urllib.request
import json
import collections
import time
import hashlib
import hmac
nonce = str('{:10.0f}'.format(time.time()))
apikey = '...'
apisecret = '...'
BaseCurrency = 'BTC'
url = 'https://bittrex.com/api/v1.1/account/getbalance?
apikey='+apikey+'&nonce='+nonce+'&currency='+BaseCurrency
sign = hmac.new(b'apisecret', b'url', hashlib.sha512).hexdigest()
request = urllib.request.Request(url, headers={"apisign" : sign})
balance = json.load(urllib.request.urlopen(request))

print(balance)

This returns {'success': False, 'message': 'INVALID_SIGNATURE', 'result': None}.
I have spent a couple days on this and have not been able to get passed it. Any help would be appreciated.

A: You must use
apikey = b'...'
apisecret = b'...'

instead of
apikey = '...'
apisecret = '...'

and
sign = hmac.new(apisecret, url, hashlib.sha512).hexdigest()

instead of
sign = hmac.new(b'apisecret', b'url', hashlib.sha512).hexdigest()

A: I know this is quite old but I struggled a bit before handling the connexion, here is my code :
api_secret='...'
api_key='...'
url='https://bittrex.com/api/v1.1/account/getbalances?apikey='+api_key+'&nonce='+str(time.time())
sign=hmac.new(bytes(api_secret,encoding='utf-8'),bytes(url,encoding='utf-8'),hashlib.sha512).hexdigest()

req = urllib.request.Request(url, headers={"apisign" : sign})
account=urllib.request.urlopen(req).read()
account_j=json.loads(account)

print(account_j)

I had to read() the request once opened so that the json was correctly handled.


text:
Q: Spring OAuth2 Client grant_type=password example I am looking for a Spring OAuth2 Client example that uses grant_type=password. I know how it works in Postman and I have Authorization Server and Resource server setup working with Postman. I can't find any samples for Spring OAuth2 Client using the password grant. Can anyone point me to the right direction?

A: I was able to find an example of authorization_code flow so closing this question
Here is tutorialspoint link


text:
Q: Harmonic mean of false positive and false discovery rates (analogous to F1) F1 is the harmonic mean of recall (aka sensitivity, or true positive rate, TPR) and precision (aka positive predictive value, PPV).

*

*$\text{TPR} = \text{Pr(predicted:Pos | Pos)} =$ TP/P   (wikipedia notation)

*$\text{PPV} = \text{Pr(Pos | predicted:Pos)} =$ TP/PP

Is there a name for the harmonic mean of the false positive rate (FPR) and false discovery rate (FDR)?
They are quite similar:

*

*$\text{FPR} = \text{Pr(predicted:Pos | Neg)} =$ FP/N

*$\text{FDR} = \text{Pr(Neg | predicted:Pos)} =$ FP/PP

Note the cross-symmetry (they're both Bayes couples).
Using the mean of those two as a summary measure for "wrong detections" seems reasonable to me, just as F1 is a summary of correct detections.

The below section would be in a collapsed <details> block (if stackoverflow supported it).
Something even more analogous to F1 would be the mean of the true negative rate and the negative predictive value:

*

*$\text{TNR} = \text{Pr(predicted:Neg | Neg)} =$ TN/N

*$\text{NPV} = \text{Pr(Neg | predicted:Neg)} =$ TN/PN

Like recall (TPR) and precision (PPV), these measure are ideally 1, while the false positive and false discovery rates are ideally 0.
But I find it easier to think about "wrong detections" than "correct non-detections".
For completeness:
The two measures not listed yet, false negative rate and false omission rate:

*

*$\text{FNR} = \text{Pr(predicted:Neg | Pos)} =$ FN/P

*$\text{FOR} = \text{Pr(Pos | predicted:Neg)} =$ FN/PN

Complements:
$(\text{TPR} + \text{FNR}) = (\text{PPV} + \text{FDR}) = (\text{TNR} + \text{FPR}) = (\text{NPV} + \text{FOR}) = 1$
These cut across the above Bayes couples. E.g. $\text{PPV} = 1 - \text{FDR}$, but $\text{FPR} = 1 - \text{TNR}$.


text:
Q: "Is himself in?" What does it mean? Context - A stranger knocks on your door and asks "Is himself in?"

himself, a reflexive pronoun, here seems to be used for a nominative pronoun.

A: This is a common expression in Irish English. A podcast from the Minnesota Public Radio site describes its use and origin, citing Brian Ó Broin of the English department at William Paterson University in New Jersey:

Ó Broin explains that in Irish English, the two normally reflexive pronouns himself and herself can be used nominatively—that is, they can be used to indicate the subject of a sentence or even with the verb to be. "So you can say things like 'It's herself' or 'Is himself in?'" Ó Broin says.
Ó Broin clarifies that himself and herself can often be used to refer to somebody of importance, or at least somebody of importance to both the speaker and the listener in the conversation, and that there's a clear understanding between the speaker and listener who is being spoken about. "For example, my sister is in hospital right now about to give birth to a baby," Ó Broin says. "So if I were to call her husband up and say, 'How's herself?' it would be absolutely understood that I'm not speaking about Michelle Obama or my mother. The person in question is my sister."
Ó Broin is quite certain this usage came out of Irish Gaelic. He says that Gaelic does not have a reflexive equivalent to English, but that when Irish people assemble a sentence that requires some sort of stress or an intensifier on the subject, they will use the Irish word, féin which means self. "So the Irish sentence, Sé féin atá ann, meaning 'It's him—that one,' becomes translated into Hiberno-English as 'It's himself,'" Ó Broin says. "So it's almost certain that Irish Gaelic is the origin of this phrase, 'It's himself.'"

In your example, the stranger is almost certainly asking to speak with the master of the house.


text:
Q: Passing an expression as a parameter I'm trying to build a generic GroupBy Method, I guess it should be something like this
var result = GenericGroupBy<List<DTO>>(dataList, g=>g.Id);

public object GenericGroupBy<T>(object data, Func<T, bool> groupByExpression)
{
    return ((List<T>)data).GroupBy(groupByExpression);
}

But I can not make it work.
How to pass expression like g=>g.Id?

A: Currently there are two problems:

*

*Your method expects a Func<T, bool> and I suspect g => g.Id fails that because your Id property isn't a bool

*You're currently specifying List<DTO> as the type argument, when I suspect you really want just DTO.

Given your comments, this will work:
var result = GenericGroupBy<DTO>(dataList, g => g.Id);

public object GenericGroupBy<T>(object data, Func<T, int> groupByExpression)
{
    return ((List<T>)data).GroupBy(groupByExpression);
}

... but I'd make it a bit more general unless you always want to group by int:
var result = GenericGroupBy<DTO, int>(dataList, g => g.Id);

public object GenericGroupBy<TElement, TKey>
    (object data, Func<TElement, TKey> groupByExpression)
{
    return ((IEnumerable<TElement>)data).GroupBy(groupByExpression);
}

Note how I've also changed the cast from List<T> to IEnumerable<T> - you don't need it to be a List<T>, so why cast to that?


text:
Q: Lens correction projection What is the simplest way to un-warp a photo made using fisheye or wide-angle lens? I'm looking a pixel projection formula that has few parameters. Camera and lens parameters will not be known, so user has to change the parameters visually. Thanks

A: There is a good paper here that provides some decent looking mathematical models for lens distortion. It's at least. SDX2000 was kind of on the right track with the grid I think. I think the most common way to approach the problem is to map the image to a grid and then allow warping parameters to be applied to produce pincushion and barrel distortion. See the lens distortion filters in Lightroom or Photoshop as an example.

A: There is an excellent discussion from ImageMagick. They give the equation that they use.
Note that this does not correct distortion in the same way as Photoshop CS6 (i.e. you cannot take coefficients from the Adobe lens profiles and simply chuck them in).
The paper that Kamil points to seems like an excellent in-depth look.

A: I would assume you could use the lens equation to do it.

1/f = 1/object_distance + 1/image_distance

Where f is the focal length (the user input). The ratio of image distance and object distance could be used to resize the image appropriately, using the magnification equation. To get what you really want, then, you need to restructure the equation:

1/object_distance = 1/f - 1/image_distance

And then use the magnification equation to use the object height to resize:

-image_distance/object_distance = image_height/object_height

The catch, as you may have noticed, is that you need to know the distance each pixel is away from the camera. Otherwise, it simply doesn't work. You could ask the user for that information, but that seems unlikely, and painful. I don't know of any other way to do it-- lens distortion is a 3D effect, and you're given 2D information. At best you can attempt to correct it two-dimensionally, but this will be difficult, and won't work properly.

A: If its possible you should ask the user to take a photograph of a reference image (a chess board for example) using the same camera and then use this information to analyze the lens characteristics. This information can then be used to un-warp the other photographs taken by the same camera.
For implementation you could use neural networks/genetic algorithms.


text:
Q: Handling a meta request with Ajax in Django I tried to research but couldn't find a way to handle META requests in Django with Ajax. Refreshing a page everytime kind of destroys the UX.
So if the code is something like this:
template
# of likes: {{ car.likes }}

views.py
def like_page(request):
    if 'id' in request.GET:
        id = request.GET['id']
        car = Cars.objects.get(id=id)
        car.likes += 1
        car.save()
    if 'HTTP_REFERER' in request.META:
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    return HttpResponseRedirect('/')

So the template sends the id of the object, and in the views it increments the like by 1. everytime this happens.
Now the problem is that without Ajax it reloads the page everytime it happens.
I am a backend developer, so I have almost no experience with jQuery and Ajax, so I have no clue how to approach this problem.
Any help would be appreciated. Thanks :)

A: The way to do this is do apply progressive development - make non-js work, and then on top of that make enhancements using ajax or whatever other client technologies you want.
Django request has is_ajax (docs) method which is very useful for progressive development. The idea is that when the request is non-ajax, do whatever you did before, however if it is ajax, return the like counter so that js can update the page:
def like_page(request):
    if 'id' in request.GET:
        id = request.GET['id']
        car = Cars.objects.get(id=id)
        car.likes += 1
        car.save()

    if not request.is_ajax():
        if 'HTTP_REFERER' in request.META:
            return HttpResponseRedirect(request.META['HTTP_REFERER'])
        else:
            return HttpResponseRedirect('/')
    else:
        data = {
            'likes': car.likes
        }
        json_data = json.dumps(data)
        return HttpResponse(json_data, content_type='application/json')

Please note that this returns json data back. This is very useful because it is easily extensible in the future in case you have to return additional information.
Now for the js/jquery stuff:
Template

    # of likes:
    {{ car.likes }}

JS
$(document).ready(function () {
    $('#car_like').click(function(event) {
        event.preventDefault();
        var car_like = $(this),
            url = car_like.attr('href');
        $.getJSON(url, function(data) {
            $('#car_like_count', car_like).html(data.likes);
        });
        return false;
    });
});

This will overwrite the default behavior of the like anchor, and will send ajax request. Ajax request will return a new like counter for the car, which js will display in place of the old number. However if for some reason js is not supported, the default action will happen and the like anchor will still work.


text:
Q: Regarding Team api integration I am integrating teams api to schedule meeting,
use this api
https://graph.microsoft.com/v1.0/me/onlineMeetings
request
    {
"startDateTime":"2019-07-12T14:30:34.2444915-07:00",
"endDateTime":"2019-07-12T15:00:34.2464912-07:00",
"subject":"User Token Meeting",
"isBroadcast": true,
"broadcastSettings": {
"allowedAudience": "everyone",
"isRecordingEnabled": true,
"isAttendeeReportEnabled": true
}
}

Getting response
    {
"error": {
"code": "MethodNotAllowed",
"message": "An error has occurred.",
"innerError": {
"date": "2021-05-07T10:24:58",
"request-id": "17e3655e-158d-44c2-bb92-3a6b2ff3951d",
"client-request-id": "17e3655e-158d-44c2-bb92-3a6b2ff3951d"
}
}
}

Please help me to solve this issue

A: broadcastSettings were not available for V1.0 so, try using with beta version. Check this doc for more info.


text:
Q: Change Windows installation to UEFI I bought a HP 240 G6 laptop with a 32Gb drive. Opened it up to install a 240Gb SSD and the first surprise: there was no drive in the laptop; the drive bay where I installed the 240Gb SSD was empty.
First problem: In the BIOS or in boot options I could not find a way to boot from the newly installed drive. Then I installed Ubuntu 20.04 on the internal 32Gb drive. The device is /dev/mmcblk0. I guess that means it's recognized as an SD card; I couldn't find it though examining the mainboard. Anyway, I couldn't get grub to boot the newly installed drive either. I could mount it though.
Then I read about MBR and UEFI being incompatible. And now it dawns on me: The fact that I can't choose the drive to boot from, does that mean I have an UEFI only laptop?
The new 240GB drive has Windows 10 installed. I investigated the small partitions on that drive and found no EFI folder. So I guess, that Windows installation is in MBR mode. Is it possible to update the Windows installation to UEFI? Or do I have to reinstall Windows?

A: You're experiencing this because of how Legacy and Secure Boot are set. If you change this setting, it should work.
Do note that they are 2 different mechanisms of access, so you may have to reinstall any OS so they see each other, and may also have to repartition disks.


text:
Q: PLSQL query to search through table type I have declared the following types in a package.
TYPE l_task_type_rec is record (task_id number, creation_date date);

TYPE tas_tab is table of l_task_type_rec;

l_task_rec tas_tab;

I am trying to use a for loop to iterate through the objects in the table type objects like this. I am not sure if it is possible.
for counter in l_task_rec.first ..l_task_rec.last

loop

    select task_id into l_task_id from l_task_rec where rowid = counter;

    select location_id into p_location_id from csf_ct_tasks where task_id = l_task_id;

    OPEN c_location_rec (p_location_id);

                    FETCH c_location_rec

                    BULK COLLECT INTO x_location_rec;

     CLOSE c_location_rec;

end loop;

What I want is to call a cursor from inside the for loop so that I can get a list of all the locations one by one and fetch and store all the data in a record type. I know the query to search the table type is wrong because it says the table or view l_task_rec does not exist! Can anyone tell me what I am doing wrong here or point me in the right direction? Thanks in advance..

A: Here is an example of how you can iterate through objects in the table type:
declare
  l_task_rec tas_tab;
  p_location_id number;//Assuming number
begin
  --Example data
  l_task_rec:=tas_tab( l_task_type_rec (10, sysdate), l_task_type_rec (21, sysdate), l_task_type_rec (35, sysdate));--This should come from somewhere else

  for counter in l_task_rec.first .. l_task_rec.last
  loop
    --You can get the data like this
    DBMS_OUTPUT.PUT_LINE('TASK_ID: '||l_task_rec(counter).TASK_ID);
    DBMS_OUTPUT.PUT_LINE('CREATION_DATE: '||l_task_rec(counter).CREATION_DATE);

    select location_id into p_location_id from csf_ct_tasks where task_id = l_task_rec(counter).TASK_ID;
   --More code
   --OPEN  ...
   --CLOSE ...
  end loop;
end;

In order for this to work, I changed how l_task_type_rec type is created:
create TYPE l_task_type_rec is object (task_id number, creation_date date)


text:
Q: Given user-inputted data, match up their fields to fields in my database When the user uploads a spreadsheet with headers, I parse it into JSON. Then, I need to match their fields with the fields in my database. For example, if they uploaded a fname and lname field, I'd recognize those, and concatenate them into the full name field in my database.
My idea is to write patterns based on regex, column name, and column position. For example, a Last Name has a header name that probably starts with "Last" or at least "L". The values probably have a regex pattern of [a-zA-Z]{2,20} and the previous column's values (presumably first name) probably follows the same regex pattern. I'll keep my regex pattern simple & scan a sample of the records to rule out edge cases like "Jo Ann O'hoolihan".
Does this approach sound reasonable? Has anyone already created something similar? Of course, I'll have the user confirm that the algorithm guessed correctly, but I find it strange how little information I've found googling about the pattern. Any ideas, comments, or sources welcome!

A: You could try something like this:
var fieldName = "First Name", dbColumn = "FName", s1, s2;
fieldName.length < dbColumn.length ? (s1 = fieldName, s2 = dbColumn ) : (s1 = dbColumn, s2 = fieldName); // (s1 must be the shorter string)
RegExp(s1.split("").join("(.*?)"), 'gi').test(s2);

After making s1 the shorter string, have each character match across the target.
In this example, given a JSON property named "First Name", "F Name", "FName", or even "F-NAME", "First N", "FN", etc., it will match to database name "FName".


text:
Q: remove php extension using .htaccess I'm working on script, and want to set links to be as following:
www.mysite.com/sign-up.php
to
www.mysite.com/sign-up

and
www.mysite.com/profile.php?username=abc
to
www.mysite.com/profile/abc

I found this code and works for me.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [L,QSA]

but when I want to access:
www.mysite.com/profile/abc

The stylesheet doesn't work, it seems the path for it has changed. Also all links in that profile become like:
www.mysite.com/profile/profile/filename.php
It keeps adding /profile everytime
how to fix this?
EDIT: all files works fine with stylesheet except profile.php

A: You can create it with htacess and modrewrite of apache.
Just check the link below for generating dynamic URL. It might solve your problem:
URL Generation

A: Have you tried this?
RewriteRule ^(.*)$ $1.php

Just replace you current rule with this one

A: www.mysite.com/sign-up.php to www.mysite.com/sign-up
   RewriteEngine on
   RewriteRule ^(.*)$ $1.php [r=301,L]

It is required to store this file to folder www.mysite.com/profile/.htaccess
   RewriteEngine on /profile/
   RewriteRule ^(.*)$ profile.php?username=$1 [r=301,L]

www.mysite.com/profile/abc to www.mysite.com/profile/profile.php?username=abc
The problem is that, first script will redirect string to string.php so www.mysite.com/profile/abc to www.mysite.com/profile/abc.php or www.mysite.com/profile/profile.php?username=abc.php. We must create an exception:
   RewriteEngine on
   RewriteRule ^profile/(.*)$ profile.php?username=$1 [r=301,L]
   RewriteRule ^(.*)$ $1.php [r=301,L]

We can create the whole script as an exception. This will simple do all the work.

A: This isn't a problem with your rewrite rules, it's a problem with your href's.
If you have a style tag like... <link rel="stylesheet" type="text/css" href="css/main.css" media="screen" /> and an a tag like <a href="profile">, they will be treated as relative URLs since there is no forward slash at the start. If your browser is at /profile.php, it will load /css/main.css and the link goes to /profile, but once you are at /profile, the browser thinks you are in that "folder", so it will now look at /profile/css/main.css and your link will go to /profile/profile. You need to make the href's absolute paths, i.e. href="/css/main.css" and href="/profile".

A: If your CSS link is broken amongst other things, try using the base tag in your document head:
<head>
<base href="http://www.mysite.com/" />
</head>

I have found this to work when dealing with pesky URL rewrites.
There may be better ways to solve it via .htaccess, but this might be a nice short term fix until that happens.


text:
Q: Recurrence relation of Chebyshev nodes Doing a few practice questions, I came across a proof based question. How would one go around to solve this?
"Prove the following recurrence relation:"
$\frac{d}{dx}T_{n+1}(x)=(n+1)T_n(x)+\frac{n+1}{n}x\frac{d}{dx}T_n(x)$
for $n=1,2,3...$


text:
Q: how to convert list type to double? i have a list called cusList which consists of only one value which is a number,i want to convert this list to double data-type and assign it to a variable?how do i do it?

A: What is the langue?
In C# it would be:
double d = (double)cusList[0];

In VB it would be:
Dim d As Double = cusList(0)


text:
Q: The Laurent series of $ g(z)=\frac{z^n+z^{-n}}{z^2-(a+\frac{1}{a})z+1}$ How to find Laurent series of g(z) ?
$$  g(z)=\frac{z^n+z^{-n}}{z^2-(a+\frac{1}{a})z+1} \hspace{10mm}   \begin{cases} n \in N    \\
0<a<1   \end{cases}   $$
answer is :
$$  g(z)=\sum_{p=-n}^{n+1}\frac{1}{a^{p+n}}.\frac{1-a^{2p+2+2n}}{1-a^2}z^p + \sum_{p=n}^{+ \infty} \frac{1}{a^{p+n}} . \frac{(a^{2n}+1)(1-a^{2p+2})}{1-a^2} z^p \hspace{10mm} (i)$$
I can't understand how .
I try to solve, but I can't Please help me. Thank you so much. if Numerator was 1 :
$$  f(z)=\frac{1}{z^2-(a+\frac{1}{a})z+1} $$
$$ z^2-(a+\frac{1}{a})z+1=0 \rightarrow \begin{cases} z_1=a    \\
z_2=\frac{1}{a}   \end{cases} $$
$$  f(z)=\frac{1}{(z-a)(z-\frac{1}{a})}=\frac{\frac{1}{a-\frac{1}{a}}}{z-a}+\frac{\frac{-1}{a-\frac{1}{a}}}{z-\frac{1}{a}} $$
we know:
$$ (a+b)^n =a^n+\frac{n}{1!}a^{n-1}b+\frac{n(n-1)}{2!}a^{n-2}b^2+...+b^n$$
As regards $$ |a|<1 $$
Taylor series of f(z) is:
$$  f(z)=\frac{\frac{1}{a-\frac{1}{a}}}{z-a}+\frac{\frac{1}{a-\frac{1}{a}}}{\frac{1}{a}-z}=(\frac{1}{a-\frac{1}{a}}) \left[ \frac{-\frac{1}{a}}{1-\frac{z}{a}}+\frac{a}{1-az} \right]$$
$$ f(z)=(\frac{1}{a-\frac{1}{a}}) \left[ \frac{-1}{a} \sum_{n=0}^{\infty}(\frac{z}{a})^n+a \sum_{n=0}^{\infty} (az)^n \right] $$
$$  f(z)=\sum_{p=o}^{\infty} \frac{(1-a^{2p+2})}{a^p(1-a^2)}z^p $$
now if consider
$$ g(z)=(z^n+z^{-n}) f(z) $$
we have :
$$  g(z)=(z^n+z^{-n}) \sum_{p=o}^{\infty} \frac{(1-a^{2p+2})}{a^p(1-a^2)}z^p $$
$$  g(z)= \sum_{p=o}^{\infty} \frac{(1-a^{2p+2})}{a^p(1-a^2)}z^{p+n} + \sum_{p=o}^{\infty} \frac{(1-a^{2p+2})}{a^p(1-a^2)}z^{p-n}  \hspace{10mm} (ii) $$
I can't understand how (ii) transformed to (i) $$$$
Edit :
(thanks to Hurkyl) if apply the Change of variables , we have:
$$ p \rightarrow p-n \space for  \space first \space  \sum  \space  and  \space p \rightarrow p+n \space  for \space  second  \space \sum  $$
$$ g(z)= \sum_{p-n=o}^{\infty} \frac{(1-a^{2(p-n)+2})}{a^{p-n}(1-a^2)}z^{p-n+n} + \sum_{p+n=o}^{\infty} \frac{(1-a^{2(p+n)+2})}{a^{p+n}(1-a^2)}z^{p+n-n}  $$
$$ g(z)= \sum_{p=n}^{\infty} \frac{(1-a^{2p-2n+2})}{a^{p-n}(1-a^2)}z^{p} + \sum_{p=-n}^{\infty} \frac{(1-a^{2p+2n+2})}{a^{p+n}(1-a^2)}z^{p}  $$
$$ g(z)= \sum_{p=n}^{\infty} \frac{(1-a^{2p-2n+2})}{a^{p-n}(1-a^2)}z^{p} +  \left[ \sum_{p=n}^{\infty} \frac{(1-a^{2p+2n+2})}{a^{p+n}(1-a^2)}z^{p} +\sum_{p=-n}^{n-1} \frac{(1-a^{2p+2n+2})}{a^{p+n}(1-a^2)}z^{p}\right] $$
$$ \sum_{-n}^{\infty}=\sum_{-n}^{n-1}+\sum_{n}^{\infty} $$
$$ g(z)=\sum_{p=n}^{\infty}\frac{a^{p+n}(1-a^{2(p-n)+2})+a^{p-n}(1-a^{2(p+n)+2})}{a^{p+n}(1-a^2)a^{p-n}}z^p  +\sum_{p=-n}^{n-1} \frac{(1-a^{2p+2n+2})}{a^{p+n}(1-a^2)}z^{p}$$
$$ g(z)=\sum_{p=n}^{\infty} \frac{(a^{2n}+1)(1-a^{2p+2})}{a^{p+n}(1-a^2)}z^p+\sum_{p=-n}^{n-1} \frac{(1-a^{2p+2n+2})}{a^{p+n}(1-a^2)}z^{p} $$
now difference between my answer and book is:
$$ my \space answer : \rightarrow g(z)=\sum_{n}^{\infty}+\sum_{-n}^{\color{red}{n-1}} $$
$$ book \space answer : \rightarrow g(z)=\sum_{n}^{\infty}+\sum_{-n}^{\color{red}{n+1}} $$
Please help me to understand where I am wrong

A: Assuming your work is right, the key idea you seem to be overlooking is
$$
\begin{align}
g(z) &= \sum_{p=o}^{\infty} \frac{(1-a^{2p+2})}{a^p(1-a^2)}z^{p+n} + \sum_{p=o}^{\infty} \frac{(1-a^{2p+2})}{a^p(1-a^2)}z^{p-n}
\\ &= \sum_{(p-n)=o}^{\infty} \frac{(1-a^{2(p-n)+2})}{a^{p-n}(1-a^2)}z^{(p-n)+n} + \sum_{(p+n)=o}^{\infty} \frac{(1-a^{2(p+n)+2})}{a^{p+n}(1-a^2)}z^{(p+n)-n}
\end{align}
$$


text:
Q: Clustering ranking I'm analyzing a data in R where predictor variables are available but there is no response variable. Using unsupervised learning (k-means) I have identified patterns in the data. But I need to rank the clusters according to their overall performance (example: student's data on exam marks and co-curricular marks). What technique do I use after clustering in R?

A: The cluster attribute of the kmeans output gives you the index of which cluster each data point is in. Example data taken from kmeans documentation:
nclusters = 5
# a 2-dimensional example
x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
           matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(x) <- c("x", "y")

cl <- kmeans(x, nclusters, nstart = 25)

Now, your evaluation function (e.g. mean of column values) can be applied to each cluster individually:
for (i in 1:nclusters){
    cat(i, apply(x[which(cl$cluster==i),],MARGIN=2,FUN=mean), '\n')
}

Or better still, use some kind of aggregation function, e.g. tapply or aggregate, e.g.:
aggregate(x, by=list(cluster=cl$cluster), FUN=mean)

which gives
  cluster          x          y
1       1  1.2468266  1.1499059
2       2 -0.2787117  0.0958023
3       3  0.5360855  1.0217910
4       4  1.0997776  0.7175210
5       5  0.2472313 -0.1193551

At this point you should be able to rank the values of the aggregation function as needed.


text:
Q: 100vh adding space at the bottom from anterior sibling I'm trying to make a very simple page, but I'm pulling my hair off trying to find a solution for the layout.
What I want to achieve is a simple header and below, some content ( I don't know the actual height of it, but won't probably cover the full height of the viewport) with a full background cover image that covers the remaining height.
I tried using 100vh on the container that's going to hold the content, but as you can see in the codepen: http://codepen.io/renttless/pen/vGvzRj , it creates a scrollbar apparently the size of the previous sibling, which will be the header.
Here's the code:

Home

Who are we

Our work

Contact

I'm a full size h1

I'm some paragraph

CSS:
    html,body{
  height: 100%;
}
.sectionTest .backgroundTest{
    background-color:red;
    height:100vh;
}

A: This is a pain to do.  Maybe try using the flexbox approach. Here's an example.

Home

Who are we

Our work

Contact

I'm a full size h1

I'm some paragraph

CSS:
html,
body {
  height: 100%;
  margin: 0
}

.box {
  display: flex;
  flex-flow: column;
  height: 100%;
}

.box .row {
  border: 1px dotted grey;
  flex: 0 1 30px;
}

.box .row.header {
  flex: 0 1 auto;
  background-color: red;
}

.box .row.content {
  flex: 1 1 auto;
  background-color: green;
}

A: If you add a background to your header and move the 100vh to the html element it will solve your problem

    html{
        background-color:red;
        height:100vh;
    }
    header{
      background: white;
    }
    body, header ul{
      margin: 0;
    }

Home

Who are we

Our work

Contact

I'm a full size h1

I'm some paragraph


text:
Q: setState() in React not updating state onClick Switch (antd) When we click on the switch the state "valueState" does not update I don't know why ??
Also, I have a "statusValue" type problem because "switch antd" accepts boolean by cons initial value of props is of type number
Here is the code I am using :
//Code//
import React from 'react';
import { Form, Input, Switch } from "antd";
class UpdateCard extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        valueState: this.props.state.status,
    }
}

handleToggle = (checked) => {
    console.log("state",this.state.valueState);
    console.log("checked",checked);
   if (checked === false){
    this.setState({
        valueState:1
      });
   }else {
    this.setState({
        valueState:0
      });
   }
    console.log("handleToggle valueState",this.state.valueState);
  };

  render() {
    const { state } = this.props;

    var statusValue = false;

    if (state.status === 0) { statusValue = true; }
  return (
  <Form id='update-state-form'
            onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}
            initialValues={{
                name: state ? state.name : '',
                status: state ? state.status : false,
                color: state ? state.color :'',
            }}
        >
            <FormItem {...formItemLayout}
               name="name"
               label={<IntlMessages id="app.stateName" />}
               rules={[{ required: true, message: 'Please input the name !' }]}
            >
                <Input />
            </FormItem>

            <FormItem {...formItemLayout}
               name="color"
               label={<IntlMessages id="app.color" />}
               rules={[{ required: true, message: 'Please input the color !' }]}
            >
                <CirclePicker color={state.color} />
            </FormItem>

            <FormItem {...formItemLayout}
               name="status"
               label={<IntlMessages id="app.status" />}
               rules={[{ required: true, message: 'Please input the status !' }]}
            >
                <Switch  defaultChecked={statusValue}  onClick={this.handleToggle}/>
            </FormItem>
        </Form>
    );
}
}
export default connect(
 null,
  {
     updateStateCardAction,
  }
 )(UpdateCard );

//****************************** Show console.log  ******************************//

A: you need to pass the value also.
<Switch  defaultChecked={statusValue}  onClick={(statusValue) =>this.handleToggle(!statusValue)}/>

A: I feel you are missing on two main things here as long as I understood your problem :

*

*statusValue has not been declared in the state. And it should be a boolean value in the state. From documentation of Ant-Design defaultChecked prop is set false. First make sure you declare statusValue as state variable:
this.state = {
 valueState: this.props.state.status,
 statusValue:false
}

... // and keep state in sync with the UI

*Then you have to make sure to pass statusValue state in the onClick handler.
 <Switch
      defaultChecked={this.state.statusValue}
      onClick={()=>this.handleToggle(this.state.statusValue)}
  />

A: Here my solution

import React, { Component } from 'react';
import { Switch } from 'antd';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      onCheck: 0,
    };
  }

  componentDidUpdate() {
    const { onCheck } = this.state;
    console.log(onCheck);
  }

  handleToggle = (checked) => {
    const { onCheck } = this.state;

    if (checked) {
      this.setState({ onCheck: 1 });
    } else {
      this.setState({ onCheck: 0 });
    }
  };

  render() {
    const { onCheck } = this.state;
    return (
      <div className="App">
        <header className="App-header">
          <Switch defaultChecked={onCheck} onChange={this.handleToggle} />
        </header>
      </div>
    );
  }
}

export default App;
.App {
  text-align: center;
}

.App-header {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
}


text:
Q: conversion from string "" to 'date' is not valid vb.net I have following code
LastLeaveDt = DispName(con, "Select max(dtLeave) from EmpLeave where Empid='" & eid.Text & "' and year(dtleave)='" & cmbYear.Text & "'")

Public Function DispName(cn As ADODB.Connection, mQRY As String) As String
    Dim xrs1 As New ADODB.Recordset
    Try
        xrs1.Open(mQRY, cn, ADODB.CursorTypeEnum.adOpenForwardOnly)
        If xrs1.EOF = False Then
            DispName = IIf(IsDBNull(xrs1(0).Value), "", xrs1(0).Value)
        End If
        xrs1.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
        Return False
    End Try
End Function

In this code at run time it is giving me error "Conversion From String "" To 'Date' is not valid"

A: try to change your code as :
 If xrs1.EOF = False Then
        If IsDate (IsDBNull(xrs1(0).Value)) then
             DispName = xrs1(0).Value
         else
             DispName =""
        End If
   End If


text:
Q: Mach-Zehnder interferometer vs Michelson interferometer I am doing a project that is based on the Mach-Zehnder interferometer, and we're asked to compare the interferometer with Michelson's interferometer. I know the geometrical differences between the two, but when I think about it, I can't figure out when one is more suitable than the other. What are your thoughts?

A: As a direct consequence of their respective geometries, I believe that the main difference between the Michelson and Mach-Zehnder interferometers is that the latter can be used to probe a sample with light only passing a single time through it.
Cheers.

A: One of the difference between two,is that while in case of Michelson single output is obtained while in later two images are obtained with a phase of π.
This makes the mach zehnder interferometer more accurate in comparison to other


text:
Q: Using a Generic Class as Upper Bound of a Type Parameter I'm struggling with generic bounds for type parameters in Java. What I want to achieve is the following:

*

*I have a generic class (Generic<> (1) in the sample code)

*I have a generic class where the type parameter should scope over types of the first generic class (UsingGeneric<> (2); this is already strange, as it forces me to repeat the Comparable constraint)

*I then want to instantiate this second class with a third class (MyGeneric (3)) which extends a concrete application of the first class.

Think of it like this: You have a generic container class where the elements are constrained. You have a generic iterator class that scopes over such containers. Now you want to create a concrete iterator for a concrete container.
The problem: Statement (4) won't compile, complaining:
Type parameter MyGeneric is not within its bound; should extend Generic<MyGeneric>.
The problem seems to be that Java forces me to repeat the type variable in the upper bound - which is kind of nonsensical as, to stay with the container example, I don't want my concrete container to be of a type of "container of container". I still want it to be of type "container of comparable". I.e the UsingGeneric class should have a signature where the primary type variable is decoupled from the type variable of the upper bound, somewhat like UsingGeneric<T extends Generic<S> & Comparable<S>>. Which is not possible, AFAIK.
What am I doing wrong?
Sample code:
class Test {

  static class Generic<E extends Comparable<E>> {}  // (1)

  static class UsingGeneric<T extends Generic<T> & Comparable<T>> {} // (2)

  static class MyGeneric extends Generic<Integer> {}  // (3)

  static UsingGeneric<MyGeneric> myUsingGeneric;  // (4) - won't compile

}

A: The reason your current code doesn't compile is because:
class UsingGeneric<T extends Generic<T> & Comparable<T>> { ... }

Requires that the type argument used must implement both Generic<T> and Comparable<T>. The Integer class may implement the latter but does not implement the former, thus the compilation error. And the reason you have to specify the Comparable bounds again is because UsingGeneric has declared a new type parameter, T, which is being used as the type argument to the Generic bound, which is a parameterized type in this context. Since the type parameter of Generic is bounded by Comparable you must ensure the type parameter of UsingGeneric has compatible bounds.
That said, what you seem to be looking for is a way to specify the Comparable type used with the Generic type, while not requiring that the type implements both interfaces. This will require two type parameters:
class UsingGeneric<T extends Generic<E>, E extends Comparable<E>> { ... }

This may seem redundant at first but all the information is necessary. Now we have E being used as the type argument of the Generic bound of T while allowing E to be a different type than T. But again, since the type parameter of Generic is bounded by Comparable we have to make sure E has compatible bounds.


text:
Q: Access not saving a design report change Good Evening,
I am hoping someone can help me. I have changed the below code.
SELECT tblPrj.*, tblLkpCts.[CName], tblLkpCts.Loc
FROM tblLkpCts INNER JOIN tblPrj ON tblLkpCts.ID = tblPrj.CKey
WHERE (((tblPrj.[DType]) Like "UFH*") AND ((tblPrj.[Date Completed]) Is Not Null) AND ((tblPrj.[Date Out]) Is Null));

to
SELECT tblPrj.*, tblLkpCts.[CName], tblLkpCts.Loc
FROM tblLkpCts RIGHT OUTER JOIN tblPrj ON tblLkpCts.ID = tblPrj.CKey
WHERE (((tblPrj.[DType]) Like "UFH*") AND ((tblPrj.[Date Completed]) Is Not Null) AND ((tblPrj.[Date Out]) Is Null));

Since making this amendment from SQL View it says I can save, the file last modified time concurs with the save time, however when I go back to report view and then exit, it keeps asking if I would like to save, and regardless of what I select the message dissapears but the report will not exit or save.
Is anyone able to assist me to why this may be?


text:
Q: How to cover code for SOQL and if statement in Apex class Can any one please help me to how to cover those SOQL and if Condition?

A: You need tp update your survey reocrd to  match the condiitons
survey__c survey = new survey__c(Contact__c = con.id, Most_Recent_NPS_Survey__c  = true);
Insert survey;

And need to provide same contact id in task as well
Task task= new task();
     task.Subject='Message Sent';
    task.status='Completed';
    //task.Whatid= survey.id;
    task.whoId = con.id;
    insert task;

It will cover your if conditions.
Also you should use system.assert in your test class to validate your functionality.
Something like
System.assert(task.Whatid == survey.Id)


text:
Q: differential entropy rate for stationary processes the differential entropy rate of a stochastic process $X = (X_i)_{i \in \mathbb{N}}$ is defined as $$h(X) = \lim_{n \to \infty} \frac{1}{n} h(X_1,\ldots,X_n)$$,
where $h(X_1,\ldots,X_n)$ is the joint Entropy of $X_1,\ldots,X_n$.
Now my Question: in every Source it is written that you can show that if $X$ is stationary, the entropy rate of $X$ exists. But I have no idea how to prove this, since every source only shows the discrete case.
Can someone help?


text:
Q: Searching for names in a MySQL database that probably has typos I'm currently writing a script tasked with going through tens of thousands of rows of account information and cleaning mistyped addresses, as well as printing out reports on how the address was cleaned. Currently the biggest source of unclean addresses is mistyped street-names (it's amazing how many ways you can spell a street-name). In any case, currently my script grabs the input street-name and performs a series of edits specific to the Norwegian language (v. becomes vegen, gt. becomes gata etc.) and searches for the street-name in a ~2 million row database of addresses. If it doesn't find a match it proceeds to split off the latter half of the street-name and replacing it with a wildcard. It tries out different variations of the wildcard search.
Anyway, my question is:
Does MySQL include anything that could make this easier for me? I recall hearing mention of a "search" function in MySQL that finds the cells in a column with the most matching characters or something. In the cases where my wild-card search fails it would be a great tool to have.
Anything else that would help with finding matches to mistyped addresses would be great.

A: One option might be to try to use SOUNDEX to get you close to what you want.  SOUNDEX will make matches off of pronunciation so it might get you closer if people are mistyping based off of the phonetic spelling of a street name.
You might also try the Levenshtein distance algorithm.  This is probably more closely tied to what you are looking for.  Basically it looks at how close one word is to another.  It can be used for spell checking, etc. and it might be useful when looking for bad data in address fields.  Here is a link to it:
http://www.merriampark.com/ld.htm
If you want the function to use the Levenshtein distance algorithm in MySQL, you can look at an example here:
http://www.artfulsoftware.com/infotree/queries.php#552

A: You might want to play around with FULLTEXT indexes and fuzzy MATCH ... AGAINST queries. Keep in mind that words shorter than 4 letters are excluded from the index by default.

A: This is a little bit more of work, but:

*

*Create a table words with the fields

*

*word

*num_appeared

*And a pivot table between words and addresses

*

*address_id

*word_id
Traverse your addresses table, split the address by word, then insert each word in the words table and create the record in the pivot table. When you are done, sort the words table by num_appeared ASC and there - you have the words with biggest chances of being mistyped. You can then create a script that searches google after those words and the suggestion google makes might be the correct form of the word.


text:
Q: Creating nested tags using document.createElement I want to create a nested tag using javascript createElement function like

Jan

Can anyone give me an idea how to do it?

A: The simplest way is with createElement() and then set its innerHTML:
var tag = document.createElement("li");
tag.innerHTML = 'Jan';

You can then add it to the document with .appendChild() wherever you want it to go.

A: var li = document.createElement('li');
var span = document.createElement('span');
span.className = 'toggle';
span.appendChild(document.createTextNode('Jan'));
li.appendChild(span);


text:
Q: Creating a reusable javascript function instead of copy/paste I made a page I need to have in different instances. In short it is used to fill in different parts of a script and then display said script on the page for the user to copy it.
This script below handles the main part of the job, getting a field from HTML and then i can call the result in html to be displayed.
var urlField = document.getElementById('urlField').value;
var resultUrl = document.getElementById('resultUrl');
resultUrl.textContent = urlField;

Problem: there are different fields, eg. url, startdate, enddate, adschedule, etc. so I would like to have a reusable script that just says get the respective field and result the value which is assigned to it in html.
Can I do this somehow? I was researching the function "this" in javascript, but it is too complicated for my current knowledge. Bear in mind that I am in only a very basic level.
You can find the whole codepen to understand the issue better here: https://codepen.io/kmb5/pen/GxZbZq

A: Add parameters to your re-usable function and then call it whenever you need to use it. Use javascript to get the required data and pass it in as parameters.
reusable.js:
function myFuncWithParameters(parm1, parm2, parm3){

}

Alternatively:
function myFuncWithParameters(myObject){
    //access properties from the object: myObject.parm1, myObject.parm2, myObject.parm3
}

Using the object route might make it easier since the order of the properties will not matter like parameters. Regardless of either method you will have to validate the input.
In your html pages, you will need some More JavaScript and HTML to bring in the JS and call it.
<html>
    <head>
        <title>my page</title>
        <script scr="path to reusable js"></script>
        <script src="path to this path's js"></script>
    </head>
    <body>
        my page
    </body>
</html>

If you look at the script tags, by importing the reusable js you can use it in javascript that was written / imported further down into the page.
In order to ensure you have access to an imported function, you can check if the function you need is defined:
if(typeof(myFuncWithParameters) !== 'undefined' && typeof(myFuncWithParameters) == typeof(Function){
    //myFuncWithParameters will definitely be defined and is a function, if we get in here
}else{
    //myFuncWithParameters is not defined and/or is not a function
}

In your html page to call the re-usable function...
var parm1 = value;
var parm2 = value;
var parm3 = value;
myFuncWithParameters(parm1, parm2, parm3);

In you decide to use the object:
var myObject = {
    'parm1' : 4,
    'parm2' : 6
}
//myObject.parm1 == 4
myFuncWithParameters(myObject);


text:
Q: How do I align th and td content of a table using Bootstrap 4? Im having troubles with alignment of th and td content. I dont know what else to do, I´ve used all the possible classes in bootstrap 4 ex: text-center, center-block, align-items-center, justify-content-center and other but the table it looks the same. Please give me an idea to fix this issue or better help me to find the problem. Thanks in advance.Table Employee

            Id
            Name Employees
            User Name
            Department
            Position
            Campaign

            '.$item['id_employee'].'
            '.$item['name_employee'].'
            '.$item['user_employee'].'
            '.$item['name_department'].'
            '.$item['name_position'].'
            '.$item['name_campaign'].'

            <button type="button" style="border-radius:8px;" class="btn btn-outline-primary btn-sm">
            </button>

             <button style="border-radius:8px;" class="btn btn-outline-danger btn-sm" type="button">
             </button>

A: Judging from the picture, it looks like you have multiple tables, something like:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

      ID
      Name
      Description

      1
      John Smith
      N/A

      ID
      Name
      Description

      2
      Frank Peters
      Frank Peters has a much longer description than John

Having multiple tables means that each table will resize it's columns, independent of the other ones.
What you want to do is put them in the same table:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

      ID
      Name
      Description

      1
      John Smith
      N/A

      ID
      Name
      Description

      2
      Frank Peters
      Frank Peters has a much longer description than John


text:
Q: Ruby, Initialize, Assigning Variables Values How would I assign multiple instance variables the same value in the ruby initialize method?
Looking to refactor the below:
def initialize
 @weekly_stats = Hash.new {|h, k| h[k]={}}
 @report_times = Hash.new {|h, k| h[k]={}}
 @email_stats = Hash.new {|h, k| h[k]={}}
end

A: Not sure what doing this in a one-liner buys you but you could do something like this:
%w{weekly_stats report_times email_stats}.each { |v| instance_variable_set("@#{v}", Hash.new {|h, k| h[k]={}} }

Or break it into two non-duplicating lines like:
vars = %w{weekly_stats report_times email_stats}
vars.each { |v| instance_variable_set("@#{v}", Hash.new {|h, k| h[k]={}} }

Or combining it with jvnill's answer:
value = Hash.new {|h, k| h[k]={}}
vars = %w{weekly_stats report_times email_stats}
vars.each { |v| instance_variable_set("@#{v}", value.dup }

A: you can't do this in a single line because you're assigning a hash.  Using Vinay's answer
>> a = b = c = { a: 'b', c: 'd' }
>> a # {:a=>"b", :c=>"d"}
>> a[:a] = 2 # 2
>> b # {:a=>2, :c=>"d"}

In the example above, b changed when you changed a.  I'm not sure if there's a way to write this in a single line but try the following code instead
@weekly_stats = Hash.new {|h, k| h[k]={}}
@report_times = @weekly_stats.dup
@email_stats = @weekly_stats.dup

A: Try this,
@weekly_stats = @report_times = @email_stats = Hash.new {|h, k| h[k]={}}

This works, but you should know that it's only safe for your situation if you're using the variables for numbers, which are immutable in Ruby. If you tried the same thing with a string, for example, you could end up with some behavior you didn't expect:
ruby-1.9.2-p180 :001 > foo = bar = "string"
 => "string"
ruby-1.9.2-p180 :002 > foo.upcase!
 => "STRING"
ruby-1.9.2-p180 :003 > bar
 => "STRING"


text:
Q: RestClient - Request gives back 500 internal server error (content as html) and no ErrorMessage I am having issues with a PUT request using REST Client. I tried the same in Postman and I get a ErrorResponse back with a proper error message. So I was expecting the same in the C# - RestSharp Request call. Instead I get a 500 Internal Server Error, with request.ErrorException = null and request.ErrorMessage = null as well. Before anyone accuses me of the Request header, I did set request.AddHeader("Accept", "application/json");
My code is something like this
var client = new RestClient(uri);
var request = new RestRequest(Method.PUT);
request.AddHeader("Accept", "application/json");`
request.AddParameter("xx...", value);
var response = client.Execute(request);
var content = response.Content;

So now the response.Content I see is the following html (I will just post partial content for information)
<html>
    <head>
        <title>Runtime Error</title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">
.....

....
</html>

For now in my wrapper method I am checking to see if the StatusCode is not a 200, then if the request.ErrorException is null, in this case to just show a generic message 'something went wrong... ' type of a thing. This is just a bandaid solution for now. I would like to know how to get the exact Error Response or how to handle this situation.
Any help is greatly appreciated.

A: In web services the actual error will never be returned unless you explicitly set the error message to one of its properties.  For example in WebAPI you can return error message by using Request.CreateResponse() method.  The method needs to return HttpResponseMessage type.  Following is the code
[HttpPut]
public HttpResponseMessage MyPutMethod()
{
try
{
...process
return Request.CreateResponse(HttpStatusCode.OK, "Success");
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}

NOTE:  It is not a good idea to send exception details for security reasons.


text:
Q: Error in Kafka running on openshift during SSL I have Kafka running on openshift and have exposed a route (TLS passthrough) to access the Kafka broker. Below are server.properties of the broker.
Note that openshift service is port forwarding message to 9043.
I have keystore and certificate on Kafka broker and ca-cert on the client.
sasl.mechanism.inter.broker.protocol=PLAIN
sasl.enabled.mechanisms=PLAIN
listeners=INTERNAL://0.0.0.0:9092,EXTERNAL://0.0.0.0:9043
advertised.listeners=INTERNAL://localhost:9092,EXTERNAL:abc:9043
inter.broker.listener.name=INTERNAL
listener.security.protocol.map=INTERNAL:PLAINTEXT,EXTERNAL:SSL
ssl.client.auth=none
security.protocol=SSL
ssl.enabled.protocols=TLSv1.2,TLSv1.1,TLSv1
ssl.keystore.location =
ssl.keystore.password =
ssl.key.password =
ssl.truststore.location =
ssl.truststore.password =
ssl.endpoint.identification.algorithm=

I am trying to access the route using Kafka producer on my local as below
kafka-console-producer.bat --broker-list abc:443 --producer-property security.protocol=SSL --producer-property ssl.truststore.password=*** --producer-property ssl.truststore.location=ca.crt  --topic dummy

I am getting below error on Kafka pod.
data-plane-kafka-network-thread-0-ListenerName(EXTERNAL)-SSL-3, READ: TLSv1.2 Handshake, length = 347
check handshake state: client_hello[1]
data-plane-kafka-network-thread-0-ListenerName(EXTERNAL)-SSL-3, fatal error: 10: Handshake message sequence violation, 1
javax.net.ssl.SSLProtocolException: Handshake message sequence violation, 1
%% Invalidated:  [Session-1, SSL_NULL_WITH_NULL_NULL]
%% Invalidated:  [Session-2, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384]
data-plane-kafka-network-thread-0-ListenerName(EXTERNAL)-SSL-3, SEND TLSv1.2 ALERT:  fatal, description = unexpected_message
data-plane-kafka-network-thread-0-ListenerName(EXTERNAL)-SSL-3, WRITE: TLSv1.2 Alert, length = 2
data-plane-kafka-network-thread-0-ListenerName(EXTERNAL)-SSL-3, called closeOutbound()
data-plane-kafka-network-thread-0-ListenerName(EXTERNAL)-SSL-3, closeOutboundInternal()
data-plane-kafka-network-thread-0-ListenerName(EXTERNAL)-SSL-3, called closeInbound()
data-plane-kafka-network-thread-0-ListenerName(EXTERNAL)-SSL-3, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLException: Inbound closed before receiving peer's close_notify: possible truncation attack?
[2020-08-01 23:30:26,397] INFO [SocketServer brokerId=0] Failed authentication with /10.X.X.X (SSL handshake failed) (org.apache.kafka.common.network.Selector)

Below is error on producer client
)
javax.net.ssl|ERROR|0E|kafka-producer-network-thread | console-producer|2020-08-01 19:40:02.523 CDT|TransportContext.java:313|Fatal (CERTIFICATE_UNKNOWN): Extended key usage does not permit use for TLS server authentication (
"throwable" : {
  sun.security.validator.ValidatorException: Extended key usage does not permit use for TLS server authentication

Any ideas on what could be the problem.

A: After some research we figured out that the extended key usage on certificate was set as client auth. We updated the same, added the SAN and were able to connect.


text:
Q: Running a Single Test using Maven i want to run a single test using maven
here's my pom.xml :

      junit
      junit
      4.8.1
      test

        org.seleniumhq.selenium.client-drivers
        selenium-java-client-driver
        1.0.2

        <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>3.0-alpha-1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2.1-b03</version>
        <scope>provided</scope>
    </dependency>

    WebTestAutomatisation

       org.apache.maven.plugins
       maven-war-plugin
       2.0.2

     <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>tomcat-maven-plugin</artifactId>
    <version>1.0-beta-1</version>
  </plugin>

     <!--  Start the tomcat server and  Deploy the war -->
    <plugin>
      <groupId>org.codehaus.cargo</groupId>
      <artifactId>cargo-maven2-plugin</artifactId>
      <version>1.2.2</version>
        <configuration>

    <fork>true</fork>
        <wait>false</wait>
            <container>
 <containerId>tomcat7x</containerId>
 <type>installed</type>
  <home>${env.CATALINA_HOME}</home>
   </container>
  <!-- <executions>
  <execution>
 <id>start-container</id>
  <phase>pre-integration-test</phase>
  <goals>
  <goal>start</goal>
   <goal>deploy</goal>
  </goals>
 </execution>
 <execution>
  <id>stop-container</id>
 <phase>post-integration-test</phase>
  <goals>
   <goal>stop</goal>
  </goals>
 </execution>
 </executions> -->
</configuration>

 <!-- Start the selenium server -->
 <plugin>
  <groupId>org.codehaus.mojo</groupId>
 <artifactId>selenium-maven-plugin</artifactId>
 <version>2.3</version>

  <executions>
     <execution>
      <id>start</id>
    <phase>pre-integration-test</phase>
  <goals>
   <goal>start-server</goal>
   </goals>
  <configuration>
   <background>true</background>
   <logOutput>true</logOutput>
  </configuration>
 </execution>
 <execution>

stop
      post-integration-test

     stop-server

     org.apache.maven.plugins
     maven-surefire-plugin
      2.4.3

     org.junit:com.springsource.org.junit

    **/functional/*Test.java

 <!--   Running the tests in the functional tests package
      during the integration tests phase. -->
 <id>integration-tests</id>
 <phase>integration-test</phase>
  <goals>
<goal>test</goal>

    false

     none

     **/functional/*Test.java

</project>

i used this command : mvn -Dtest=MyTestClass test
and i get this error :
i tried this command but it runs all tests and not the specified one  mvn -Dit.test=MyTestClass verify

A: Jute maven plugin allows to execute single JUnit test as external JVM process


text:
Q: input and textarea appear different width when are set to same width? When I set the width of an input and a text area to 94% they appear to be slightly different in width. This is something I have seen many times on many sites.
Can anyone explain why a textarea is not as wide as an input when set to the same % width?
input, textarea {
    width: 94%;
}

A: With CSS3 you can also use:
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box;    /* Firefox, other Gecko */
box-sizing: border-box;         /* Opera/IE 8+ */

A: *

*Don't forget the box model includes borders, padding, and margins. They all affect the actual physical width of an element in the page.

*Unless you use a CSS reset you're at the mercy of the default browser stylesheets which set different borders, padding, and margins for each element.


text:
Q: Mount and Unmount trigger Desktop environment crash I'm posting this question here, but is also available on here.
I'm running an up-to-date Fedora 27 on my laptop. Since a couple of days, every time I plug in or unmount a removable device (USB Drive, SD card or Hard Drive), it makes my desktop environment reset and closes my session, jumping me back to the login screen.
journalctl -e's output (run right after a crash) consists in a lot of lines, some of which are in bold. Here is the beginning of the bold section of the output, but I can provide the full output if needed.
Object Clutter.Clone (0x56127655f8d0), has been already finalized. Impossible to get any property from it.
gnome-shell[2701]: Object Clutter.Clone (0x56127655f8d0), has been already finalized. Impossible to set any property to it.
org.gnome.Shell.desktop[2701]: == Stack trace for context 0x561274cd5170 ==
A lot of stuff here...

dmesg's output shows some errors involving my video card (which is a NVidia GTX 960M):
[drm:wait_panel_status [i915]] *ERROR* PPS state mismatch
[drm:wait_panel_status [i915]] *ERROR* PPS state mismatch
rfkill: input handler disabled
nvidia-modeset: Allocated GPU:0 (GPU-a2132636-974c-cba4-5912-ecb030e4238f) @ PCI:0000:01:00.0
nvidia-modeset: Freed GPU:0 (GPU-a2132636-974c-cba4-5912-ecb030e4238f) @ PCI:0000:01:00.0

Can anyone help me?

A: After some tests, I discovered that the process triggering the shutdown was indeed one of the builtin extensions of gnome-shell, in particular the places one. The faulty package is gnome-shell-extension-places-menu, and the fix for that is already in the upcoming update of the package.
Until the update happens, I managed to solve it by doing the following:
cd /usr/share/gnome-shell/extensions/places-menu@gnome-shell-extensions.gcampax.github.com/
mv placeDisplay.js placeDisplay.js.old
wget https://gitlab.gnome.org/GNOME/gnome-shell-extensions/raw/master/extensions/places-menu/placeDisplay.js

Be aware that the location of the extensions might be  in ~/.local/share/gnome-shell/extensions, if it has been installed locally.
Reference of the bug can be found here.


text:
Q: Cache manifest manual updates I want to provide users the ability to choose whether or not they want to update my Web app. From my research, cache manifest automatically fires the "downloading" event as soon as it finds a modified appcache file. The goal is to maintain this behavior if the user loads my app for the first time, but if the user already has an older version on cache, he or she would receive the confirm box:
An update is available. Do you want to download it?
Ok
Cancel

Clicking "Ok" would fire the "downloading" event, while clicking "Cancel" would fire the "noupdate" event instead, skipping the download.
How can I do this?

A: I don't believe that the exact behavior you are looking for is possible.
Since JavaScript is effectively loaded into the page, it will always execute after (or while) the appcache magic is happening.
The first time a user visits the page, the browser would see that there is a manifest attribute. The page and all server-resources would continue loading normally, and the browser would download and cache all resources specified in the manifest file in the background.
The next time the user visits the page, it first checks to see if the manifest has updated or any caching headers for the manifest have expired. If the manifest is new, it will download the updated cache and present the user with the old version. The new version won't be presented until the user refreshes the page. So, by the time the page loads and you prompt the user, the new appcache has already been downloaded.
Try this experiment. Create a bare-bones simple html page with a cache manifest. Include the following in the header:
<script>
var cache = window.applicationCache,
    handleEvent = function(event) {
        console.log("appcache event fired.");
    };

cache.addEventListener('checking', handleEvent);
cache.addEventListener('downloading', handleEvent);
cache.addEventListener('progress', handleEvent);
cache.addEventListener('cached', handleEvent);
cache.addEventListener('noupdate', handleEvent);
cache.addEventListener('updateready', handleEvent);
cache.addEventListener('obsolete', handleEvent);
cache.addEventListener('error', handleEvent);

</script>

Watch the Chrome developer console. Notice that all the event handlers here fire after Chrome logs the browser's build-in event handlers.
What you could try is detect on the server that the cache-manifest has changed. If that is the case, instead of directing the user to the main page, redirect to a different page that will contain the prompt. If the user wants the updated version, continue as normal. If not, you will need to intercept the request for the app-cache and return a 304 (Not Modified).
This is an excellent resource.


text:
Q: how to pass a xsl variable value to a javascript function i am trying to pass an xsl variable value to a javascript function.
My xsl variable
<xsl:variable name="title" select="TITLE" />

i'm passing the value like this
<input type="button" value="view" onclick="javascript:openPage('review.html?review=$title')" />

i have tried the above code in different possible ways but i gets errors.
<script type="text/javascript">
                    function jsV() {
                    var jsVar = '<xsl:value-of select="TITLE"/>';
                    return jsVar;
                    }
                </script>

                <input type="button" value="view" onclick="javascript:openPage('javascript:jsV()')" />

I also tried

<input type="button" value="view" onclick="javascript:openPage('review.html?review='\''
    +$title+'\')" />

Is there alternative way or am i not doing it right?

A: You forgot about {}:
<input type="button" value="view" onclick="javascript:openPage('review.html?review={$title}')" />

A: Here is a working example how to do this:
This transformation:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/*">
   <xsl:variable name="vTitle" select="TITLE"/>

     <input type="button" value="view"
     onclick="javascript:openPage('review.html?review={$vTitle}')" />
 </xsl:template>

</xsl:stylesheet>

when applied on this XML document (no XML document was provided!):
<contents>
 <TITLE>I am a title</TITLE>
</contents>

produces the wanted, correct result:
<input type="button" value="view"
 onclick="javascript:openPage('review.html?review=I am a title')"/>

Explanation: Use of AVT (Attribute Value Templates).

A: It is also possible to access xsl variable from a JavaScript code in the same file by doing the following:
<xsl:variable name="title" select="TITLE"/>
<script type="text/javascript">
    function getTitle() {
        var title = <xsl:value-of select="$title"/>;
        return title;
    }
</script>


text:
Q: When did system-on-chip (SoC) arrive in mainstream laptops? Are intel chipsets used in laptops such as XPS 13, SoCs? An SoC has multiple functional units like CPU, GPU, sometimes DSPs(Digital Signal Processors), memory and many other units embedded in a single chip. Most intel chipsets used in laptops do have integrated graphics, so in that sense, are they SoCs? Wikipedia mentions SoCs arriving to mainstream laptops as of 2018, but intel chipsets had integrated graphics even before 2018. Is Wikipedia correct? The question is open to other laptop chipsets such as AMD too.

A: No, they aren't SoCs, the RAM is external.
The point of SoCs is that all the standard components are in a single IC, so only low-speed interfaces for the application are on the outside, which simplifies the design of the PCB a lot.
SoCs with display outputs are seldom as well, as these too are high-speed signals that are difficult to route on a PCB, it's more common to combine them with a display with integrated controller, typically via SPI. These will be small and have slow updates, so they are unsuitable for laptops.

A: A System-On-Chip (SoC) is a very loosely defined term, but essentially can be considered as a solution which provides all of the necessary functionality for a given system integrated into a single IC. This is usually a single die, but can also include vertical integration such as Package-On-Package and horizontal integration in the form of System-On-Package.
The key defining feature is that the chip can basically run standalone once power is supplied. Features like power regulation and clocking are usually considered seperately, as are external storage such as flash memory and external RAM which are useful for expansion.
There are many types of SoC:

*

*Simple microcontrollers with processor, flash, RAM, IO can be considered SoCs.

*More modern SoCs include larger processor + RAM + IO combos

*Some then also include a GPU for graphics

*Some which include an FPGA for co-processing

*Some are more related to mixed signal analogue + digital + processor

There is no hard and fast requirement for a SoC to have a large external RAM integration. It might of course have an external memory controller integrated. The lack of say DDR memory does not disqualify a device from being considered a SoC. For example the Cyclone V SoC devices are FPGA + Processor + 64kB executable on-chip RAM.

With regard to the "SoCs are being applied to mainstream personal computers as of 2018" claim from Wikipedia, that links to a blog post which talks about arm entering the consumer PC market with a roadmap through 2020. It doesn't in any way discuss system-on-chip. There isn't anything else given there that specifically backs up the statement, and so should be taken with a pinch of salt. I presume that whomever wrote the Wiki article is simply assuming that if its an arm processor, it must be a SoC when adding that reference.
Doing a bit more research, the Surface Go released in 2018 makes use of an Intel Pentium Gold 4415Y processor. There are a number of sites, usually marketing sites and blogs, that refer to this as a SoC device. However Intel don't refer to this processor as a SoC on their specification page.
Having said that, as a Kaby Lake processor, the 4415Y starts to come under the class of System on Package type devices, whereby multiple dies are placed within the same physical package (or in this case interposer board). The 4415Y is indeed a two die device.
Indeed further looking around Kaby Lake processors reveals the Kaby Lake-G series which do in fact include DDR RAM - they use the Hybrid Memory Cube technology to integrate several DDR memory chips on the same physical package as the processor, which would in fact put it into the book of something which could operate standalone. The HP Spectre x360 and Dell XPS 15, models of both released in 2018 make use this SoP processor. So yes, mainstream laptops in 2018 did include SoC type processors.


text:
Q: Pandas to_csv truncating string values to exponent notation I am adding a column to my dataframe like:
df['AccountID'] = "123456789765".
I am assigning it a string value.
Then I am writing the dataframe to a csv file using the to_csv method.
But in the csv file the column values appear like: 1.23456E+11.
Can someone tell the reason and solution for this ?
I've already tried casting the column to object type again.

A: Based on this answer here

Unfortunately excel does not allow you to turn this functionality off
  by default.
However if you select your data, right click, and click "Format
  cells..." and choose Number you can stop excel from changing your data
  to scientific notation.

e.g. it's not a pandas issue.


text:
Q: How to pass object as parameter into function from .h and .cpp I am relatively new to C++, but have come from Python and C.
I am using an SDK for a lidar sensor. I have 5 main files that are involved; SDK.h, SDK.cpp, setup.h, setup.cpp and main.cpp.
A class is defined within the SDK.
rplidar.h
class RPlidarDriver{
public:
    static RPlidarDriver * CreateDriver(_u32 drivertype = DRIVER_TYPE_SERIALPORT);
    // more code
}

main.cpp
#include <iostream>
#include "rplidar.h"
#include "setup.h"

using namespace std;
using namespace rp::standalone::rplidar;

int main()
{
    //code

    RPlidarDriver* lidar = RPlidarDriver::CreateDriver(DRIVER_TYPE_SERIALPORT);

    start_reading(lidar, scanMode);

    //code
}

setup.cpp
#include "setup.h"
#include "rplidar.h"

using namespace std;
using namespace rp::standalone::rplidar;

void start_reading(RPlidarDriver* driver, const char* scanMode)
{
    //start motor
    driver->startMotor();

    //more code...

}

setup.h
#include "rplidar.h"
using namespace rp::standalone::rplidar;

namespace setup
{
    void start_reading(RPlidarDriver* driver, const char* scanMode);
}

However I get this error

main.obj : error LNK2019: unresolved external symbol "void __cdecl setup::start_reading(class rp::standalone::rplidar::RPlidarDriver *,char const *)" (?start_reading@setup@@YAXPAVRPlidarDriver@rplidar@standalone@rp@@PBD@Z) referenced in function _main

I also get the same error for other functions that I try to use the object as a parameter.
If I put the function in setup.cpp into main.cpp, it compiles easily. I tried to implement & and use the parameter as a reference instead, but not luck.

A: main.cpp and setup.cpp both need to be compiled and the resulting object files need to be linked together along with the SDK libraries. The error you're getting is telling you you're trying to link the final binary using just main.o and the SDK without setup.o That's why the linker is failing to find the symbol with the implementation of your start_reading function.


text:
Q: Switch Wordpress Post Template based on URL query Parameter I have a wordpress magazine website. I want to combine Endless Scrolling & Pagination for the Article Page.
Question: Is it possible to show the same post(Article) different ways (Paginated, Endless Scrolling), based on the query param of the visit ? Like for example (If "?layout=paginated" then the post should be "paginated", else "Turn On the Endless Scrolling").
Is there any plugin or custom code to do that ?
A real example like this used by nickiswift.com:
https://www.nickiswift.com/137343/movie-villains-who-are-gorgeous-in-real-life/
https://www.nickiswift.com/137343/movie-villains-who-are-gorgeous-in-real-life/?utm_source=zergnet.com&utm_medium=referral&utm_campaign=zergnet_3987140&utm_content=5
Tried a bunch of plugins but no results...

A: In your child-theme template you could simply use a If statement to run the endless scrolling or not.
For example if your script runs on a specific class .endless
<?php
    if ($_GET['layout' == 'paginated') {$class=''}
    else {$class='endless'};
?>

Then to the container you want to be endless or paginated
<div class="container <?php echo $class; ?>">

Of course this code must be customised to your particular case.


text:
Q: Facebook API - Is it possible to email users when they click "Become a Fan"? I want to do the following, but not sure if it is possible with the current API.  The only thing I found in the AP is the ability to tell if a FB user is a fan.  Here goes:
When a user clicks the become a fan button, it sends a custom message (email or facebook email) with url to redeem a code for a free song. The code is obtained from my own custom DB.
Is this possible?


text:
Q: Woocommerce - Print Product's Custom Field In Email In Woocommerce, I need to print a custom field on the Completed Order email.
The template is completely unique in my themes woocommerce/emails folder because the default template doesn't work for my needs.
As such I'm trying to display the following:
Title, Quantity and two custom fields
This needs to be included in the customer-completed-order.php email template but I am not certain what syntax is necessary to print it.
I found something by Googling but it doesn't work:
<?php foreach ( $items as $item_id => $item ) :
$_product     = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item );
?>

Class: <?php echo get_post_meta($_product->id,'name',true); ?>

Date: <?php echo get_post_meta($_product->id,'date_text_field',true); ?>

Time: <?php echo get_post_meta($_product->id,'time_text_field',true); ?>

Number of Spaces: <?php echo get_post_meta($_product->id,'qty',true); ?>

<?php endforeach; ?>

A: Try adding to action hook,
do_action( 'woocommerce_order_item_meta_start', $item_id, $item, $order );
OR
do_action( 'woocommerce_order_item_meta_end', $item_id, $item, $order );
This could be used in following way:
add_action( 'woocommerce_order_item_name', 'action_custom_order_meta', 10, 3 );

OR
add_action( 'woocommerce_order_item_name', 'action_custon_order_meta', 10, 3 );

Following is the callback handler function.
function action_custom_order_meta($item_name, $item, $false){
    $product_id = $item['product_id'];
    $product_custom_date = get_post_meta($product_id, 'product_custom_date', true);
    $product_custom_time = get_post_meta($product_id, 'product_custom_time', true);
    $product_custom_meta = 'Date: ' . $product_custom_date . '
 Time: ' . $product_custom_time;
    echo $product_custom_meta;
}

Change the custom field names to appropriate. You might also need to wrap the output according to the required markup for your custom email.
Hope this helps.


text:
Q: Congruency Modulo - How to Derive I'm wondering how to derive $41 \equiv 6 \pmod 7$ or $2 \equiv 2 \pmod 7$. Is there a formula for that?

A: According to definition, $a\equiv b \pmod c$ iff $a$ and $b$ have the same remainder when divided by $c$.
$41$ has a remainder of $6$ when divided by $7$.
$2$ has a remainder of $2$ when divided by $7$.


text:
Q: Redirect non-www and HTTP to www and HTTPS I am running an Express web server. I used Let's Encypt to create SSL certificates for both the www and non-www version of my domain. My DNS has these records:
CNAME | Host: @   | Target: dynamicdns.example.com. | TTL: 60min
CNAME | Host: www | Target: dynamicdns.example.com. | TTL: 60min

I also have this node.js code to run the webserver:
// Dependencies
const express = require('express');
const fs = require('fs');
const http = require('http');
const https = require('https');

// Create express instance
const app = express();

// Get credentials from system
const privateKey = fs.readFileSync('/etc/letsencrypt/live/www.example.com/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/www.example.com/cert.pem', 'utf8');
const ca = fs.readFileSync('/etc/letsencrypt/live/www.example.com/chain.pem', 'utf8');
const credentials = {
    key: privateKey,
    cert: certificate,
    ca: ca
};

// Initalize server
app.use(express.static('public'));
const httpServer = http.createServer(app);
const httpsServer = https.createServer(credentials, app);

// Listen for HTTP
httpServer.listen(80, () => {
    console.log('HTTP Server running on port 80');
});

// Listen for HTTPS
httpsServer.listen(443, () => {
    console.log('HTTPS Server running on port 443');
});

This all works correctly, but it creates an issue with having multiple valid URLs for the same content. The following URLs are all valid right now:
http://example.com
http://www.example.com
https://example.com
https://www.example.com

I want to redirect all the wrong URLs to https://www.example.com, which is the correct URL. I'm not sure how I should go about doing this. Any help would be appreciated.

A: you could use a middleware like this one, to check all domains and redirect accordingly:
app.use((req, res, next) => {
  if (!req.secure) {
    return res.redirect('https://' + req.get('host') + req.url);
  }
  next()
})

Just make sure to use it just for production


text:
Q: Apply transparency on pixels in an image with PyQGIS I'm trying to grab the pixels that intersect with my polygon shapefile and apply transparency to them (that is, I'm trying to create a hole in my raster)
For that, I get all the pixels that are in the footprint of the shapefile in a list (see code below)
Then I used the QgsRasterTransparency.TransparentThreeValuePixel () class to apply transparency, but I get an error message:

Error message: AttributeError: 'Dataset' object has no attribute
  'renderer'

Code:
from PyQt4.QtCore import *
from osgeo import gdal, ogr
from osgeo.gdalconst import *
import numpy as np

iface = qgis.utils.iface

layers = iface.legendInterface().layers()
raster = gdal.Open("F:\\MASTER GEOM\\MasterGeomatique_data\\PLEIADES\\PLEIADES_20130415_COLNAT.TIF")
print(raster)

transform = raster.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = transform[5]
print xOrigin, yOrigin

shp = ogr.Open("F:\essai.shp")
lyr = shp.GetLayer()
feat = lyr.GetNextFeature()
geom = feat.GetGeometryRef()

if (geom.GetGeometryName() == 'POLYGON'):
    ring = geom.GetGeometryRef(0)
    numpoints = ring.GetPointCount()
    pointsX = []; pointsY = []
    for p in range(numpoints):
                lon, lat, z = ring.GetPoint(p)
                pointsX.append(lon)
                pointsY.append(lat)
                #print (pointsX)
xmin = min(pointsX)
xmax = max(pointsX)
ymin = min(pointsY)
ymax = max(pointsY)
print xmin, ymin
print xmax, ymax
 # Specify offset and rows and columns to read
xoff = int((xmin - xOrigin)/pixelWidth)
yoff = int((yOrigin - ymax)/pixelWidth)
xcount = int((xmax - xmin)/pixelWidth)+1
ycount = int((ymax - ymin)/pixelWidth)+1
print xoff, yoff
print xcount, ycount

bandList = []
# retrieve pixel on region of interest
for i in range(raster.RasterCount):
    band = raster.GetRasterBand(i+1)
    data = band.ReadAsArray(xoff, yoff, xcount, ycount)
    bandList.append(data)

# Apply transparency using QgsRasterTransparency.TransparentThreeValuePixel()
active_layer = raster
raster_transparency  = active_layer.renderer().rasterTransparency()
ltr = QgsRasterTransparency.TransparentThreeValuePixel()
tr_list = []
ltr.min = np.min(bandList)
ltr.max = np.max(bandList)
ltr.percentTransparent = 100
tr_list.append(ltr)
active_layer.renderer().rasterTransparency().setTransparentThreeValuePixelList(tr_list)
active_layer.triggerRepaint()

# Refresh canvas
QgsMapLayerRegistry.instance().addMapLayer(raster)

# Message d'erreur : AttributeError: 'Dataset' object has no attribute 'renderer'

A: I don't think using gdal.open returns a QgsRasterLayer object, which you need to access it's renderer.
Try replacing:
raster = gdal.Open("F:\\MASTER GEOM\\MasterGeomatique_data\\PLEIADES\\PLEIADES_20130415_COLNAT.TIF")

with:
raster = QgsRasterLayer("F:\\MASTER GEOM\\MasterGeomatique_data\\PLEIADES\\PLEIADES_20130415_COLNAT.TIF", gdal)