text:
Q: logout multiple sites in a single click in php in my logout page I have to complete 3 tasks
1. destroy session
2. logout from google account
3. redirect to google home page

i've written the following code in logout page :
<?php
    session_start();

    session_destroy();
    header('location: https://www.google.com/accounts/Logout');
    header('location: http://www.google.com');
?>

steps 1 and 3 working perfectly but logout from google account is not working.
Any suggestion about it ?


text:
Q: Sort array and arrange on the basis of some value I have an array like this
 [Defense] => Array
    (
        [0] => stdClass Object
            (
                [id] => 1
                [position] => G
                [point] => 1.6

            )
        [1] => stdClass Object
            (
                [id] => 1
                [position] => F
                [point] => 2.7
            )

        [2] => stdClass Object
            (
                [id] => 1
                [position] => C
                [point] => 1.4
            )
        [3] => stdClass Object
            (
                [id] => 2
                [position] => C
                [point] => 1.7
            )

        [4] => stdClass Object
            (
                [id] => 2
                [position] => D
                [point] => 1.1
            )
        [5] => stdClass Object
            (
                [id] => 1
                [position] => F
                [point] => 1.7
            )

        [6] => stdClass Object
            (
                [id] => 1
                [position] => G
                [point] => 1.6

            )

        [7] => stdClass Object
            (
                [id] => 1
                [position] => G
                [point] => 1.8

            )
       [8] => stdClass Object
        (
                [id] => 2
                [position] => D
                [point] => 1.5
        )
  )

I want to sort the array on the basis of point descending in PHP. Also, all the position come in sequence (all G than all F so on..)
like this:
  [Defense] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [position] => G
                    [point] => 1.8

                )
             [1] => stdClass Object
                (
                    [id] => 1
                    [position] => G
                    [point] => 1.6

                )
            [2] => stdClass Object
                (
                    [id] => 1
                    [position] => G
                    [point] => 1.6

                )
            [3] => stdClass Object
                (
                    [id] => 1
                    [position] => F
                    [point] => 2.7
                )
            [4] => stdClass Object
                (
                    [id] => 1
                    [position] => F
                    [point] => 1.7
                )

            [5] => stdClass Object
                (
                    [id] => 1
                    [position] => C
                    [point] => 1.7
                )
            [6] => stdClass Object
                (
                    [id] => 2
                    [position] => C
                    [point] => 1.4
                )
            [7] => stdClass Object
                (
                    [id] => 2
                    [position] => D
                    [point] => 1.5
                )
            [8] => stdClass Object
                (
                    [id] => 2
                    [position] => D
                    [point] => 1.1
                )

      )

Any help?

A: use usort() function to sort the array as below
usort($array,function($a,$b){
if($a->position == $b->position )
    return $a->point < $b->point;
else
    return $a->position < $b->position;
});
var_dump($array);

redpajama_set_name: RedPajamaStackExchange


text:
Q: What happens when I apply an offset to one part of this date output? I am trying to write a function that takes in a parameter which is the offset days, and returns the date those many offset days from now. I can easily get the current date from below
#include <ctime>
#include <iostream>
using namespace std;

int main() {
time_t t = time(0);   // get time now
struct tm * now = localtime( & t );
cout << (now->tm_year + 1900) << '-'
     << (now->tm_mon + 1) << '-'
     <<  now->tm_mday
     << endl;
}

My question is if I change the now->tm_mday to now->tm_mday - offset, is it smart enough to do the month change or the year change as they may change.

A: No — (now->tm_year + 1900), (now->tm_mon + 1) and now->tm_mday are separate expressions and adding a new arithmetic operation to one will not affect the others.
Apply the offset to t instead, which is an integral value representing seconds since UNIX epoch. Then the change will carry through to the tm structure and, ultimately, each of your output expressions:
time_t t0 = time(0);               // now
time_t t1 = time(0) - 5;           // five seconds ago
time_t t2 = time(0) - 60*60*2;     // two hours ago
time_t t3 = time(0) - 60*60*24*5;  // five days ago

// (do try to avoid "magic numbers", though)


text:
Q: EF Core Logging SQL Queries when Unit Testing I'm running some unit tests (NUnit) on my DbContext (to an Oracle database) in EF Core 2.2 and I'd like to see the SQL queries it's constructing for each unit test, preferably

*

*in the Debug window and

*in the Test Explorer pane's detail view of each test.

I have a Unit Test similar to:
[SetUp]
public void Setup()
{
    var options = new DbContextOptionsBuilder<MyContext>()
        .UseOracle("some connection string")
        .Options;

    _context = new MyContext(options);
}
[Test]
public void We_can_count_all_the_things()
{
    var count = _context.Things.Count();

    Assert.That(count, Is.GreaterThan(0));

    // something like this for Test output:
    Assert.Pass($"SQL QUERY:{???}")
}

... or maybe I can use an ILogger to direct output to the test result or some magic I'm unaware of.
Any assistance is appreciated.

A: There's an answer here that shows how to log EF Core SQL queries using the Microsoft.Extensions.Logging.Console package...
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLoggerFactory(MyLoggerFactory) // Warning: Do not create a new ILoggerFactory instance each time
        .UseSqlServer(
            @"Server=(localdb)\mssqllocaldb;Database=EFLogging;Trusted_Connection=True;ConnectRetryCount=0");

With something like this:-
public static readonly LoggerFactory MyLoggerFactory
    = new LoggerFactory(new[] {new ConsoleLoggerProvider((_, __) => true, true)});

Further info here

A: NUnit's TestContext.WriteLine is what you are looking for:
...
TestContext.WriteLine($"SQL QUERY:{???}");

Edit:
To get the generated SQL:
EF core:
Get SQL code from an EF Core query
EF 6: How do I view the SQL generated by the Entity Framework?


text:
Q: The type or namespace name 'DomainServices' does not exist in the namespace 'System.ServiceModel' I am getting the following error in my VS 2015 project :
.net framework 4.6
Severity    Code    Description Project File    Line    Suppression State
Error   CS0234  The type or namespace name 'DomainServices' does not exist in the namespace 'System.ServiceModel' (are you missing an assembly reference?)

Also  the following dlls are missing under the References folder :
System.ServiceModel.DomainServices.EntityFramework
System.ServiceModel.DomainServices.Hosting
System.ServiceModel.DomainServices.Server

A: I believe you will need to install the WCF RIA Services Toolkit separately because DomainServices is not apart of the standard WCF library.
Here is the link to download the WCF RIA Services Toolkit


text:
Q: Running Sh Script Post Login via SSH / Console I need to run a bash script for all users when a login is obtained, in either local console access or SSH.
I know about ~/.profile, however I need this to run if the user bypasses the profile during login with "noprofile". It basically needs to run in every single possible context.
Is there a particular folder/file that executes every time a user successfully logs on that I can tap into?

A: As per Sorins comment. Successfully done using the following link.
https://manpages.ubuntu.com/manpages/precise/en/man8/sshd.8.html
LOGIN PROCESS
     When a user successfully logs in, sshd does the following:
       1.   If the login is on a tty, and no command has been specified, prints last login
            time and /etc/motd (unless prevented in the configuration file or by
            ~/.hushlogin; see the FILES section).

       2.   If the login is on a tty, records login time.

       3.   Checks /etc/nologin; if it exists, prints contents and quits (unless root).

       4.   Changes to run with normal user privileges.

       5.   Sets up basic environment.

       6.   Reads the file ~/.ssh/environment, if it exists, and users are allowed to change
            their environment.  See the PermitUserEnvironment option in sshd_config(5).

       7.   Changes to user's home directory.

       8.   If ~/.ssh/rc exists, runs it; else if /etc/ssh/sshrc exists, runs it; otherwise
            runs xauth.  The "rc" files are given the X11 authentication protocol and cookie
            in standard input.  See SSHRC, below.

       9.   Runs user's shell or command.


text:
Q: stale element reference: element is not attached to the page document with the chrome web driver I have already read a lot of threads dealing with this issue in the afternoon but I'm currently running short of solutions unfortunately :(
I try to scrape this website: https://www.kumon.co.uk/find-a-tutor/
I use this code in order to store every url of the different stores. To do so I have to iterate on the next page till the last page.
Here is the code I use:
def get_urls(url) -> list:
    # Get all URLs to the store pages
    options = Options()
    # options.add_argument('--headless')
    path_chromedriver = Path(__file__).parent.parent.joinpath('externals/chromedriver')
    browser = webdriver.Chrome(str(path_chromedriver), chrome_options=options)
    browser.get(url)
    inputElement = browser.find_element_by_id("centre_search")
    inputElement.send_keys('london')
    inputElement.send_keys(Keys.ENTER)
    store_url = []
    links = browser.find_elements_by_link_text('Choose Centre')
    for link in links:
        href = link.get_attribute('href')
        store_url.append(href)
    while browser.find_element_by_xpath("//ul[@class='pagination']//li[last()]/a/small"):
            WebDriverWait(browser, 20).until(
                    EC.element_to_be_clickable((By.XPATH, "//ul[@class='pagination']//li[last()]/a/small"))).click()
            links = browser.find_elements_by_link_text('Choose Centre')
            for link in links:
                href = link.get_attribute('href')
                store_url.append(href)
    return store_url

Unfortunately I get a

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

To use a Try... Except is not a good solution, I'm looking for a robust solution.
Should I switch from Chrome to Firefox ?
Thank's in advance,
Nicolas.

A: Not sure why you think that try/except is not good solution, but this is exactly what you need:
from selenium.common.exceptions import WebDriverException

def get_urls(url) -> list:
    # Get all URLs to the store pages
    options = Options()
    # options.add_argument('--headless')
    path_chromedriver = Path(__file__).parent.parent.joinpath('externals/chromedriver')
    browser = webdriver.Chrome(str(path_chromedriver), chrome_options=options)
    browser.get(url)
    inputElement = browser.find_element_by_id("centre_search")
    inputElement.send_keys('london')
    inputElement.send_keys(Keys.ENTER)

    links = browser.find_elements_by_link_text('Choose Centre')
    store_url = [link.get_attribute("href") for link in links]

    while True:
        try:
            WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, "//li[last()][not(normalize-space(@class))]/a[@data-page]"))).click()
            WebDriverWait(browser, 10).until(EC.staleness_of(links[-1]))
        except WebDriverException:
            break
        links = WebDriverWait(browser, 10).until(EC.visibility_of_all_elements_located((By.LINK_TEXT, 'Choose Centre')))
        store_url.extend([link.get_attribute("href") for link in links])
    return store_url


text:
Q: How can Appium start server before tests and stop it after tests using gulp task? Is it possible to start appium server before tests using gulp task and then execute the tests / suite and stop it using another gulp task.
I have created few tests using webdriver io and now want to execute them without manually starting and stopping the appium server.
There is wdio service for the same wdio-appium-service but it is not working on windows, here is the issue.


text:
Q: How do I use supervisord's environment option in program sections? The supervisord documentation states that

No shell is executed by supervisord when it runs a subprocess, so
  environment variables such as USER, PATH, HOME, SHELL, LOGNAME, etc.
  are not changed from their defaults or otherwise reassigned. (...)
  If you need to set environment variables for a
  particular program that might otherwise be set by a shell invocation
  for a particular user, you must do it explicitly within the
  environment= program config option.

The include an example, which I reproduced into /etc/supervisor/conf.d/apache2.conf:
[program:apache2]
command=/home/chrism/bin/httpd -c "ErrorLog /dev/stdout" -DFOREGROUND
user=chrism
environment=HOME=/home/chrism,USER=chrism

However,
# supervisorctl reread
ERROR: CANT_REREAD: Unexpected end of key/value pairs

Removing the 'environment' line of the apache2 configuration results in no parse errors for the re-read. What's dotty here? I'm using supervisor 3.0a8-1 on Debian Squeeze and note that the mainline supervisor is 3.0a10; I cannot find reference of environment has having been added since 3.0a8

A: http://supervisord.org/configuration.html#program-x-section-settings
says "Values containing non-alphanumeric characters should be placed in quotes"


text:
Q: What built-in codesniff could I use to ensure there are no spaces before parenthesis and after function name Is there a built-in sniff to ensure that
public function foo () {
                   ^----

there is no such a space.
I couldn't find it in any built-in standard, or did I just miss it?

A: You can easily extend or create your own standard. This is an example how requested functionality could be added to the PEAR standard (which is default).
<?php
//DisallowSpaceBeforeParenthesisSniff.php

class PEAR_Sniffs_Methods_DisallowSpaceBeforeParenthesisSniff implements PHP_CodeSniffer_Sniff
{
    public function register()
    {
        return array(T_FUNCTION);
    }

    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        do {
          $stackPtr++;
          $type = $tokens[$stackPtr]['type'];
        } while ('T_OPEN_PARENTHESIS' != $type);

        if ('T_WHITESPACE' == $tokens[$stackPtr-1]['type']) {
            $error = 'Spaces before parenthesis and after function name are prohibited. Found: %s';
            $place = $tokens[$stackPtr-2]['content'] .
                $tokens[$stackPtr-1]['content'] .
                $tokens[$stackPtr]['content'];
            $error = sprintf($error, $place);
            $phpcsFile->addError($error, $stackPtr-1);
        }
    }
}

The following file is located under: /usr/share/php/PHP/CodeSniffer/Standards/PEAR/Sniffs/Methods
Example:
<?php

// test.php
class abc
{
    public function hello ($world)
    {

    }
}

bernard@ubuntu:~/Desktop$ phpcs test.php
FILE: /home/bernard/Desktop/test.php
--------------------------------------------------------------------------------
FOUND 5 ERROR(S) AFFECTING 2 LINE(S)
--------------------------------------------------------------------------------
 2 | ERROR | Missing file doc comment
 2 | ERROR | Missing class doc comment
 2 | ERROR | Class name must begin with a capital letter
 4 | ERROR | Missing function doc comment
 4 | ERROR | Spaces before parenthesis and after function name are prohibited.
   |       | Found: hello (
--------------------------------------------------------------------------------

I hope this will help you


text:
Q: Local normal form of a (several complex variable) holomorphic map at a point? Suppose $F\colon\Omega\subseteq\mathbb C^m\to\mathbb C^n$ is a holomorphic map. WLOG, $0\in\Omega$ and $F(0)=0$. I want to determine the local normal form of $F$, i.e. classifying $F$ up to local biholomorphic coordinate changes:
$$
\require{AMScd}
\begin{CD}
\Omega_0@>F>>\mathbb C_0^n\\
@V\sim VV@V\sim VV\\
\Omega_0'@>F'>>\mathbb C_0^n
\end{CD}
$$
When $m=n=1$, the result is well-known: $F$ is either a constant function, or locally $z\mapsto z^n$. On the other hand, when $F'(0)$ is injective or surjective, then implicit function theorem tells us that $F$ is locally equivalent to $F'(0)$, which is classified up to congruence. When $m,n>1$, maybe there's no complete classification, but I want some partial results.
Thoughts: Maybe we can view the problem formally. Instead of holomorphic maps, we can consider formal power series, especially when $n=1$. Weierstrass preparation theorem might work.
Background: I learnt that injective holomorphic maps $\mathbb C^n\to\mathbb C^n$ are biholomorphic. The proof in the course is approximately this. However, such a proof doesn't give any information on the classification of maps. I'm just looking for a result which is strong enough to prove that proposition.
Any idea? Thanks!


text:
Q: AndroidJUnit4.class is deprecated: How to use androidx.test.ext.junit.runners.AndroidJUnit4? For my instrumentation tests I was using
@RunWith(AndroidJUnit4.class)

from
import androidx.test.runner.AndroidJUnit4;

in order to establish my test cases. Now this line gets marked as deprecated with the hint to use AndroidJUnit4 from
import androidx.test.ext.junit.runners.AndroidJUnit4

However if I try to import AndroidJUnit4 from the named package I get the error, that ext can not be resolved.
Do you have an idea, what package should be included in gradle to resolve this issue?

A: In my case changing androidTestImplementation to testImplementation helped.
I did't know the difference before reading this android difference between testImplementation and androidTestImplementation in build.gradle

A: *

*Include these lines in build.gradle app module.
testImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'

*In the test class replace your test runner to
import androidx.test.ext.junit.runners.AndroidJUnit4;

*If InstrumentationRegistry.getTargetContext() is deprecated use InstrumentationRegistry from androidx.test.platform.app like this
InstrumentationRegistry.getInstrumentation().getTargetContext()

A: If you've tried @MarcelGangwisch's solution and your build fails saying it can't find the resource AND you also cleaned/rebuilt your project and it still doesn't work, try this:
(based also on @KrzysztofDziuba's solution)
In your gradle file where you changed the dependency, make sure you are adding it as the type you need, ie.:
For UI tests:

androidTestImplementation 'androidx.test.ext:junit:1.1.0'

For Unit tests:

testImplementation 'androidx.test.ext:junit:1.1.0'

In my instance I added it as both and now it works.

A: According to the documentation for AndroidJUnit4,

*

*The gradle file should contain the following line:

androidTestImplementation 'androidx.test.ext:junit:1.1.1'

*Change test class to AndroidJUnit4ClassRunner from AndroidJUnit4
If it still doesn't work, make sure that you clean and/or rebuild your project. Also you can check the current version directly in Google's maven repository

A: If you imported those AnroidX test libraries, synced and re-built the project, but the imported packages were still not resolved. Just remember how you upgraded your project to AndroidX, close Android Studio and remove the .idea folder and reopen your project again...
This worked for me !

A: For me the following steps worked:
1. Replace the androidx libraries with the one posted here . my final app/build.gradle looked like this:
android {
    ...
    defaultConfig {
        ...
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

    }
    ...
}

dependencies {
    ...
    testImplementation 'junit:junit:4.12'

    // Core library
    androidTestImplementation 'androidx.test:core:1.2.0'

    // AndroidJUnitRunner and JUnit Rules
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test:rules:1.2.0'

    // Assertions
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.ext:truth:1.2.0'
    androidTestImplementation 'com.google.truth:truth:0.42'

    // Espresso dependencies
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}

I then manually replaced the imported modules in my ExampleInstrumentTest.java class with latest classes:
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4ClassRunner.class)
public class ExampleInstrumentedTest {
    ...
    @Rule
    public final ActivityTestRule<MainActivity> main = new ActivityTestRule<>(MainActivity.class, true);

    @Before
    public void init() {
        ...
    }
    @Test
    public void listCount() {
        ...
    }

    @Test
    public void useAppContext() {
        Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();

        Assert.assertEquals("in.curioustools.aad_x_testing2", appContext.getPackageName());
        System.out.println("useAppContext : Test Ran");
    }
}

The thing that was bugging me was the fact that InstrumentationRegistery class was still deprecated. So i used InstrumentationRegistry.getInstrumentation().getTargetContext(); from androidx.test.platform.app.InstrumentationRegistry class.

A: Solution

*

*Add this line in to build.gradle: androidTestImplementation 'androidx.test.ext:junit:1.1.1'

*Change AndroidJUnit4 to AndroidJUnit4ClassRunner in the test class
Warning
I got the same error, but the following solution failed for me:
File -> Invalidate Caches..., and select Invalidate and Restart

A: I tried all given above until I went to the official Android site,  and they suggested importing from androidx.test.ext.junit.runners.AndroidJUnit4 instead of androidx.test.runner.AndroidJUnit4. link


text:
Q: QtCharts add custom axis I would need to have custom axis on QtCharts. However, these lines cause crash.
chart->addAxis(axisX, Qt::AlignCenter);
chart->addAxis(axisY, Qt::AlignCenter);

Please, can you provide example how to customize the axis? The intent is to have some specified range and axis title.
QtCharts::QValueAxis *axisX = new QtCharts::QValueAxis();
axisX->setRange(0, 3);
axisX->setTitleText("x");
QtCharts::QValueAxis *axisY = new QtCharts::QValueAxis();
axisY->setRange(0, 3);
axisY->setTitleText("y");

QtCharts::QScatterSeries *series0 = new QtCharts::QScatterSeries();
for (uint i=0; i<size; i++)
    series0->append(vector4.at(i), vector6.at(i));

series0->setName("scatter1");
series0->setMarkerShape(QtCharts::QScatterSeries::MarkerShapeRectangle);
series0->setMarkerSize(10.0);

QtCharts::QChart *chart = new QtCharts::QChart();
chart->addSeries(series0);
chart->createDefaultAxes();
//chart->addAxis(axisX, Qt::AlignCenter);   CRASH
//chart->addAxis(axisY, Qt::AlignCenter);

QtCharts::QChartView *chartView = new QtCharts::QChartView();
chartView->setChart(chart);
chartView->show();

Thanks in advance

A: After some time I found the solution. It could help to someone.
chart->createDefaultAxes();
chart->axes(Qt::Horizontal).back()->setRange(-35, 135);
chart->axes(Qt::Vertical).back()->setRange(-35, 50);
chart->axes(Qt::Horizontal).back()->setTitleText("axis x [mm]");
chart->axes(Qt::Vertical).back()->setTitleText("axis y [mm]");

A: Try this:
  chart->addAxis(axisX, Qt::AlignBottom);
  chart->addAxis(axisY, Qt::AlignLeft);

Chart centre is not valid place for an axis, I suppose.


text:
Q: ASP MVC3 - ActionLink not routing to controller properly Below is the action link I'm using in an ASP MVC3 view. I need to a method in the controller and send in two variables. These variables serve as the compound key on a SQL table that the controller method is trying to pull information from.
The link appears to be rendered properly by the @Html.ActionLink, however I am getting this error:
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.
Requested URL: /BankListMasterController/AgentEdit/11
Here is the action link
@Html.ActionLink("Edit Agent", "AgentEdit", "BankListMasterController",
                                            new { agentId = int.Parse(item.AgentId), id = item.ID }, null)

Here is the controller method
    public ViewResult AgentEdit(int id, int agentId)
    {
        string compare = agentId.ToString();

        BankListAgentId agent = (from c in db.BankListAgentId
                                 where c.ID == id &&
                                       c.AgentId.Equals(compare)
                                 select c).Single();

        return View("AgentEdit", agent);
    }

and here is the URL that is rendered in the original view
http://localhost:2574/BankListMasterController/AgentEdit/11?agentId=5309721

I've also put a breakpoint in the first line of the method and it never gets tripped when debugging.

A: You do not need to include "controller" in the third parameter.
Try:
@Html.ActionLink("Edit Agent", "AgentEdit", "BankListMaster", new { agentId = int.Parse(item.AgentId), id = item.ID }, null)


text:
Q: Delivery Confirmation For Sent Mail My requirement is to send E-Mail Alerts to various customers for our client for which, we're planning to use JavaMail API. However, once mail is sent, we need to update status in DB as Sent/Delivered/Failure depending on the status of the mail. Please tell me how do we get Delivery Notification for the mail reaching the Mail Server of the Receiver. It's not necessary to ensure whether the person has read the mail or not, however, it will be great if we'll be able to know that. The mandatory thing to check is for delivery. How can we get the status. What I read was that using 'SMTPMessage' we can get the status, however, I couldn't find a code sample for how to read the Notification. I am putting my code which is very sample of what I have done till now. Please let me know how I can achieve the thing which we are trying to fulfill.
public class MailSender {
    private int port = 25;
    private String host = "testmailsrvr";
    private String from = "test@test.com";
    private boolean auth = true;
    private String username = "test";
    private String password = "test@123";
    private Protocol protocol = Protocol.SMTP;
    private boolean debug = true;

    public void sendEmail(String strMailID, String strSubject, String strBody) throws MessagingException{
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        switch (protocol) {
        case SMTPS:
            props.put("mail.smtp.ssl.enable", true);
            break;
        case TLS:
            props.put("mail.smtp.starttls.enable", true);
            break;
        case SMTP:
            props.put("mail.smtp.ssl.enable", false);
            break;
        }

        Authenticator authenticator = null;
        if (auth) {
            props.put("mail.smtp.auth", true);
            authenticator = new Authenticator() {
                private PasswordAuthentication pa = new PasswordAuthentication(username, password);
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return pa;
                }
            };
        }

        Session session = Session.getInstance(props, authenticator);
        session.setDebug(debug);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        InternetAddress[] toAddress = {new InternetAddress(strMailID)};
        message.setRecipients(Message.RecipientType.TO, toAddress);

        message.setSubject(strSubject);
        message.setSentDate(new Date());

        message.setText(strBody);
        Transport.send(message);
    }
}

A: You'll want to read these JavaMail FAQ entries:

*

*If I send a message to a bad address, why don't I get a SendFailedException or TransportEvent indicating that the address is bad?

*When a message can't be delivered, a failure message is returned. How can I detect these "bounced" messages?
Then read the javadocs for the com.sun.mail.smtp and com.sun.mail.dsn packages to learn about Delivery Status Notifications.

A: You will have to approach the issue differently. The Transport.send() method will throw a SendFailedException if it runs into problems sending to any of the recipients. The exception will give you information on which recipient addresses failed. You should catch that exception, get the failing addresses and record them.

A: You might want to look into http://www.ultrasmtp.com.  This service will send a notice back to the recipient upon the message being accepted, deferred, or refused by the receiving mail server.  There is also an option to setup alerts for opened messages.


text:
Q: $\mathbf H R$ is a ring spectrum if $R$ is a ring The first example of a ring spectrum is probably the Eilenberg-McLane spectrum of a ring $R$. But how is the multiplication $\mu: \mathbf H R \wedge \mathbf H R \to \mathbf H R$ defined? Probably this is so trivial that no book includes an explanation, but I really can not figure this out.
I am using the basic definition of spectra as sequential, possibly CW-, spectra given by Adams, I have found details on the multiplication on Schwede's book on symmetric spectra, but I am still not comfortable with those.


text:
Q: How to safely check .NET Framework version using a .NET Framework version that may not exist? I have an application built with .NET 3.5. If a user runs it without having .NET 3.5 installed, I want to have control of what they see and perhaps provide a message that they can understand (with a link to .NET 3.5) versus unhandled exception stack traces. But if they don't actually have .NET 3.5 how can my application control anything?

A: Are you assuming that at least SOME version of .NET is installed?
You could write a small loader to be compatible with all versions to do the check.
Or if .NET is not installed, found a simple batch program (though this could easily be done in C++ if you prefer).
@ECHO OFF
SET FileName=%windir%\Microsoft.NET\Framework\v1.1.4322
IF EXIST %FileName% GOTO Skip
ECHO.You currently do not have the Microsoft® .NET Framework 1.1 installed.
ECHO.This is required by the setup program for MyApplication.
ECHO.
ECHO.The Microsoft® .NET Framework 1.1 will now be installed on you system.
ECHO.After completion setup will continue to install MyApplication on your system.
ECHO.
Pause
SET FileName=
Start /WAIT .\dotnetfx.exe
Start .\Setup.exe
ECHO ON
Exit
Tongue Tiedkip
SET FileName=
Start .\Setup.exe
ECHO ON
Exit

This might also help.

A: You could instead consider using an installer that requires 3.5 is installed. That would prevent the app from getting to the user in the first place if they can't run it.

A: Better yet, you could use an installer technology, such as Wix or a Visual Stuido setup project, that checks during installation that all the prerequisites for you software, such as a particular .NET framework runtime exist. If not, it will install them, or at least tell the user where to get them and what to do next

A: You need an non .NET EXE file that checks for the .NET runtimes. It could be written in anything that you know exists in the target PC. For example, if targeting Windows 2000 or above, you know the Visual Basic 6.0 runtime is present, so your installer could always start a Visual Basic 6.0 splash application that checks for the runtimes before starting your .NET EXE file. A better way would be to write a C++ application that didn't rely on any runtime other than the Windows APIs.


text:
Q: Django single website structure I want to start a new django project. This will just be a relatively simple website to test django itself. So the way all tutorials structure their project is this:

*

*mysite

*

*mysite

*some_app

*...

For me it's not very clear what does what. I don't really need any app right now. Could I implement my website without using any app? Should I use an app? What would it be called for a simple website?

A: Have you read Django doc already?
They have a nice tutorial on how to get started.
As for apps, in Django, you have a project containing one or more app. If you just want to try to build a simple website, your project called mysite will contain only one app.

A: I think you don't need more than the main mysite, BUT, at the django documents, have a session that says:

If your background is in plain old PHP (with no use of modern
  frameworks), you're probably used to putting code under the Web
  server's document root (in a place such as /var/www). With Django, you
  don't do that. It's not a good idea to put any of this Python code
  within your Web server's document root, because it risks the
  possibility that people may be able to view your code over the Web.
  That's not good for security.
Put your code in some directory outside of the document root, such as
  /home/mycode.

This model may have been designed with focus on safety.
Some files in mysite could be used to control things in another apps, so i think that is a 'best pratice' to follow this model.
Font

A: if u aren't in need of an app you can avoid creating one. just give your view in views.py of your project set the url and u r all set to go.
here the first mysite folder is just an usual folder u can change the name in ur convenience next mysite is your project folder and recommended not to change it and next some_app is the application name(you can name your app anything relevant but in proper convention.)
and follow django documentation and djangogirls tutorial for better understanding.
https://docs.djangoproject.com/en/2.0/
https://tutorial.djangogirls.org/en/


text:
Q: Laravel 5 Middleware not working properly I have define a middleware in laravel 5. But when I login it redirect me to dashboard but dashboard doesn't show and an error occurred. I have upload a picture of it.
http://imgur.com/a/1fCwt
AdminAuth.php
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class AdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check())
        {
            $user = Auth::user();
            return redirect()->route('admin_display_dashboard');
        }  else {
            return redirect()->route('admin_display_login');
        }
    }
}

Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],
        'api' => [
            'throttle:60,1',
        ],
    ];
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'adminAuth' => \App\Http\Middleware\AdminAuth::class,
    ];
}

Route.php
Route::group(['middleware' => ['adminAuth']], function () {

Route::get('admin/dashboard', array('as'=>'admin_display_dashboard', 'uses'=>'AdminViewController@displayDashboard'));

});

A: what's in your admin_display_dashboard() and admin_display_login(), you sure there is no redirect or so in there.
Meanwhile try this
 if(!Auth::check())
 {

    return redirect()->route('admin_display_login');
 }

 $user = Auth::user();

 return $next($request);


text:
Q: Android - C++ compile errors in cygwin/android-ndk Ive created a simple app to help me learn the ndk, jni, and get my c++ skills back up to par. However Im kind of stuck because Im getting some compile errors when I run ndk-build on my project from the cygwin command line. Its been a while since Ive used c++ to any extent so I know that my syntax is probably way off so if some one could help me clean this up or explain how I could do so then that would be awesome.....so heres my c++ code:
EDIT: latest code
#include <iostream>
#include <Eigen/Dense>
#include <math.h>
#include <jni.h>

using namespace Eigen;

Vector3f vec;
Vector3f vec2;
Vector3f vecRtrn;

void vecLoad(float x, float y, float z, float x2, float y2, float z2){

vec(0) = x;
vec(1) = y;
vec(2) = z;
vec2(0) = x2;
vec2(1) = y2;
vec2(2) = z2;

}

void vecAdd(Vector3f vecA, Vector3f vecB){
vecRtrn = vecA+vecB;
}

extern "C"
{
JNIEXPORT jfloatArray JNICALL Java_jnimath_act_JnimathActivity_test
(JNIEnv *env, jobject obj, jfloatArray fltarray1, jfloatArray fltarray2){

float array1[3];

jfloatArray flt1 = fltarray1;
jfloatArray flt2 = fltarray2;

//flt1 = env->GetFloatArrayElements( fltarray1,0);
//flt2 = env->GetFloatArrayElements( fltarray2,0);

vecLoad(flt1[0], flt1[1], flt1[2], flt2[0], flt2[1], flt2[2]);
vecAdd(vec, vec2);

array1[0] = vecRtrn[0];
array1[1] = vecRtrn[1];
array1[2] = vecRtrn[2];

return array1;

};
}

Now Im pretty sure Im not using the correct way to return the array back to java through jni but thats a separate problem......but please feel free to comment on that as well ;)
Heres an updated list of the last couple of build errors I have.....its definitely a lot shorter than the original list :)
$ /cygdrive/c/android-ndk-r7/ndk-build
Compile++ thumb  : test <= test.cpp
jni/test.cpp: In function '_jfloatArray* Java_jnimath_act_JnimathActivity_test(JNIEnv*,  _jobject*, _jfloatArray*, _jfloatArray*)':
jni/test.cpp:42: error: cannot convert '_jfloatArray' to 'float' for argument '1' to      'void vecLoad(float, float, float, float, float, float)'
jni/test.cpp:49: error: cannot convert 'float*' to '_jfloatArray*' in return
make: *** [obj/local/armeabi/objs/test/test.o] Error 1

EDIT: heres my java code......
package jnimath.act;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class JnimathActivity extends Activity {
/** Called when the activity is first created. */

public EditText x;
public EditText y;
public EditText z;

public EditText x2;
public EditText y2;
public EditText z2;

public float[] vecArray;

public TextView textView1;
public Button run;

float[] array3 = new float[3];
float[] array1 = new float[3];
  float[] array2 = new float[3];

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    x = (EditText)findViewById(R.id.x);
    y = (EditText)findViewById(R.id.y);
    z = (EditText)findViewById(R.id.z);

    x2 = (EditText)findViewById(R.id.x);
    y2 = (EditText)findViewById(R.id.y);
    z2 = (EditText)findViewById(R.id.z);

    textView1 = (TextView)findViewById(R.id.textView1);
    run = (Button)findViewById(R.id.run);

    run.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {

            array1[0] = Float.parseFloat(x.getText().toString());
            array1[1] = Float.parseFloat(y.getText().toString());
            array1[2] = Float.parseFloat(z.getText().toString());

            array2[0] = Float.parseFloat(x2.getText().toString());
            array2[1] = Float.parseFloat(y2.getText().toString());
            array2[2] = Float.parseFloat(z2.getText().toString());
            array3 = test(array1, array2);

            String text = array3[0]+" "+array3[1]+" "+array3[2];
            textView1.setText(text);

        }

      });

  }

  public native float[] test(float[] array1, float[] array2);

  static {
    System.loadLibrary("test");
  }
}

A: As the error states, compiler does not like what you have in vecLoad. Are you sure Vector3f has correct '(' operator? I would check that first.

A: The first error is due to net specifying a size for float array1[];  Unlike java this isn't allowed.  You can on the other hand specify the array as float *array1; without initializing it.
The second and third error refer to you dereferencing your pointer before using the -> operator.  The correct way to do it would be:
flt1 = env->GetFloatArrayElements(env, fltarray1, NULL);
flt2 = env->GetFloatArrayElements(env, fltarray2, NULL);

The last error you are just missing a number it looks like it should be flt2[2] instead of flt[2].


text:
Q: Firebase and Node.js application results in the requested URL was not found on this server for the firebase serve command I have created a Node.js application and trying to deploy in the Firebase for hosting. Before deploying, I am making sure that it will work properly using the command firebase serve --only hosting,function. This command creates the server and I am able to access the Home page of the application using the URL (localhost:5000) provided by Firebase but for some reason, my Angularjs HTTP request is unable to find the Node.js controller due to which I am getting the 404 URL not found error in the brwoser.
As soon as the index.html is accessed using the localhost:5000 I am trying to populate various dropdown options in my frontend. These options are present within the Node.js controller file populator.js. Hence I am making an HTTP request from angularjs to my node.js controller but I get the 404 URL not found error. I am guessing there is some issue with folder structure or the firebase.json file due to which the code is unable to find my Node.js controller.
My firebase.json file:
{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "function": "app"
      }
    ]
  }
}

My index.js file:
const   functions                   =   require("firebase-functions");
const   express                     =   require('express');
const   app                         =   express();

//call function to popultae the fields
app.get('/populateFields', function(req,res){
    populateFields.BusinessStep(function(data){
        res.send(data);
    });
});

exports.app      =   functions.https.onRequest(app);

Here is my folder structure
Firebase Hosting (root)
    |--functions
        |---index.js
        |---package.json
    |
    --public
        |---index.html
    |
    --firebase.json
    --.firebaserc

I tried running the command firebase serve --only hosting,function in both the root directory and within the functions folder but none worked and still getting the error The requested URL was not found on this server.
I found many post related to this issue but could not find there solution after trying the methods mentioned there hence posting this question.

A: I was running the command wrongly so I was getting that issue the actual command is
firebase serve --only functions,hosting
If anyone is facing the issue then run the command correctly.

A: "I was running the command wrongly so I was getting that issue the actual command is
firebase serve --only functions,hosting"
I guess that the error was for specifying function instead of functions


text:
Q: Same padding on the sides with media queries When I resize the browser window to under 768 px the boxes is getting different padding on the sides of my column boxes: See the example here.
I tried to set a media query with something like this, but I am aware of that it is not the correct way to do it at all:
@media only screen and (max-width: 768px) {
    .small-padding-left {
            padding-left: 7.5px;
        }

    .col-sm-8 {
        padding-right: 7.5px;
    }

}

Does anybody knows a good way how I can achieve this? This is my code so far:
/* Global CSS*/
    .row > div{
        margin-bottom: 15px;
    }
    .content{
        background: #b4bac0;
        min-height: 300px;
    }
    /* When there is 2 columns on top of eachother */
    .sidebar{
        background: #b4bac0;
        min-height: 300px;
    }
    .sidebar-top{
        min-height: 140px;
        background: #dbdfe7;
    }
    .sidebar-bottom{
        min-height: 145px;
        background: #7e8aa0;
        margin-bottom: -15px;
    }
    /* Padding used for the core CSS */
    .small-padding.top {
       padding-top:5px;
    }

    .small-padding.bottom {
        padding-bottom:5px;
    }
    .small-padding.left {
        padding-left:7.5px;
    }

    .small-padding.right {
        padding-right:7.5px;
    }
    /* Media quries */
    @media only screen and (max-width: 768px) {
        .small-padding-left {
                padding-left: 7.5px;
            }

        .col-sm-8 {
            padding-right: 7.5px;
        }

    }

A: You need to add some custom css to make it work the right way. Try adding this code to your css file.
.row {
  margin-left: -7.5px;
  margin-right: -7.5px;
}

.row>[class*="col-"] {
  padding-left: 7.5px;
  padding-right: 7.5px;
}

A: In your example  the issue happens in below 575 width.
please update the media query in your css file
@media only screen and (max-width: 575px) {
.small-padding.right
{
padding-right: 15px;
}
.small-padding.left
{
padding-left: 15px;

}
}


text:
Q: Thread pool in each api request vs single application pool reuse I want to run few task in parallel on each request I receive from client . I am using spring boot to run server and on HTTP api call it calls getItems method . I am using Executors.newCachedThreadPool() to spawn multiple threads . I need few inputs on below implementation

*

*Is it good to have ExecutorService thread pool with each request or create a pool once for application and reuse it?

*How to decide the pool size for the Executors service.

@Override
            public List<Item> getItems(List<String> id) {
                List<Item> items = new ArrayList<>();
                ExecutorService execSvc = Executors.newCachedThreadPool();
                List<Callable<Item> > inventories = id.stream()
                        .map((itemId)-> (Callable<Item>) () -> {
                            List<InventoryNode> inventoryNodes =  getInventory(itemId);
                            return getItem(inventoryNodes);
                        }).collect(Collectors.toList());
                try {
                    List<Future<Item>> results = execSvc.invokeAll(inventories);
                    for(Future<Item> inventory :results){
                        if(inventory.isDone()){
                            items.add(inventory.get());
                        }
                    }
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }finally {
                    execSvc.shutdown();
                }
                return items;
            }

A: A thread is an independent path of execution through program code. Creating a thread is an expensive task. There is a lot of work needs to be done like allocating memory, initializing the thread stack.

*

*It is good to create thread pool once
for the application and not on each request. It reduces overhead and
latency in processing the request. In Spring boot you can define a
bean for this.
 @Bean("cachedThreadPool")
 public ExecutorService cachedThreadPool() {
    return Executors.newCachedThreadPool();
 }

*Consider a database connection with a
maximum pool size of 50. It doesn't make sense to have a thread pool
of 100 in this case. So it is always better to decide on maximum
numbers of threads based on the use case you're on.

A: You can use spring ThreadPoolTaskExecutor. Here you can configure pool size, max pool size, queue size etc.
@Bean
ThreadPoolTaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setCorePoolSize(500);
    taskExecutor.setMaxPoolSize(1000);
    taskExecutor.setQueueCapacity(200);
    taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    return taskExecutor;
}

Check this fore maxPoolSize, corePoolSize, queueSize.


text:
Q: Foundation 4: Use rows in orbit slider I am using Foundation 4 with the Orbit slider.
I want to use it as a content-slider.
Is it possible to put the rows from foundation in the orbit slider without messing up the margins from Orbit?

Hallo

Doei

There are 3 slider-items. 2 divs with row classes and 1 full-width image.
This example messes with the margins from the class row.
I want to add margins so the divs with row classes will align in the middle.

A: I'm not sure I understand your question well, but if you want 3 slides (2 with text on the middle of the large screen and 1 with the image) I think this code should work (however I didn't test it):
If you add the .large-centered classes to the
 tags, they will align the texts to the middle automatically, and you don't have to care about the margins in css.

Hallo

Doei


text:
Q: Footer Semantic UI Hi this is my first time using semantic-ui framework & I have some problem with footer. I want to make footer to always stick in the bottom of page (not fixed).
this is the simple html of mine
<!DOCTYPE html>

I was trying use this css:
body {
    position: relative;
    height: 100%;
}

.footer {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
}

but it doesn't work, it just work when the height of page is less than 100% of the monitor height, when it's height have more than 100% of monitor height the footer will float like this:

I also already change the css body with this:
    body {
        position: relative;
        min-height: 100%;
    }
but still doesn't work, anyone can help?
This is the full code, I made a long list table so you would know when you click the filter it will push the table down and the footer will mess.

body {
  height: 100%;
  color: #696F84;
  position: relative;
}
.menu {
  border-radius: 0 !important;
}
.item {
  color: #696F84 !important;
}
.logo {
  margin-right: 7px !important;
}
.company {
  font-family: 'Righteous', cursive;
  font-weight: normal;
  font-size: 27px;
  color: #515151;
  padding-bottom: 2px;
}
.desc {
  position: relative;
  background-color: #EEEEEE;
  margin-top: -1rem;
  padding: 30px 0;
  font-family: Raleway;
  font-size: 24px;
  color: #757575;
}
#filter {
  width: 100%;
  margin: 20px 0;
}
.footer {
  background-color: #212121;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 15px 0;
}
<link href="//oss.maxcdn.com/semantic-ui/2.1.6/semantic.min.css" rel="stylesheet" />

Company Name

"Description here | Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard."

      Filter

                  <input type="radio" name="size" value="small">
                  Small

                  <input type="radio" name="size" value="medium">
                  Medium

                  <input type="radio" name="size" value="large">
                  Large

                  <input type="radio" name="size" value="x-large">
                  X-Large

                  <input type="checkbox" name="small">
                  Red

                  <input type="checkbox" name="medium">
                  Orange

                  <input type="checkbox" name="large">
                  Green

                  <input type="checkbox" name="x-large">
                  Blue

                    Name

                  <input type="text" placeholder="your name">

                  <input type="hidden" name="gender">

Gender

Male

Female

        No
        Food
        Code
        Calories
        Protein
        Action

        1
        Apples
        Ap
        200
        0g

        2
        Orange
        Or
        310
        0g

        3
        Mango
        Mg
        360
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

  Micro Tech 2015. All Rights Reserved

A: add a warp div like below

  .......

 ......

and set css
.main{min-height:100%;
      padding-bottom:60px;
      box-sizing:border-box;}
.footer {
  background-color: #212121;
  position: absolute;
  /* bottom: 0;  remove this */
  margin-top: -50px; /* add this */
  left: 0;
  width: 100%;
  padding: 15px 0;
}

body {
  height: 100%;
  color: #696F84;
  position: relative;
}
.menu {
  border-radius: 0 !important;
}
.item {
  color: #696F84 !important;
}
.logo {
  margin-right: 7px !important;
}
.company {
  font-family: 'Righteous', cursive;
  font-weight: normal;
  font-size: 27px;
  color: #515151;
  padding-bottom: 2px;
}
.desc {
  position: relative;
  background-color: #EEEEEE;
  margin-top: -1rem;
  padding: 30px 0;
  font-family: Raleway;
  font-size: 24px;
  color: #757575;
}
#filter {
  width: 100%;
  margin: 20px 0;
}
.main{min-height:100%; padding-bottom:60px; box-sizing:border-box;}
.footer {
  background-color: #212121;
  position: absolute;
  /* bottom: 0;  remove this */
  margin-top: -50px; /* add this */
  left: 0;
  width: 100%;
  padding: 15px 0;
}
<link href="//oss.maxcdn.com/semantic-ui/2.1.6/semantic.min.css" rel="stylesheet" />

Company Name

"Description here | Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard."

      Filter

                  <input type="radio" name="size" value="small">
                  Small

                  <input type="radio" name="size" value="medium">
                  Medium

                  <input type="radio" name="size" value="large">
                  Large

                  <input type="radio" name="size" value="x-large">
                  X-Large

                  <input type="checkbox" name="small">
                  Red

                  <input type="checkbox" name="medium">
                  Orange

                  <input type="checkbox" name="large">
                  Green

                  <input type="checkbox" name="x-large">
                  Blue

                    Name

                  <input type="text" placeholder="your name">

                  <input type="hidden" name="gender">

Gender

Male

Female

        No
        Food
        Code
        Calories
        Protein
        Action

        1
        Apples
        Ap
        200
        0g

        2
        Orange
        Or
        310
        0g

        3
        Mango
        Mg
        360
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

        4
        Grape
        Gr
        210
        0g

  Micro Tech 2015. All Rights Reserved

A: Just set
.footer{
 position:fixed;
 bottom:0;
}

fixed position in this case is the best way to position your footer always on the bottom.

A: OP stated he does not want a fixed footer
This is what is causing your issue:
body, html {
    height: 100%;
}

height should not be set for your footer to be at the bottom (it comes from semantic.min.css).
To cancel this, add this at the beginning of your CSS stylesheet (!important is needed here to override the value set by the other stylesheet, but you should otherwise avoid using it at all costs):
body, html {
  height: auto!important;
}

body {
  font-size: 40px;
  position: relative;
}

.footer {
  background-color: black;
  color: red;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
}

  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
  tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
  quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
  consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
  cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
  proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

  some footer at the bottom


text:
Q: How communicate two remote machine through ansible I am running ansible playbook from system 1 which runs tasks on system 2 to take backup and after that, I want to copy backup file from system 2 to system 3.
I am doing this task for automating below command
where /bck1/test on system 2 and opt/backup on system 3
rsync -r -v -e ssh /bck1/test.* root@host3:/opt/backup

A: You can run the raw rsync command with the shell module.
tasks:
  - shell: rsync -r -v -e ssh /bck1/test.* root@host3:/opt/backup

For this to work, you will either need to have your private ssh key deployed to system 2, or, preferable enable ssh agent forwarding, for example in your .ssh/config:
Host host2
    ForwardAgent yes

Additionally sshd on system 2 would need to accept agent forwarding. Here are some tasks which I use to do this:
- name: Ensure sshd allows agent forwarding
  lineinfile: dest=/etc/ssh/sshd_config
              regexp=^#?AllowAgentForwarding
              line="AllowAgentForwarding yes"
              follow=yes
              backup=yes
  sudo: yes
  register: changed_sshd_config

- name: "Debian: Restart sshd"
  shell: invoke-rc.d ssh restart
  sudo: yes
  when:
    - ansible_distribution in [ "Debian", "Ubuntu" ]
    - changed_sshd_config | changed

- name: "CentOS 7: Restart sshd"
  shell: systemctl restart sshd.service
  sudo: yes
  when:
    - ansible_distribution == "CentOS"
    - ansible_distribution_major_version == "7"
    - changed_sshd_config | changed

There are two separate tasks for restarting sshd on Debian and CentOS7. Pick what you need or maybe you have to adapt that to your system.
You might need to configure this in a separate playbook. Because Ansible will keep an open ssh connection to the host and after activating agent forwarding you most probably will need to re-connect.
PS: It's not the best idea to allow ssh login for user root, but that is another topic. :)


text:
Q: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 96 path This is my json
{
    "success": true,
    "error": null,
    "responseA": {
        "responseB": [{
                    "response": {...},
                    "request": "\/observations\/atlanta,ga"
                }, {
                    "response": [{...}],
                    "request": "\/forecasts\/atlanta,ga"
                },
                ...
            ]
    }
}

I creat my class for the json from here:
http://www.jsonschema2pojo.org/
and I find the error of the title is from the two "response" which are array and object.
As I said Ianalyze the that by Retrofit, How can I analy a json like this with the "repsonse" of two types(array and object) by Retrofit2.0? Thanks~*
Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();`

This is log:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 96 path $.response.responses[0].response
      at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)
      at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
      at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
      at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
      at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)
      at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)
      at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)
      at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)
      at com.google.gson.Gson.fromJson(Gson.java:810)
      at com.google.gson.Gson.fromJson(Gson.java:775)
      at retrofit.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:36)
      at retrofit.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:24)
      at retrofit.OkHttpCall.parseResponse(OkHttpCall.java:148)
      at retrofit.OkHttpCall.execute(OkHttpCall.java:116)
      at retrofit.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:61)

A: there is mistake in your json:
responseB first object has a response object and second object has response array. this is creating problem
{

"success":true,

"error":null,

"responseA":{

  "responseB":[
     {

        "response":{... ***// This is object***
              },
        "request":"\/observations\/atlanta,ga"
     },
     {
        "response":[   ***// This is Array***
           { ...
              }
        ],
        "request":"\/forecasts\/atlanta,ga"
     },
... ]

} }

You have make a same structure for arrays object.
Hope this help.
Thanks


text:
Q: TypeScript XAML framework As a .NET/XAML developer I am wondering if anybody has started to write a framework which will replace Silverlight and Flex using technologies like TypeScript and XAML to produce HTML5, JavaScript and CSS cross platform desktop apps or RIA's.
If not, wouldn't it be great to have a framework which understands XAML (or just XML) to define the user interface and JavaScript or better TypeScript to code the view controller?
I know, Sencha has done a great job building a JavaScript framework called EXT JS to build rich internet- or desktop applications, but from a .NET developer perspective EXT JS sucks.
A .NET developer likes to design the UI's using tools like Blend or Visual Studio with the ability to hack code in XAML and not in JSON.
There is also a good approach called Zebra which renders completely inside an html-canvas, but it isn't XAML based and there is no ability to use themes at all.
Also jQuery UI and jQuery Mobile are great frameworks from an HTML developer perspective, but I am looking for a XAML based framework, because you have to code less in XAML than in HTML. There is also the ability to use Blend to design the UI.
I have asked myself this question months ago when Adobe gave away Flex and Microsoft didn't admit to extend Silverlight 5 and I answered it with:
Microsoft or Adobe should do this for us.
But today I think now it is up to us.
Depending on your feedback I would like to start such a framework as an open source project, but I hope that there is still one on the way^^

A: You don't really need XAML to write an HTML application as XAML is really just another kind of mark-up.
From your WPF/Silverlight experience, you will find that the following concepts were actually borrowed from HTML anyway:

*

*XAML is mark-up for content, which is what HTML is

*Resources are styles and behaviours, which is what CSS is

Some parts actually don't map directly, some of the triggers in your WPF program may be either CSS or JavaScript in a web application, for example. Also, in HTML attributes are used less than I have seen them used in WPF - normally all sizes and layouts are placed in CSS, not attributes in the mark-up.
You may not directly have a substitute for every available WPF control, but you will find that most things are possible.
Although there will be a learning curve involved in picking up HTML, CSS and JavaScript if you haven't used them extensively, they are useful tools in your tool-belt.

A: Correct me if I am wrong, but I believe you are looking for http://fayde.wsick.com.  I am in the midst of rebuilding the framework in Typescript.  Check out my blog at http://faydeproject.blogspot.com/.

A: there is also rAppid:Js http://www.rappidjs.com which is XAML based, but it's not made to work with Visual Studio or Expression blend.
A XAML framework for HTML/JS is a fantastic idea, XAML files could be converted in HTML5 or perhaps in JavaScript directly by having an InitializeComponents() method where all objects are instantiated (like in WinForms).
If you decide to start a such project, consider using a C# to JavaScript compiler like Saltarelle or Script#.

A: Search the Web for
"M&P H5J is Silverlight in HTML5"
it implements an XAML processor in TypeScript.


text:
Q: Caching content of Virtual Documents I made my TextDocumentContentProvider for virtual documents. I'm generating the content of the file on the go, and it looks like VS Code is caching the content of the file. This is a problem for me. I expect to see a new number in the text of the document every time. Does anyone know how to get around this without using random numbers in the filename?
const vscode = require('vscode');

class MyVirtualDocument {
    constructor() {
        this.onDidChangeEmitter = new vscode.EventEmitter();
        this.onDidChange = this.onDidChangeEmitter.event;
    }
    provideTextDocumentContent(uri) {
       return "Test String for uri: " + uri.path + "\nRandom number: " + Math.floor(Math.random() * 65535) + ".";
    }
};

function activate(context)
{
    context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider('myvirtualdocument', new MyVirtualDocument()));

    context.subscriptions.push(vscode.commands.registerCommand('myvirtualdocument.open', () => {
        vscode.workspace.openTextDocument(vscode.Uri.parse('myvirtualdocument:1.txt')).then(doc => {
             vscode.window.showTextDocument(doc, { preview: true });
        });
    }));
}

function deactivate(){}
module.exports = {activate, deactivate}


text:
Q: Firefox and IE not rendering SVG I have a set of SVG images, which are rendered perfectly in Chrome and Opera, but fail to display in FF and IE11 and Edge. Here is one such SVG source:
<?xml version="1.0" encoding="UTF-8"?>
<svg width="16px" height="17px" viewBox="0 0 16 17" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

    <title>bin</title>
    <desc>Created with Sketch.</desc>
    <defs></defs>
    <g id="add-to-cart" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <path d="M1.77777778,4.44355556 L1.77777778,15.1102222 C1.77777778,16.0897778 2.57511111,16.888 3.55555556,16.888 L12.4444444,16.888 C13.4248889,16.888 14.2222222,16.0897778 14.2222222,15.1102222 L14.2222222,4.44355556 L1.77777778,4.44355556 Z M7.11111111,13.3333333 L5.33333333,13.3333333 L5.33333333,8 L7.11111111,8 L7.11111111,13.3333333 Z M10.6666667,13.3333333 L8.88888889,13.3333333 L8.88888889,8 L10.6666667,8 L10.6666667,13.3333333 Z M10.6666667,1.77688889 L16,1.77688889 L16,3.55466667 L0,3.55466667 L0,1.77688889 L5.33333333,1.77688889 L5.33333333,0 L10.6666667,0 L10.6666667,1.77688889 Z" id="bin" fill="#00cc66" fill-rule="nonzero"></path>
    </g>
</svg>

The SVG is displayed in HTML like so:

        <svg>
            <image href="image/bin.svg" />
        </svg>

CSS:
svg {
    width: 28px;
    height: 28px;
    padding: 8px 6px 6px 6px;
}

svg image {
    width: 16px;
    height: 100%;
}

I tried changing and disabling the explicit width/height properties in CSS, but to no avail. The svg tag is getting resized to any large size, however the image tag stays 0 x 0.
In Chrome and Opera the image is displayed correctly. In the other browsers I can see the size is set to 0 x 0. When I open the image separately in FF, it is displayed fine. In FF network tab, I can see the image in the "response" field, it also says "Size: 16 x 17" in the "response" field. Same in Edge. In IE11, the "response" field shows the image, but says "Size: 0 x 0".
I did notice that IE is complaining I should use explicit closing tag for the "image" tag. Firefox automatically adds these:
<image href="image/bin.svg"></image>

However even if I add the closing tags, it still doesn't work.
I think there is something wrong with this SVG, or the way I am displaying it. Unfortunately I cannot give you a public link for the site, it is currently under development, and will only be available to registered users later.


text:
Q: Referencing a range using hyperlink I'm looking for a solution of hyperlinking a cell.
For example:

*

*On Sheet one I have details

*

*for XYZ from B1 to D5

*for ABC B7 to D11.

*On sheet two I have XYZ and ABC. If I click in sheet two XYZ then the entire details should open and same for rest.

Currently I'm able to hyperlink from B1 to D5, B7 to D11 and so on.
I'm facing problem if I insert two rows for XYZ: now XYZ is from B1 to D7 and ABC has gone two columns down from B9 to D13. Here the hyperlink is not referring to B1 to D7. It is still referring B1 to D5.

A: To make your hyperlinks following their target you need to use the Hyperlink function:˛
=HYPERLINK("[name of workbook]"&ADDRESS(ROW(B1),COLUMN(B1),1,1,"Sheet One")&":"&ADDRESS(ROW(D5),COLUMN(D5),1,1))
This way link will be updated as you insert / delete rows / columns.


text:
Q: Finding the closest difference between 2 degrees of a compass - Javascript I'm basically trying to find how many degrees apart two points of a compass are.  For example if a person is facing 270 and their compass is 280 there are 10 degrees between those 2 points.  I'd also like a negative number if it's to the left and positive to the right, relative to the 1st heading.
The problem comes when the to headings are 350 and 020 for example.  These two points are 30 degrees apart but would give a result of -330.
Below is an example of my code:
function ConvertToRadians(_var)
{
    return _var * (Math.PI/180);
}
function ConvertToDegrees(_var)
{
    return _var * (180/Math.PI);
}
function GetHeadingDiff(_Heading1, _Heading2)
{
    return ConvertToDegrees((ConvertToRadians(_Heading2) - ConvertToRadians(_Heading1)));
}

$(document).ready(function (){
    $('#process').click(function (e){
        e.preventDefault();
        var Hdg1 = parseFloat($('#heading1').val());
        var Hdg2 = parseFloat($('#heading2').val());
        $('#results').html(GetHeadingDiff(Hdg1,Hdg2));
    });
});

<input id="heading1" type="text" />
<input id="heading2" type="text" />
<button id="process" type="button">Submit</button>
<div id="results">
</div>

I'm sure there is some simple math function I'm missing, I just can't seem to figure it out.
Here is a jsfiddle link http://jsfiddle.net/dTmPn/3/

A: first of, why are you doing back and forth conversion of radians and degrees?
look at this. http://jsfiddle.net/dTmPn/5/
var diff = _Heading2-_Heading1;
if(diff>180) diff-=360;
if(diff<-180) diff+=360;
return diff;

is that enough?

A: function GetHeadingDiff(_Heading1, _Heading2)
{
    return (_Heading2-_Heading1+540) % 360 - 180;
}

Examples:
GetHeadingDiff( 280, 270 )
-10
GetHeadingDiff( 270, 280 )
10
GetHeadingDiff( 350, 20 )
30
GetHeadingDiff( 20, 350 )
-30

A: im not sure how you expect it to work, (which it doesnt i tried 10-30 and got 19.999996) but this would be the general idea based on your code.
sum1 = ConvertToDegrees((ConvertToRadians(_Heading2) - ConvertToRadians(_Heading1)));
sum2 = ConvertToDegrees((ConvertToRadians(_Heading1) - ConvertToRadians(_Heading2)));

return sum1 < sum2 ? sum1 : sum2;

this does you calculation twice in opposite directions and returns the smaller sum.
i would do it like this:
function GetHeadingDiff(s1, s2)
{
    r1 = (s1 - s2 + 360 ) % 360;
    r2 = (s2 - s1 + 360 ) % 360;

    return r1<r2?r1:r2;
}

fiddle


text:
Q: passing dataframe data to python selenium xpath I have a xpath into which I need to add a variable data:
browser.find_element_by_xpath("//span[contains(@class,'urLblPadding') and contains(text(),'"+notif_status_name+"')]").click()

If I pass data directly, then it will work. Else I get an error. I checked data from dataframe. It is showing correct data only.
Error:
File "C:\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)

I tried this :
browser.find_element_by_xpath("//span[contains(@class,'urLblPadding')[contains(text(),'%s')]" % notif_status_name']).click()

I got error :
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//span[contains(@class,'urLblPadding')[contains(text(),'0    UYTY
Name: notif_status, dtype: object')]' is not a valid XPath expression.

Here UYTY is what I want. But it adds 0 UYTY

A: your syntax is incorrect. try:
browser.find_element_by_xpath("//span[contains(@class,'urLblPadding')[contains(text(),'%s')]" % notif_status_name).click()

the issue is that you've messed with quotes.


text:
Q: Avaya IP Office - "Invalid community specified in SNMP request" I have an Avaya IP office which is configured to send errors by email. It is normally quiet, however it sometimes decides to send a stack of emails containing:
Invalid community specified in SNMP request
I can reproduce by pointing a SNMP client at the PBX with the wrong community string. One would think that there must be a monitoring daemon (e.g. nagios) configured somewhere with the wrong community string, but this is not the case. I have enabled as much debugging as I can on the PBX to try and find out what IP address it is coming from, but so far no luck.
Just wondering if anyone has seen this sort of behaviour on the Avaya IP office before? Or some way to determine what is connecting to it with the wrong SNMP community string?
I am tempted to set up port mirroring on the switch and capture SNMP traffic!

A: Setup port mirroring on the switch and use Wiresharek to determine where the SNMP traffic is coming from. You've got something else on your network querying it by SNMP using an invalid community string.


text:
Q: Accessing the registry through the .NET Framework shows 1 thing; Regedit shows another I'm posting here because this question has nothing to do with how to program something and everything to do with a screwed up computer.
When I run the following line of VB .Net code in the Visual Studio 2010 Immediate Window:
MsgBox(My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Control Panel\Desktop\ProductName",                                               "SCRNSAVE.EXE", Nothing))

then I get the following message box:
---------------------------
Screensaver State Checker
---------------------------
C:\Windows\system32\PhotoScreensaver.scr
---------------------------
OK
---------------------------

This makes no sense because the registry doesn't even have a SCRNSAVE.exe entry in the screenshot.

In fact, the current screensaver according to the Windows Control Panel is "(None)."
By the way, prior to this little exercise with VB .Net, I was having all sorts of problems trying to get the screensaver to turn on at the right times.
How can I fix this problem?
System Information:

*

*ThinkPad T400

*Windows 7 Ultimate 32-bit edition

*More info upon request

A: Patrick S had the right answer:
your code is looking at HKEY_CURRENT_USER\Control Panel\Desktop\ProductName, but your screenshot stops at the Desktop key. Drop the "\ProductName" from the code, as your screenshot is correct.


text:
Q: VMware tools is not working after update ubuntu 16.04 I have Ubuntu 16.04 installed as a virtual machine using VMware on a Windows 10 host. After upgrading Ubuntu, VMware tools is no longer working and my system is experiencing problems as a result of that. For example, I can not copy/paste between my OSes, and my screen resolution is limited to 1680x1050.
I've tried reinstalling the VMware Tools, but that did not resolve my problem.
Is there anything I can do?


text:
Q: Elegant transformation of various rules to strings, {f[z_] -> y} becomes "f = @(z) y" Assume that I have some function for transformation mathematica expressions to strings.  For simplicity, just assume it is an identity:
mytostring[e_] := ToString[e]; (* In reality, much more complicated... *)

What I want to take various permutations of variadic rules syntax and apply this function to create a string for the function.  e.g. assume my basic test is:
rulestostring[rule_????] := ???
testrules = {f[x,y] -> x, f[x_,y_] -> x, f[x,y] :> x, f[x_,y_] :> x};

(* Create a function rulestostring where all of these give the same output as a string:
==>    "f = @(x,y) x"
Where the f is actually generated from mytostring[f], x is from mytostring[x], etc.
*)

I need it to support variadic arguments and a few other things:
otherrules = {f[x_] -> x, f[x[bar]] -> x[bar]};
(* ==>   {"f = @(x) x", "f = @(x[bar]) x[bar]"
where in reality both x[bar] would be transformed by mytostring
*)

(you can probably guess that what I am doing is extending the http://library.wolfram.com/infocenter/MathSource/577/ package to generate matlab functions.  If anyone has an updated version of this package it would be appreciated)

A: ruleToString[(Rule | RuleDelayed)[h_[a__], rhs_]] :=
  ToString @ Row[{h, " = @(", Row[{a} /. Pattern -> (# &), ","], ") ", rhs}]

Test:
ruleToString /@ testrules // Union

{"f = @(x,y) x"}

ruleToString /@ otherrules

{"f = @(x) x", "f = @(x[bar]) x[bar]"}

Based on communication in comments I propose this as a more complete solution:
Options[ruleToString] = {Format -> mytostring};

ruleToString[(Rule | RuleDelayed)[h_[a__], rhs_], OptionsPattern[]] :=
  With[{fn = OptionValue[Format]},
    ToString@Row[{fn@h, " = @(", Row[fn /@ ({a} /. Pattern -> (# &)), ","], ") ", fn@rhs}]
  ]

You can then change the function that is used to convert elements by using SetOptions, or by providing the option Format -> function directly in ruleToString.


text:
Q: Expectation of the log of a ratio of two lognormal random variables with additive constants I have two independent lognormal random variables $X$ and $Y$ with known means and variances. I would like to know the expected value and the variance of $\ln\big((X+1)/(Y+1)\big)$. If there is no exact solution, is there a means of approximation?
I have tried a Taylor expansion on $\ln(X+1) - \ln(Y+1)$ as suggested in an answer to the question Expected value of a natural logarithm. Unfortunately, the Taylor expansion does not provide a good estimate for one of the lognormal random variables I am working with.
To provide more detail on the problem and in particular the failed Taylor expansion, I have $X=\exp\big((m-Z)/v\big)$ where $Z$$\sim$$N(\mu,\sigma^2)$ with constants $m>0$ and $v>0$. This implies:
$E[X]=\exp\big(\frac{m-\mu}{v} + \frac{1}{2}(\frac{\sigma}{v})^2\big)$
and
$V[X]=\Big[\exp\big((\frac{\sigma}{v})^2\big) - 1\Big]\centerdot\exp\big(2\frac{m-\mu}{v} + (\frac{\sigma}{v})^2\big)$.
If I run a simulation where I set $\mu=9024$ and $\sigma=600$ to generate a large sample of $n$ random variates of $Z$, and using R code mean(log(exp((m - Z)/v) + 1)) to take the average of the $n$ by $\ln(x+1)$ variates with $m=8900$, $v=400$, by the central limit theorum I get $E\big(\ln(X+1)\big)\approx0.7784$. However, plugging those values into the Taylor expansion I get:
$E\big(\ln(X+1)\big)\approx\ln(E[X] + 1) - \frac{V[X]}{2(E[X]+ 1)^2}\approx-0.8577$.


text:
Q: Exclude code coverage in assemblyinfo file I want to know how we can set the Exclude code coverage attribute for few files from assemblyinfo file? I am aware that we can set the attribute at class level but in my case I do not want to go to each of these classes and set the attribute.
I will like to set this attribute at a higher level or at a single place from where I can easily manage this. I believe we can do it in assemblyinfo file but not sure.

A: Use a .runsettings file to configure the code coverage as specified here:
http://msdn.microsoft.com/en-us/library/jj159530.aspx
in that file use the "Source" element to exclude the source files you want to leave out.
        <Sources>
          <Exclude>
            <Source>.*\\Model\\.*</Source>
          </Exclude>
        </Sources>


text:
Q: Stub "new Date()" with Cypress In my tests, "new Date()" returns the current date, but I want it return a constant object. But I don't know how to stub this. Example of what I would like :
cy.stub(Date, 'constructor', () => {
  return new Date(2020, 6, 24, 22, 19, 00)
})

How to do this ? Thanks

A: Try this approach:
cy.clock(new Date(2020, 6, 24, 22, 19, 00), ['Date'])

A: Refer: Specify a now timestamp.
In app code:
// element

// script
document.getElementById('mockedDate').innerText = new Date();

it('stub date', () => {
    cy.clock(new Date(2020, 6, 24, 22, 19, 0).getTime());
    cy.visit('http://localhost:8081/?j=test');
    cy.get('#mockedDate').invoke('text').then(cy.log);
});

A: Not sure about cy.stubbing the Date, but for anyone experiencing issues when using cy.clock & having all sorts of setIntervals which break the cy.visit, etc.
I was able to mock the new Date() by simply overwriting the global win.Date
my.spec.ts
export class FakeDate extends Date {
  constructor(date) {
    super(date)
    if (date) {
      return new Date(date)
    }
    // The date you want
    return new Date('Fri Apr 29 2022 01:59:59 GMT+0200 (Central European Summer Time)')
  }
}
// ...
cy.visit('my-page', {
  onBeforeLoad(win) {
    win.Date = FakeDate
  }
})


text:
Q: SSH refused after updating from wheezy to jessie I have a Raspberry Pi Model B and I updated it this afternoon from wheezy to jessie. I connect headlessly with VNC and SSH (usually the latter) because I play around with home LAMP and nodeJS servers.
Both worked fine before the upgrade. Since upgrading to jessie, SSH has been refusing my connections. The error is:
ssh: connect to host 192.168.2.3 port 22: Connection refused

So, I double checked the IP - no problem there. Then, I checked the hostname and users, both are correct. Then, I tried clearing my RSA keys on both the Mac and the Pi. No luck.
Finally, I checked to make sure the SSH daemon was actually running. And, it wasn't. So, I went through raspi-config and started SSH. I checked again with service ssh status and still got an empty response.
So, my question is: why isn't the SSH service starting and could it have something to do with updating to jessie?
If so, is my only option to reflash with wheezy?

A: First of all check that /etc/ssh/sshd_config is valid and service should listen on port 22. Then check iptables rules:
iptables -L -nvx

(Eventually /etc/iptables/rules.v4 if you're chrooted into the system).
You can check /var/log/auth.log for messages like:
error: Could not load host key: /etc/ssh/ssh_host_rsa_key

which might mean that some keys are missing, check with:
ls -al /etc/ssh/ssh*key

Easiest way how to fix this would be:
dpkg-reconfigure openssh-server

Jessie uses sort of hybrid mode for running services, there should be /etc/init.d/ssh script and also systemd config. Systemd ssh service should be enabled:
systemctl is-enabled ssh

in case that it's not, enable with systemctl enable ssh.
Make sure that /var/run/sshd directory exists:
/bin/mkdir -p -m0755 /var/run/sshd

And finally you can try running sshd in debug mode:
/usr/sbin/sshd -f /etc/ssh/sshd_config -d


text:
Q: How to test whether the activity has not been routed with Robolectric? I have an activity which is as simple as this:
class HomeActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)

        if (!this.userPreference.memberRegistered) {
            goToActivity(AuthActivity::class.java)
        }
    }
}

So if the user is registered, it will stay at HomeActivity, otherwise it will route to AuthActivity.
userPreference is a wrapper around SharedPreference. Works well and well tested in another codebase.
I first tried whether RuntimeEnvironment from Robolectric could do the trick or not, and it works of course.
@Test
fun try_test() {
    val userPreference = UserPreference(
        Settings(SETTINGS_NAME, RuntimeEnvironment.application.applicationContext)
    )

    // default value should be false, PASS
    assertEquals(false, userPreference.memberRegistered)

    // change it to true, then it should be true, PASS
    userPreference.memberRegistered = true
    assertEquals(true, userPreference.memberRegistered)
}

Then I tried whether the route to AuthActivity works or not, and it works. The test pass.
@Test
fun should_go_to_AuthActivity_when_1st_start() {
    val homeActivity = Robolectric.setupActivity(HomeActivity::class.java)
    val expectedIntent = Intent(homeActivity, AuthActivity::class.java)
    val actual = ShadowApplication.getInstance().nextStartedActivity
    assertEquals(expectedIntent.component, actual.component)
}

Problem
Then the problem is I don't know how to check if the activity stays at HomeActivty when this.userPreference.memberRegistered = true. The following test failed due to the reason that actual is null. It is because there is no routing happen, so nextStartedActivity is null, but how to verify that it stays at this activity from the test?
@Test
fun should_stay_at_HomeActivity_when_already_member() {
    val userPreference = UserPreference(
        Settings(SETTINGS_NAME, RuntimeEnvironment.application.applicationContext)
    )

    userPreference.memberRegistered = true

    val actual = ShadowApplication.getInstance().nextStartedActivity
    assertEquals(
        actual.component.shortClassName,
        ".ui.home.HomeActivity"
    )
}


text:
Q: How to reflow DIV boxes in CSS to stick to bottom right? Let's say I have a DIV that's styled as a square, and it has squares (DIV) inside of it. I'd like the squares inside the main DIV to stack in the lower right. I can use float: right to to get them on the right edge, but how do I make them stack at the bottom rather than the top?

A: To get a child to stick to the very bottom of a container, set the position:relative and bottom:0px.  However this will not stack them, you'd have to set the bottom to another value for a child to be above another child.  You could use javascript or jquery to dynamically fit them if the sizes are variable like this:
$('#second_element').css('bottom', $('#bottom_element').height() + 5);

Note: 5 is just for padding

A: You can use display:table-cell with vertical-align:bottom
Here's a good tutorial on using "table-cell" layout:
http://www.digital-web.com/articles/everything_you_know_about_CSS_Is_wrong/

A: Depending on what you mean by "stack at the bottom", you can achieve this with the use of an inner container div that is aligned at the bottom.  Then these child squares can be float right inside of this container div, causing them to stick to the bottom of the main div, like so:

Square 1 Content

Square 2 Content

Square 3 Content

What this would do is flow these squares right to left at the bottom of the main div.  However, these child squares would still flow top to bottom inside the container div.  If you wanted them to vertically flow in reverse (bottom up), I'm not sure if that would be possible without some complex layout javascript.
Obviously, the exact styling of "right_floated_square" has been removed for brevity.

A: Should you not find a good CSS solution, jQuery can easily handle this:
Fiddle
$('.inner').each(function(i) {
    $this = $(this);
    var bottomPos = ($this.outerHeight())*i;
    $this.css('bottom', bottomPos);
});

HTML and CSS

One

Two

Three

Four

A: Here is a pure css version: http://jsfiddle.net/zkhWA/1/
Basically place your little squares in another absolutely positioned element that is grounded to the bottom right corner of the big square using:
position: absolute;
right: 0px;
bottom: 0px;

Then make all the little squares float right:
float: right;

Don't forget to apply position:relative to the big square.


text:
Q: Как правильно закрыть объект ms word в OleContainer Мой MS Word имеет СОМ нештатную надстройку (DIRECTUM), которая "прихватывает" открытый файл своим процессом. Не знаю зачем.
Если закрывать файл в оболочке Word, то все будет нормально.
Если рабочий файл открыть в OleContainer:
oc1.CreateObjectFromFile(LMDLabel1.Caption,false);

затем
oc1.Close;
oc1.DestroyObject;

то процесс надстройки не завершается. После завершения моей программы выдается сообщение об ошибке COM и в каталоге остается файл с тильдой.
Что нужно сделать, чтобы файл в OleContainer закрывался корректно как в оболочке Word?

A: Нашел пример, может поможет:
var
  SaveChanges: OLEVariant;
  OriginalFormat: OLEVariant;
  RouteDocument: OLEVariant;
begin
  SaveChanges := wdDoNotSaveChanges;
  OriginalFormat := unAssigned;
  RouteDocument := unAssigned;
  oc1.Quit(SaveChanges, OriginalFormat, RouteDocument);
end;


text:
Q: My real AdMob adUnitID doesn't work but i can see test ones EDITED: Okay so after googling a little bit more. I found this other stackoverflow post that says that it might even take 12 hours for the production AdMob to be activated. If that occurs, I will close this post.
I made an iOS game and I added some AdMob. Created the AdMob account, linked my game with the itunesconnect app info. So everything seemed to be working fine.
Afterwards, they give you the real adUnitID. But when I add it, it doesn't show up. Only when I use the test ones.
Why is that? am I doing something wrong ? or this is on purpose?
Here's my code:
var googleBannerView: GADBannerView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.googleBannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
        self.googleBannerView.adUnitID = "ca-app-pub-3940256099942544/6300978111"
        self.googleBannerView.rootViewController = self
        //for testing simple : ca-app-pub-3940256099942544/6300978111
        //for testing interstitial : ca-app-pub-3940256099942544/1033173712
        //for production : ca-app-pub-6797599317996282/85919XXXXX
        let request = GADRequest()
//        request.testDevices = ["d0acc1d1423027d2d259f6bb2cbb9652"]
        self.googleBannerView.loadRequest(request)

        self.googleBannerView.frame = CGRectMake(0, self.view.bounds.height - self.googleBannerView.frame.size.height,
                                                 self.googleBannerView.frame.size.width, self.googleBannerView.frame.size.height)

//        self.googleBannerView.hidden = true
        self.view.addSubview(self.googleBannerView)

    }

    func adViewDidReceiveAd(bannerView: GADBannerView!) {
        self.googleBannerView.hidden = false
    }

    func adView(bannerView: GADBannerView!, didFailToReceiveAdWithError error: GADRequestError!) {
        self.googleBannerView.hidden = true
    }


text:
Q: Django - For loop brings QuerySet but can't get individual data (as if blank) in HTML template I have a django project.
Some tables with some info already in place.
I can't see the individual data when applying a FOR LOOP
I revised the code. Looked it up and found no apparent mistake.
Can anyone help me?
Views.py:
from django.shortcuts import render
from .models import Client, Address

main_title = 'Company Name'

def home(request):
    client_list = Client.objects.all()
    address_list = Address.objects.all()
    contex = {
        'address_list' : address_list,
        'main_title'   : main_title,
        'client_list'  : client_list,
    }
    return render(request, 'home.html', contex)

in home.html
{% for i in address_list %}

{{ i }}

{% endfor %}

And all I see when going in the browser are the bullet points
*
*

The source code in the browser is loading as:

Now if i change the html code for something without a for loop like
{{ address_list }}

Then the browser shows:
<QuerySet [<Address: THIS IS THE FIRST ADDRESS >, <Address: THIS IS THE SECOND ADDRESS >]>

In other words. The database data is coming trough,
But when inside a for loop i gets empty.
But I know there are two entries. Because it show two bullet points

EDIT:
After sometime. I striped the code down to the bare minimum and tried to pin-point the problem.
When I finaly figured it out.
my class in the models.py was
class Client(models.Model, RegexValidator):

Once i removed the RegexValidator
it worked.
For some stupid reason I tought i had to include RegexValidator in that line.
All solved now

A: I guess this is because you try to access a dictionary I had a similar problem with nested dictionaries a few weeks before.
My solution in the html temaplte looked like follows:
{% for key, value in exampleDict.items %}

Display Key Name {{ key }}

        {% for item in value %}

Item: {{ item }}

        {% endfor %}

{% endfor %}

My code in views.py looked like follows
items = Item.objects.order_by('-date_taken')
items_dict = {}

for item in items:
   date_key = str(item.date_taken.year) + '-' + str(item.date_taken.month)
   if date_key not in items_dict.keys():
      items_dict[date_key] = {}
   items_dict[date_key][item.filename] = item.filename
return render(request, 'items/allitems.html', {'itemsDict': items_dict})

A: EDIT:
After sometime. I striped the code down to the bare minimum and tried to pin-point the problem.
When I finaly figured it out.
my class in the models.py was
class Client(models.Model, RegexValidator):
Once i removed the RegexValidator it worked.
For some stupid reason I tought i had to include RegexValidator in that line.
All solved now


text:
Q: Cannot open terminal in 18.04 I have a recent installation of Ubuntu 18.04.1.
When I open a terminal, a tab shows in the taskbar for a few sencods but then it fades away. The same with Files
I've seen other users suggest to change the language but did not work for me.
Not much I can add for now

A: I just moved the .gnome folder from tty2. Pressed
Ctrl + Alt + F2 to log in into tty2
then used
mv .gnome .gnome.backup

This is /home/myuser/
And voila! it's working again