text:
Q: How does one load some variables at runtime in Photoshop Script? I have about 200 folders with X images in each of them.
I have a master script in the root folder that does some stuff to the images.
Each folder has some variables specific to it and its contents.
I want my master script, when it parses folder Y, load some sort of a config file from within folder Y to get those variables, then when folder Z is to be parsed, load the config file from that one.
I know of #include "config.jsx" that I use at the moment to load it but its at the beginning of the script, I need something dynamic and doesn't need to be a jsx at all.

A: I store all my parameters in xml format and read that in using the XML objects in extendscript.  As long as your parameters file is always named something like 'config.xml' it is easily located.
var file = new File( /c/folder/file.xml );
file.open("r");
var str = file.read();
var xml = new XML(str);


text:
Q: JAX-RS integration test with Undertow failing in Jenkins but working locally I have an JAX-RS integration test that works locally, both in IntelliJ (using Gradle to run the test) and Gradle command line .
But when I run the test in Jenkins, the test fails, with some issue during the Undertow deployment.
This is how I start the container :
public static void startContainer() throws ServletException {
  System.setProperty("org.jboss.resteasy.port", "8085");
  server = new UndertowJaxrsServer().start();

  ResteasyDeployment deployment = new ResteasyDeployment();
  deployment.setInjectorFactoryClass("org.jboss.resteasy.cdi.CdiInjectorFactory");
  deployment.setApplicationClass(MyApp.class.getName());
  DeploymentInfo di = server.undertowDeployment(deployment);
  di.setClassLoader(Server.class.getClassLoader());
  di.setResourceManager(new ClassPathResourceManager(Server.class.getClassLoader()));
  di.setContextPath("/vincent-service");
  di.setDeploymentName("DI");
  di.addListeners(Servlets.listener(org.jboss.weld.environment.servlet.Listener.class));
  server.deploy(di);
}

When the test runs in Jenkins, I get a NullPointerException :

java.lang.RuntimeException: java.lang.NullPointerException    at
io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:254)
at
org.jboss.resteasy.plugins.server.undertow.UndertowJaxrsServer.deploy(UndertowJaxrsServer.java:266)

...

Caused by: java.lang.NullPointerException     at
org.jboss.weld.module.web.servlet.WeldInitialListener.contextInitialized(WeldInitialListener.java:94)
at
org.jboss.weld.servlet.api.helpers.ForwardingServletListener.contextInitialized(ForwardingServletListener.java:34)
at
org.jboss.weld.environment.servlet.Listener.contextInitialized(Listener.java:121)
at
io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187)
at
io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:217)
at
io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:186)
at
io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
at
io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at
io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:252)

Looking in Weld source code (in weld-web-3.1.2.Final), it seems the exception is thrown from the last line here :
@Override
public void contextInitialized(ServletContextEvent sce) {
    final ServletContext ctx = sce.getServletContext();
    // First try to use the context id obtained from the servlet context (OSGi, Servlet containers, etc.)
    if (beanManager == null) {
        String contextId = ctx.getInitParameter(Container.CONTEXT_ID_KEY);
        if (contextId != null) {
            List<BeanManagerImpl> managers = new ArrayList<BeanManagerImpl>(Container.instance(contextId).beanDeploymentArchives().values());
            Collections.sort(managers, BeanManagers.ID_COMPARATOR);
            beanManager = managers.get(0);
        }
    }
    // servlet containers may not be able to inject fields in a servlet listener
    if (beanManager == null) {
        beanManager = BeanManagerProxy.unwrap(CDI.current().getBeanManager());
    }

Part of the test is running though, as I can see these logs :

[2021-10-06T08:44:16.016Z] [io.undertow.Undertow] [Test worker] [117]
[INFO ] starting server: Undertow - 2.1.3.Final
[2021-10-06T08:44:16.016Z] [org.xnio.Xnio] [Test worker] [95] [INFO ]
XNIO version 3.8.0.Final
[2021-10-06T08:44:16.016Z] [org.xnio.nio.NioXnio] [Test worker] [59]
[INFO ] XNIO NIO Implementation Version 3.8.0.Final
[2021-10-06T08:44:16.016Z] [org.jboss.threads.Version] [Test worker]
[52] [INFO ] JBoss Threads version 3.1.0.Final
[2021-10-06T08:44:17.017Z]
[org.jboss.weld.environment.servlet.Listener] [Test worker] [115]
[INFO ] WELD-ENV-001007: Initialize Weld using ServletContextListener
[2021-10-06T08:44:17.017Z] [org.jboss.weld.bootstrap.WeldStartup] [Test worker] [231] [INFO ]  WELD-000101: Transactional services not available. Injection of @Inject UserTransaction not available. Transactional observers will be invoked synchronously.
[2021-10-06T08:44:17.017Z] [org.jboss.weld.event.ExtensionObserverMethodImpl] [Test worker] [86]
[INFO ] WELD-000411: Observer method [BackedAnnotatedMethod] protected
org.apache.deltaspike.core.impl.exclude.extension.ExcludeExtension.vetoBeans(@Observes
ProcessAnnotatedType, BeanManager) receives events for all annotated
types. Consider restricting events using @WithAnnotations or a generic
type with bounds.

[2021-10-06T08:44:17.017Z] [org.jboss.weld.event.ExtensionObserverMethodImpl] [Test worker] [86]
[INFO ] WELD-000411: Observer method [BackedAnnotatedMethod] public org.apache.deltaspike.core.impl.interceptor.interdyn.InterDynExtension.processAnnotatedType(@Observes
ProcessAnnotatedType) receives events for all annotated types.
Consider restricting events using @WithAnnotations or a generic type
with bounds.

[2021-10-06T08:44:17.017Z]
[org.jboss.weld.event.ExtensionObserverMethodImpl] [Test worker] [86]
[INFO ] WELD-000411: Observer method [BackedAnnotatedMethod] protected
org.apache.deltaspike.core.impl.message.MessageBundleExtension.detectInterfaces(@Observes
ProcessAnnotatedType) receives events for all annotated types.
Consider restricting events using @WithAnnotations or a generic type
with bounds.

[2021-10-06T08:44:17.017Z]
[org.jboss.weld.event.ExtensionObserverMethodImpl] [Test worker] [86]
[INFO ] WELD-000411: Observer method [BackedAnnotatedMethod] protected
org.apache.deltaspike.core.impl.interceptor.GlobalInterceptorExtension.promoteInterceptors(@Observes
ProcessAnnotatedType) receives events for all annotated types.
Consider restricting events using @WithAnnotations or a generic type
with bounds.

[2021-10-06T08:44:17.017Z]
[org.jboss.weld.event.ExtensionObserverMethodImpl] [Test worker] [86]
[INFO ] WELD-000411: Observer method [BackedAnnotatedMethod] public
org.apache.deltaspike.core.impl.config.ConfigurationExtension.findDynamicConfigurationBeans(@Observes
ProcessAnnotatedType<?>) receives events for all annotated types.
Consider restricting events using @WithAnnotations or a generic type
with bounds.

[2021-10-06T08:44:18.018Z]
[org.jboss.weld.logging.ValidatorLogger] [Test worker] [59] [WARN ]
WELD-001478: Interceptor class
org.apache.deltaspike.core.impl.throttling.ThrottledInterceptor is
enabled for the application and for the bean archive
/tankkarte-service_/var/jenkins_home/.gradle/caches/modules-2/files-2.1/org.apache.deltaspike.core/deltaspike-core-impl/1.9.4/709e0b27bb80e52fcd6a886a216ca3f9c2b8c28/deltaspike-core-impl-1.9.4.jar.
It will only be invoked in the @Priority part of the chain.
[2021-10-06T08:44:18.018Z] [org.jboss.weld.logging.ValidatorLogger]
[Test worker] [59] [WARN ] WELD-001478: Interceptor class
org.apache.deltaspike.core.impl.lock.LockedInterceptor is enabled for
the application and for the bean archive
/tankkarte-service_/var/jenkins_home/.gradle/caches/modules-2/files-2.1/org.apache.deltaspike.core/deltaspike-core-impl/1.9.4/709e0b27bb80e52fcd6a886a216ca3f9c2b8c28/deltaspike-core-impl-1.9.4.jar.
It will only be invoked in the @Priority part of the chain.
[2021-10-06T08:44:18.018Z] [org.jboss.weld.logging.ValidatorLogger]
[Test worker] [59] [WARN ] WELD-001478: Interceptor class
org.apache.deltaspike.core.impl.future.FutureableInterceptor is
enabled for the application and for the bean archive
/tankkarte-service_/var/jenkins_home/.gradle/caches/modules-2/files-2.1/org.apache.deltaspike.core/deltaspike-core-impl/1.9.4/709e0b27bb80e52fcd6a886a216ca3f9c2b8c28/deltaspike-core-impl-1.9.4.jar.
It will only be invoked in the @Priority part of the chain.
[2021-10-06T08:44:18.018Z] [org.jboss.weld.logging.ValidatorLogger]
[Test worker] [59] [WARN ] WELD-001478: Interceptor class
org.apache.deltaspike.core.impl.monitoring.InvocationMonitorInterceptor
is enabled for the application and for the bean archive
/tankkarte-service_/var/jenkins_home/.gradle/caches/modules-2/files-2.1/org.apache.deltaspike.core/deltaspike-core-impl/1.9.4/709e0b27bb80e52fcd6a886a216ca3f9c2b8c28/deltaspike-core-impl-1.9.4.jar.
It will only be invoked in the @Priority part of the chain.
[2021-10-06T08:44:18.018Z]
[org.jboss.weld.environment.undertow.UndertowContainer] [Test worker]
[39] [INFO ] WELD-ENV-001302: Undertow detected, CDI injection will be
available in Servlets, Filters and Listeners.
[2021-10-06T08:44:19.019Z] [org.jboss.weld.bootstrap.Validator]
[weld-worker-1] [200] [WARN ] WELD-001473:
javax.enterprise.inject.spi.Bean implementation
liquibase.integration.cdi.CDIBootstrap$1@7c73f99b declared a normal
scope but does not implement
javax.enterprise.inject.spi.PassivationCapable. It won't be possible
to inject this bean into a bean with a passivating scope
(@SessionScoped, @ConversationScoped). This can be fixed by assigning
the Bean implementation a unique id by implementing the
PassivationCapable interface.

[2021-10-06T08:44:20.020Z] [liquibase.logging.core.Slf4jLogger] [Test worker] [42] [INFO ]
Booting Liquibase 3.6.2
[2021-10-06T08:44:20.020Z] [liquibase.logging.core.Slf4jLogger] [Test worker] [42] [INFO ] SELECT
COUNT() FROM PUBLIC.DATABASECHANGELOGLOCK
[2021-10-06T08:44:20.020Z] [liquibase.logging.core.Slf4jLogger] [Test worker] [42] [INFO ] SELECT COUNT() FROM PUBLIC.DATABASECHANGELOGLOCK
[2021-10-06T08:44:20.020Z] [liquibase.logging.core.Slf4jLogger] [Test worker] [42] [INFO ] SELECT
LOCKED FROM PUBLIC.DATABASECHANGELOGLOCK WHERE ID=1
[2021-10-06T08:44:20.020Z] [liquibase.logging.core.Slf4jLogger] [Test worker] [42] [INFO ] Successfully acquired change log lock
[2021-10-06T08:44:21.021Z] [liquibase.logging.core.Slf4jLogger] [Test worker] [42] [INFO ] SELECT MD5SUM FROM PUBLIC.DATABASECHANGELOG WHERE MD5SUM IS NOT NULL
[2021-10-06T08:44:21.021Z] [liquibase.logging.core.Slf4jLogger] [Test worker] [42] [INFO ] SELECT COUNT(*) FROM PUBLIC.DATABASECHANGELOG
[2021-10-06T08:44:21.021Z] [liquibase.logging.core.Slf4jLogger] [Test worker] [42] [INFO ]
Reading from PUBLIC.DATABASECHANGELOG
[2021-10-06T08:44:21.021Z] [liquibase.logging.core.Slf4jLogger] [Test worker] [42] [INFO ] SELECT * FROM PUBLIC.DATABASECHANGELOG ORDER BY DATEEXECUTED ASC, ORDEREXECUTED ASC
[2021-10-06T08:44:21.021Z] [liquibase.logging.core.Slf4jLogger] [Test worker] [42] [INFO ]
Successfully released change log lock
[2021-10-06T08:44:21.021Z] [io.undertow.Undertow] [Test worker] [252] [INFO ] stopping server:
Undertow - 2.1.3.Final

But at some point, the exception is thrown..
Any idea of what I could check to understand why this fails only in my Jenkins environment ?
I am using org.jboss.resteasy 3.12.1.Final libraries.

redpajama_set_name: RedPajamaStackExchange


text:
Q: GROUP BY Precedence in MySQL I have two tables; one is called rules and the other data. The Rules table holds events, which have a description, id and date_created and is simply used to categorize events.
The data table has a date and id column; This stores the actual dates of an event, as events can span up to months long in dates.
My issue is this: I wish to select everything from data and group it by date, so each date is represented only once. However, the event with the most recent creation date should have precedence if there is a collision, i.e. two events happen on the same day. Here is what I've tried, which doesn't offer control over date_created:
SELECT d.date, r.description FROM data d LEFT JOIN rules r ON d.id = r.id GROUP BY date ORDER BY d.date
I haven't included date_created yet because I'm stuck, and not sure where it should go in the query to get the desired effect. Any ideas would be greatly appreciated!

A: From your question it seems to me that at first you need to select maximum date of event creation and then using subquery you can desired result:
SELECT a.date, b.description
FROM data a
INNER JOIN (
    SELECT id, description,MAX(date_created) as mdate
    FROM rules
    GROUP BY id,description
) b ON a.id = b.id AND a.date = b.mdate


text:
Q: Player matching in Google Play Services based on player ranking/skill Is there a way I can match players using Google Play Game Service based on individual players' skill level in the game?
I have locally stored the player level of each player, and want a player to be matched to his/her closest ranked player.
For example: a player ranked 10 (beginner) should be paired with the closest ranked player available (e.g. 5 to 15) instead of an expert level 100 player, so that we can have a balanced competition.

A: There are two variables that can be set to influence the match making:
First, you can set a variant of the game using RoomConfig.Builder.setVariant().  This method takes an non-negative value indicating the type of match.  The variant specified needs to match exactly with other participants in order for auto-matching to take place. I suppose you could be strict in your match making and use the variant as the player's level.  In this way, players would only be matched with players of the same level. An alternative would be to group levels together in a range, for example levels 1-5 could play each other, likewise group 6-8, etc.
The second variable is the exclusiveBitMask.  This is passed in when calling RoomConfig.CreateAutoMatchCritera().  This method takes the min and max number of players to match, and the exclusiveBitMask.  This mask when logically AND'ed with the other players will equal 0.  This is used for things like role based games (need to have 1 offense and 1 defense). One possible use of this would be to mask out high level vs. low level capabilities so there is no outrageous mismatch.

A: I think Clayton Wilkinson's answer is all correct and I voted it up.
But, I imagine the OP is hoping for some way to do skill-based matching without splitting the player-base into segments.
Sadly, the answer is no you can't. The choices are to use some other matchmaking system or split up your player base. If you choose to split your player base then you need a lot of concurrent users to avoid making your players wait a long time.
On a recent title we rolled our own matchmaking service based on Raknet because we wanted more nuanced matchmaking. It's a lot of hassle though, and GPGS is pretty great otherwise, so skill based matching would have to be a very high priority before you consider abandoning GPGS.


text:
Q: I want to know how to make a floating button in android studio that remains on the screen even after closing activity I want to know how to make a floating button or anything extra. In android studio that remains on the screen even after closing activity.

A: Whenever the activity is closed (I assume you mean the moment when onDestroy() method is called) every thread used by your app is closed until onCreate() method is called again.

A: i think you want to make a floating widget like messenger. please follow the bellow link.
https://www.androidhive.info/2016/11/android-floating-widget-like-facebook-chat-head/


text:
Q: Using cbgreek with Unicode input There is at least one package containing ancient Greek fonts written in
Metafont, cbgreek.  This is from its documentation:
% file test-cbgreek10pt.tex
\documentclass[12pt]{article}
\usepackage[greek]{babel}
\usepackage[T1]{fontenc}
\usepackage[10pt]{type1ec}%
\begin{document}
Qa'ire!
Ἔρρωσο!
\end{document}

The output is Χαίρε! + gibberish.  Is it possible to use this package
entering the Greek with normal Greek Unicode letters instead of
transliterating?

A: You have to specify the utf8 encoding in inputenc
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[greek]{babel}
\usepackage[T1]{fontenc}
%\usepackage[10pt]{type1ec}%
\begin{document}
  Qa'ire!
  Eρρωσο!
 \end{document}

Whose output is


text:
Q: Log4j java.lang.NoClassDefFoundError I couldnt understand what is causing this error:
ERROR>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/PropertyConfigurator

ERROR>Caused by: java.lang.ClassNotFoundException: org.apache.log4j.PropertyConfigurator

Already got the log4j-1.2.8.jar everywhere in the project but I couldnt make it. How can I make this error go away? Thanks!

A: Well, you haven't said what kind of application this is or basically given us any context. You need to make sure that the log4j classes are available to the classloader which is loading your application. If it's a standalone application run from the commandline, that's like to just be a case of specifying the -classpath command-line option. For example:
java -classpath .;log4j-1.2.8.jar org.foo.MyApplication

If you can give us more information, we're likely to be able to help you more.

A: Setp 1 : right click on your main method
Step 2 go to run as option then
Step 3 go to Run configuration
Step 4:  and add projects or jar files
now it works.


text:
Q: Not able to write proper function in asp.net mvc 3.0 i have one method and it will return IQueryable value
public IQueryable<TabMasterViewModel> Query(Expression<Func<TabMaster, bool>> whereCondition)
{
    IQueryable<TabMaster> tabmasters = _tabmasterRepository.GetQueryable().Where(whereCondition);
    IQueryable<TabMasterViewModel> tabmasterview;
    AutoMapper.Mapper.CreateMap<TabMaster, TabMasterViewModel>()
        .ForMember(dest => dest.colID, opt => opt.MapFrom(src => src.colID));
    tabmasterview = AutoMapper.Mapper.Map(tabmasters, tabmasterview);
    return tabmasterview;
}

and the GetQueryable is like
public IQueryable<T> GetQueryable()
{
    return this.ObjectSet.AsQueryable<T>();
}

but the following line
tabmasterview = AutoMapper.Mapper.Map(tabmasters, tabmasterview);

is giving me an error
Use of unassigned local variable 'tabmasterview'
please suggest me, where is am i wrong?

A: To fix the compiler error all you have to do is
 IQueryable<TabMasterViewModel> tabmasterview = null;

But the second argument you are passing to AutoMapper.Mapper.Map(tabmasters, tabmasterview) is always null as tabMasterview has not been intialized. If that is intended you could as well pass "null".
public IQueryable<TabMasterViewModel> Query(Expression<Func<TabMaster, bool>> whereCondition)
        {
            IQueryable<TabMaster> tabmasters = _tabmasterRepository.GetQueryable().Where(whereCondition);

            AutoMapper.Mapper.CreateMap<TabMaster, TabMasterViewModel>()
                  .ForMember(dest => dest.colID, opt => opt.MapFrom(src => src.colID));
            return AutoMapper.Mapper.Map<IQueryable<TabMaster>,  IQueryable<TabMasterViewModel>> (tabmasters);
        }

EDIT:
The above code answers your question related to compiler error.
As for your comments about the runtime error.. modify this line
return AutoMapper.Mapper.Map<IQueryable<TabMaster>,  IQueryable<TabMasterViewModel>> (tabmasters);

to
return AutoMapper.Mapper.Map<IQueryable<TabMaster>,  IEnumerable<TabMasterViewModel>> (tabmasters).AsQueryable<TabMasterViewModel>();


text:
Q: How can I convert this PHP code in a way that will allow me to add it in .JS using Ajax? I have a .js file hosted on domain1.com, but for this to work correctly I need to add a PHP code at the beginning. The reason for this is to bypass some restriction on Safari for my script and it requires me to create a session. The PHP code creates a session through a url to domain2.com. There is no browser redirection or anything, the user stays in the domain1.com. I want to have a single .js file in domain1.com so maybe an AJAX solution is what I need. Here it is:
<?php
session_start();

  if (!isset($_SESSION['isIFrameSessionStarted']))
    {
        $_SESSION['isIFrameSessionStarted'] = 1;
        $redirect = rawurlencode('http://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
        header('Location: domain2.com/start-session.php?redirect=' . $redirect);

        exit;
    }

?>

The start-session.php file is hosted on domain2.com does not need any changes, it contains this:
<?php
    session_start(); // create the session cookie
    $redirect = rawurldecode($_GET['redirect']);

    header('Location: ' . $redirect); // redirect back to domain
    exit;
?>

A: Let me combine what you requested in comments:

I have a .js file hosted on domain1 ... I want to have a single js file and I can't put PHP into that ... the whole purpose of this is for domain1 to not have any php code or php file. ... The reason is because I want it cross-domain and the session to be created from domain2.

It sounds like your issue might be related to the Safari iFrame session cookie problem, especially because you have if (!isset($_SESSION['isIFrameSessionStarted'])) in one of your code blocks. I will continue with this assumption.
Summary of the problem for other readers:

Upon embeding an IFrame from one domain into a website of a different domain, you will quickly realise that Internet Explorer and Safari are blocking the cookies (and thus the session variables) of the website inside the IFrame (ref).

Attempted solutions that didn't pan out:

*

*Safari 3rd party cookie iframe trick no longer working?

*Internet Explorer & Safari: IFrame Session Cookie Problem

*IFrame must die

*Safari: Setting third party iframe cookies

*PHP Session in iFrame in Safari and other browsers

My solution:
Essentially, PHP session "hijacking". It works surprisingly well where the above solutions failed. This is the essential solution. Please do any security enhancements* and URL-prettifying you like. Basically, we retrieve the PHP session ID through redirects and pass this to the iframe. Instructions are in the comments.
In your domainA.com head place this:
<script src="session.js"></script>

session.js (on domainA.com):
// Location of the domain B session starter
var sessionScriptURL = "http://domainB.com/start-session.php";
var refQSparam = "phpsessionid";

// Check if we have the phpsessionid in the query string
var phpsessionid = getParameterByName(refQSparam);
if(phpsessionid === null) {
    // Not in the query string, so check if we have it in session storage
    var sessionStore = sessionStorage.getItem(refQSparam);
    if(sessionStore === null) {
        // We have no session storage of the PHP session ID either, redirect to get it
        top.location = sessionScriptURL + "?redirect=" + encodeURIComponent(self.location.href);
    } else {
        // phpsessionid was found in session storage. Retrive it
        phpsessionid = sessionStore;
    }
} else {
    // Save the phpsessionid to session storage for browser refresh
    sessionStorage.setItem(refQSparam, phpsessionid);
    // Optional: Redirect again to remove the extra query string data
}

// Helper to get QS values
function getParameterByName(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

session-starter.php (on domainB.com):
<?php
session_start(); // create the session cookie
$redirect = rawurldecode($_GET['redirect']);

// redirect back with the php session ID
// Optional: encode this information
$href = $redirect . '?phpsessionid=' . session_id();
header('Location: ' . $href);
exit;

HTML (in the body, on domainA.com):
Append PHP session information to the iframe src.
<script>
document.write('<iframe src="http://domainB.com/embedded-script.php?phpsessionid='+phpsessionid+'"></iframe>');
</script>

embedded-script.php (on domainB.com, in an iframe):
<?php
// Use the phpsessionid passed in
$phpsessionid = rawurldecode($_GET['phpsessionid']);

// REF: http://php.net/manual/en/function.session-id.php
function session_valid_id($session_id) {
    return preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0;
}
// Check that this is potentially a valid session ID
if(session_valid_id($phpsessionid)) {
    // Set the session to the one obtained in session-start.php
    session_id($phpsessionid);
}
session_start(); // Only call this after session_id()!
// Rest of your code

*Considerations:

*

*Don't actually use document.write, use jQuery or document selectors.

*Encode the PHP session ID

*Perform another redirect back to the base URL of domainA.com to remove the ?phpsessionid= in the URL for a cleaner look.

*If you decide to call session-starter.php with AJAX instead, you will get a new PHP session ID every time for the same reason. The iframe will successfully use this session ID, but if you open a new page to domainB.com, the session will yet again be different.

A: If you want to run PHP within a file extended with .js, you can do this by telling your apache web server. Add the following directive to the .htaccess or directly to the apache config:
AddType application/x-httpd-php .js

After this is done, your server will run the included PHP code as soon as the file is requested from the server.

Update:
If you want to use sessions with JavaScript, you can do this with an AJAX solution. For this implement a web service on the server which should store the session values. Programming language for implementation can be PHP or another one which can be run by the web server. Request the web service with JavaScript. Here is an answer with an example.

A: If you want to redirect in Javascript, you can't use a PHP redirect which you have called from AJAX. You can pass the URL you create in PHP and send it back to JavaScript and do the redirect from there. You can do something like:
PHP:
session_start();

if (!isset($_SESSION['isIFrameSessionStarted'])) {
    $_SESSION['isIFrameSessionStarted'] = 1;
    $redirect = rawurlencode('http://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
    echo json_encode(array('url' => $redirect));
}

JavaScript:
$.get('phpfile', function(result) {
    if (!result) return;
    var data = JSON.parse(result);
    window.location.href = decodeURIComponent(data.url);
});

A: Don't know what you're trying to achieve exactly but let's say you want to go from php to js and back to php you could trying something like this:
Solution 1: Using XMLHttpRequest
In PHP (domain1.com):
<?php
  $parameter = ""; //If you'll like to add a parameter here
  echo "<script type='text/javascript'>window.addEventListener('DOMContentLoaded',". "function () { goToJS('$paramter');});</script>";
?>

In JS:
window.goToJS = function (parameter) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                //You can redirect back to a php file here
                document.location.href = "domain1.com";

                //You can view feedback from that php file you sent the stuff to here - just for testing
                alert("feedback" + xmlhttp.responseText);
            }
        }
        xmlhttp.open('GET', 'http://domain2.com/start-session.php?q=' + parameter, true);
        xmlhttp.send();

    }

Not sure about your redirect links and stuff but yeah this should pretty much work. Did something similar a while back
Solution 2: Using ajax
Using ajax you could have a JS script as follows. (type could be POST or GET, Used an example where you sent some json to the php file. Can change the data sent if you properly describe to me what you wish to send. Alternatively could be null also
In JS:
function init_() {
            $.ajax({
                type: 'POST',
                url: 'http://domain2.com/start-session.php',
                data: {json: JSON.stringify(selectedEvent)},
                dataType: 'json'
            }).done(function (data) {
                console.log('done');
                console.log(data);
            }).fail(function (data) {
                console.log('fail');
                console.log(data);
            });
        }

In PHP:
Let's say you sent a javascript json to PHP. You could use it in PHP as follows:
<?php

            $status_header = 'HTTP/1.1 ' . 200 . ' ' . 'OK';
            header($status_header);
            header('Content-type: text/javascript');
            $json = json_decode($_POST['json']); //Do whatever you want with the json or data sent
            echo "This is the returned data"; //Echo returned data back to JS or wherever

?>

A: why don't just use script directly (if you put this script on top of file it will wait the script to finish creating session in domain2 anyway. (I guess you have iframe in domain1 that call to domain2?)
<script src="http://domain2.com/start-session.php"></script>

A: USe jquery and jqxhr object for this request, no need send browser to second server, from domain1 you can request to browser load page to init session, and your client never see that.
//include jquery min library and do next code

$(document).ready(function (){
var jqxhr = $.get( "http://domain2.com/start-session.php", function() {
  alert( "success" ); //some action for success
})
  .done(function() {
    alert( "second success" ); //when all is done (success done)
  })
  .fail(function() {
    alert( "error" ); //some action for error
  })
  .always(function() {
    alert( "finished" ); //some end action for anycase
  });
});

you can delete .done function, .fail function, and always function as you wish.
NOTE: ready function is to make sure, that domain1 page completely load, and then run script.
reference https://api.jquery.com/jquery.get/


text:
Q: how do i test cookie expiry in rails rspec There is a lot of confusion about setting cookies in rspec
http://relishapp.com/rspec/rspec-rails/v/2-6/dir/controller-specs/file/cookies
in your controller, normally you can write
cookies['transaction_code'] = { :expires => 300.seconds.from_now, :value => c }

but in rspec i can only write
request.cookies['transaction_code'] = transaction_code

if i say
request.cookies['transaction_code'] = { :expires => 300.seconds.from_now, :value => c }

i get the hash back as value of cookies['transaction_code'] in my controller.
Now my question is: how do i set/test cookie expiry then in an rspec controller test example?
UPDATE: On seconds thought: What i mean is: how do i test if the controller is reacts to an expired cookie as expected, but in fact an expired cookie is just like no cookie if i trust cookie implementation, which i should do, so after all maybe my question makes no sense. If this is the case, i need to test if (another) controller action sets an expiring cookie correctly, but how do i do it if cookies['transaction_code'] in the test only gives the value back?

A: I came from the future with this:
  it 'sets the cookie expiration' do
    stub_cookie_jar = HashWithIndifferentAccess.new
    allow(controller).to receive(:cookies).and_return(stub_cookie_jar)
    get :index
    expiracy_date = stub_cookie_jar[:expires]
    expect(expiracy_date).to be_between(1.hour.from_now - 1.minutes,
                                        1.hour.from_now)
  end

A: Browsers do not send cookie attributes back to the server. This is why you can only send the key-value pair to the action.
Since you can assume that Rails, Rack and browsers do the right thing with the arguments, all you really need to test is the arguments your code is passing to the CookieJar.
To test that expiry is being set properly in the controller setting the cookie, you could stub out the #cookies method and make sure the right settings are being passed to it.
# app/controllers/widget_controller.rb
...
def index
    cookies[:expiring_cookie] = { :value   => 'All that we see or seem...',
                                  :expires => 1.hour.from_now }
end
...

# spec/controllers/widget_controller_spec.rb
...
it "sets the cookie" do
  get :index
  response.cookies['expiring_cookie'].should eq('All that we see or seem...')
                                               # is but a dream within a dream.
                                               #                - Edgar Allan Poe
end

it "sets the cookie expiration" do
  stub_cookie_jar = HashWithIndifferentAccess.new
  controller.stub(:cookies) { stub_cookie_jar }

  get :index
  expiring_cookie = stub_cookie_jar['expiring_cookie']
  expiring_cookie[:expires].to_i.should be_within(1).of(1.hour.from_now.to_i)
end
...

Testing much more than this is boiling the ocean. At some point, you have to assume that the stack you are sitting on (e.g., Rails, Rack, the web server, TCP/IP, OS, web browsers, etc) works properly and focus on the code you control.

A: Another option using Timecop:
Timecop.freeze(Time.now)

expect(controller.send(:cookies)).to receive(:[]=).with('cookie_name',
  value:   'whatever',
  expires: 1.hour.from_now
)

get :index

A: set request.cookies['transaction_code'] as a CGI::Cookie in your spec. http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI/Cookie.html#M000169

A: If you want to check several cookie attributes at once, inspect the Set-Cookie header, something like this:
it 'expires cookie in 15 minutes' do
  travel_to(Date.new(2016, 10, 25))
  post 'favorites', params: { flavor: 'chocolate' }
  travel_back

  details = 'favorite=chocolate; path=/; expires=Tue, 25 Oct 2016 07:15:00 GMT; HttpOnly'
  expect(response.header['Set-Cookie']).to eq details
end

This is a bit brittle, in that other, non-critical attributes of the cookie may break this string. But it does keep you out of Rails internals, and lets you check several attributes at once.
A better way is to match just one attribute at a time, this is a much more robust method that is not so vulnerable to changes in how the Set-Cookie string is constructed, or what other attributes you might add to the cookie in the future:
  expect(response.header['Set-Cookie']).to match(
    /favorite=chocolate.*; expires=Tue, 25 Oct 2016 07:15:00 GMT/
  )


text:
Q: Uma imagem com display:none é carregado? Consome dados? Estou desenvolvendo um layout responsivo e gostaria de diminuir o tamanho das imagens conforme a resolução.
Eu utilizei o display: none porém vi no inspetor de elementos que ela está sendo carregada. Está sendo consumido os dados das duas imagens? Qual alternativa para este problema?

A: Como já pode comprovar é carregada e tudo o que é carregado consome dados, não tem milagre.
Certamente existem técnicas para evitar a carga das duas. A carga pode ser seletiva no que realmente será usado. Isto pode ser feito com JavaScript ou com CSS (media queries). Tem pergunta sobre isto aqui.

A: Primeira coisa que deve entender é :

*

*Quando devo usar a tag  ou a propriedade do CSS background?
Caso a sua imagem não tenha valor semântico use a propriedade background-image  + display:none em uma div, isso evitará que sua imagem seja carregada.
Edição
Analisando a situação percebi que a resposta que adicionei acima não é verdadeira, ou seja, pelo ao menos no caso do Google Crome está imagem é baixada.
Veja você mesmo:

div#image {
   background-image: url("https://i.pinimg.com/736x/6b/b2/49/6bb249802cf0c124fde0ccbcea699340--funny-stuff-quotes.jpg");
   width:500px;
   height:500px;
   display:none;
}
<div id='image'>
</div>

Você pode ver isto na aba NetWork, coloquei também uma imagem para ilustrar.

Porque é necessário que a imagem carregue?
Devido a possibilidade de um Script verificar dinamicamente um elemento do DOM, o navegador não otimiza elementos ou seus conteúdos.
Fonte: Does "display:none" prevent an image from loading?

A: Neste link um usuário fez um teste no Chrome, Internet Explorer, Firefox e Opera e eles tratam isso de formas diferentes.
Se as imagens estiverem em uma tag img elas serão baixadas por todos. Mas se estiverem como background-image de um elemento apenas o Firefox e o Opera não baixam. O IE e Chrome só não vão baixar caso a imagem não se encaixe na regra definida no media-query.


text:
Q: Pacman game - how to fix I am creating really simple pacman game as a homework. I am working in Visual Studio, in c#. The problem is, when I click run, only the winform shows with nothing on it. Can someone tell me what have I done wrong?
namespace pacman
{
    public partial class Form1 : Form
    {
        Timer timer;
        Pacman pacman;
        static readonly int TIMER_INTERVAL = 250;
        static readonly int WORLD_WIDTH = 15;
        static readonly int WORLD_HEIGHT = 10;
        Image foodImage;
        bool[][] foodWorld;

        public Form1()
        {
            InitializeComponent();

            foodImage = Properties.Resources.orange_detoure;
            DoubleBuffered = true;
            newGame();
        }

        public void newGame()
        {
            pacman = new Pacman();
            this.Width = Pacman.radius * 2 * (WORLD_WIDTH + 1);
            this.Height = Pacman.radius * 2 * (WORLD_HEIGHT + 1);

            foodWorld = new bool[WORLD_WIDTH][];

            timer = new Timer();
            timer.Interval = TIMER_INTERVAL;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            timer.Interval = TIMER_INTERVAL - 1;
            if (TIMER_INTERVAL == 0)
            {
                timer.Stop();
            }
            pacman.Move(WORLD_WIDTH, WORLD_HEIGHT);
            Invalidate();
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (Keys.Up != 0)
            {
                pacman.ChangeDirection("UP");
            }
            if (Keys.Down != 0)
            {
                pacman.ChangeDirection("DOWN");
            }
            if (Keys.Left != 0)
            {
                pacman.ChangeDirection("LEFT");
            }
            if (Keys.Right != 0)
            {
                pacman.ChangeDirection("RIGHT");
            }
            Invalidate();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.Clear(Color.White);
            for (int i = 0; i < foodWorld.Length; i++)
            {
                for (int j = 0; j < foodWorld[i].Length; j++)
                {
                    if (foodWorld[i][j])
                    {
                        g.DrawImageUnscaled(foodImage, j * Pacman.radius * 2 + (Pacman.radius * 2 - foodImage.Height) / 2, i * Pacman.radius * 2 + (Pacman.radius * 2 - foodImage.Width) / 2);
                    }
                }
            }
            pacman.Draw(g);
        }
    }
}

And here is the class Pacman:
namespace pacman
{
    public class Pacman
    {
        public enum dir {UP, DOWN, RIGHT, LEFT};

        public float x { get; set; }
        public float y { get; set; }
        public string direction { get; set; }
        static public int radius = 20;
        public double speed { get; set; }
        public bool open { get; set; }
        public Brush brush = new SolidBrush(Color.Yellow);

        public Pacman() {
            this.x = 7;
            this.y = 5;
            this.speed = 20;
            this.direction = Convert.ToString(dir.RIGHT);
            this.open = false;
        }

        public void ChangeDirection(string direct)
        {
            // vasiot kod ovde
            for (int i = 0; i < 3; i++) {

                if(direct == Convert.ToString(dir.RIGHT))
                {
                    direction = "RIGHT";
                }
                if (direct == Convert.ToString(dir.LEFT))
                {
                    direction = "LEFT";
                }
                if (direct == Convert.ToString(dir.UP))
                {
                    direction = "UP";
                }
                if (direct == Convert.ToString(dir.DOWN))
                {
                    direction = "DOWN";
                }
            }
        }

        public void Move(float width, float height)
        {
            if (direction == Convert.ToString(dir.RIGHT))
            {
                x = x + 1;
                if (x > width) {
                    x = 1;
                }
            }
            else if (direction == Convert.ToString(dir.LEFT))
            {
                x = x - 1;
                if (x < 0) {
                    x = 14;
                }
            }
            else if (direction == Convert.ToString(dir.UP))
            {
                y = y + 1;
                if (y > height) {
                    y = 1;
                }
            }
            else if (direction == Convert.ToString(dir.DOWN))
            {
                y = y - 1;
                if (y < 0) {
                    y = 14;
                }
            }
        }

        public void Draw(Graphics g)
        {
            if (!open) {
                g.FillEllipse(brush, 7, 5, 15, 15);
            }
        }
    }
}

It should look like this http://prntscr.com/70e0jt.
I will be grateful if someone can tell me what should I fix so it finally works..

A: Add this to your constructor:
this.Paint += Form1_Paint;
What is happening is that you made a Paint handler, but never assigned the paint event to handle it (that I can see, its possible that the event was assigned in the other partial part of the class).
The other problem is that you did not fully define the "food world" variable, you initialized the first rank, but not the second. You need to fully initialize this and set the booleans inside of it.


text:
Q: codeigniter pagination for a query So far found plenty of help to get the pagination working for a get(table) command.
What I need is to pick only few of the entries from a couple of linked tables based on a sql where statement.
I guess the query command is the one to use but in this case how do I do the pagination since that command does not take extra parameters such $config['per_page']
Thanks for the help

A: Without any more info to go on I think that what you're looking for is something like the following.
public function pagination_example($account_id)
{
    $params = $this->uri->ruri_to_assoc(3, array('page'));

    $where = array(
        'account_id'    => $account_id,
        'active'        => 1
    );

    $limit = array(
        'limit'     => 10,
        'offset'    => (!empty($params['page'])) ? $params['page'] : 0
    );

    $this->load->model('pagination_model');
    $data['my_data'] = $this->pagination_model->get_my_data($where, $limit);

    foreach($this->uri->segment_array() as $key => $segment)
    {
        if($segment == 'page')
        {
            $segment_id = $key + 1;
        }
    }

    if(isset($segment_id))
    {
        $config['uri_segment'] = $segment_id;
    }
    else
    {
        $config['uri_segment'] = 0;
    }

    $config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/controller_name/method_name/whatever_your_other_parameters_are/page/';
    $config['total_rows'] = $this->pagination_model->get_num_total_rows();// Make a method that will figure out the total number
    $config['per_page']     = '10';

    $this->load->library('pagination');
    $this->pagination->initialize($config);
    $data['pagination'] = $this->pagination->create_links();

    $this->load->view('pagination_example_view', $data);

}

    // pagination_model
public function get_my_data($where = array(), $limit = array())
{
    $this->db
        ->select('whatever')
        ->from('wherever')
        ->where($where)
        ->limit($limit['limit'], $limit['offset']);
    $query = $this->db->get();

    if($query->num_rows() > 0)
    {
        $data = $query->result_array();
        return $data;
    }
    return FALSE;
}

This should at least get you on the right track
If this isn't what you're asking I'd happy to help more if you can be a little more specific.  How about some of your code.

A: The only other options that I can think of would be to either code a count in your select statement or not limit the query and use array_slice to select a portion of the returned array.


text:
Q: Testing updated jar in project I have a main java EE project in which I use multiple jar libraries.
For one of the specific jars, I am going into the original project of that jar, and updating its libraries, and re-importing the updated jar into the main project.
I am thinking of good ways to test that the updated jar still works in the application, so I decided upon looking for where the jar is being used. Is there a way in Eclipse to find every instance that the jar is being used (classes instantiated, methods called, etc)?
Should I just be looking for import statements or anything else?


text:
Q: aws lambda versus azure functions After nearly a month of work I am stuck with aws lamda's underlying execution environment which is Linux and the external DLL that I have to use are written in Windows. And while doing research over internet looks like it will be very difficult to use Windows DLLs with aws lambda. Here is link to my query regarding this issue -module initialization error: /var/task/TDNN.dll: invalid ELF header
Therefore, I am now considering to move to azure functions assuming that I may not face this limitation over there. So could any one comment about Azure's underlying execution environment like is it windows or linux? I am correct in my conclusion.
Any comment will be highly useful and appreciated.

A: Azure functions are hosted in a windows machine next to an Azure Website.
You can easily use an existing dll in your function by adding it by FTP in the function root folder (within a bin folder) and then use #r to reference it from the azure function code.
Here is an example, a dll named "WorkOnImages.dll" is uploaded in an azure in azure function folder :


text:
Q: Nodejs Error: listen EADDRINUSE: address already in use :8080 My app was not running but when I try "npm start" command it throws error
Error: listen EADDRINUSE: address already in use :8080
I restart my EC2 instance and try this command again, but I face same error.  How do I start my Node server?

A: Going by your comments, it looks like you have a node process already running your EC2 instance and it's listening on port 8080.
As you have stated lsof -i tcp:8080 gives you,
node 3255 root 20u IPv6 20660 0t0 TCP *:webcache (LISTEN)

The PID of this process is shown in the 2nd column: 3255.
Kill it,
kill -9 3255

After this try running your npm start and it should work


text:
Q: Do new laptop batteries require charge cycles before reaching full capacity? I have purchased a new battery for my hp pavilion dv6500 laptop.
The description in the shop read that it should be a new battery.
Using Fedora OS, I did inxi -Bxxx to see some info on the battery and I see that its condition is 73%.
Does this mean it is a used battery or should I expect it will get better condition as advertised in the same seller description where I read that "it requires 4/5 full charge/discharge cycles to reach its fullest capacity"?

A: It is generally a good idea to go through a full charge - discharge cycle when replacing a battery. This is not to "initialize" the battery itself but to initialize the battery monitoring system.
In many devices the battery management circuits need to "learn" what the battery voltage is when the battery is fully charged and when it is (almost) empty. So I would fully charge the battery and then run inxi again and see what you get.
Do realize that Li-Ion batteries do degrade over time even if you do not use them. If the battery has been lying on a shelf for a year it might have lost some of its capacity even though it was never used and is considered "new".


text:
Q: Zend Framework: How to add a custom validator path to your entire application? I have custom validators and filters that I have created that I would like to use throughout my application. All my forms extend a base class. What should I do so that Zend Framework knows where to find these?

A: Have a look at the Plugin Loaders in the ZF-Documentation
class Your_Form extends Zend_Form
{
    /**
     * @param mixed $options
     * @return void
     */
    public function __construct($options = null)
    {
        $this->addElementPrefixPath('Prefix_Validate', 'Prefix/Validate/');
        $this->addPrefixPath('Prefix_Form', 'Prefix/Form/');

        parent::__construct($options);
    }
}


text:
Q: How can I specify an interface that has child objects as the type for a function with destructured props Instead of this,
import { client } from "./setupApi";

export const getLayout = ({ page, entity, list }: {page: string, entity: string, list: string}) => {
  return client.get("/secure/nav.json");
};

How can I use this interface?
export interface getLayoutProps {
  page: string;
  entity: string;
  layout: string;
}

A: This works just fine, the only reason your example doesn't work in my computer is because there's no list property in getLayoutProps, instead there's layout:
export interface getLayoutProps {
  page: string;
  entity: string;
  layout: string;
}

export const getLayout = ({ page, entity, layout }: getLayoutProps) => { // This works.
  return client.get("/secure/nav.json");
};

A: import { client } from "./setupApi";

export interface IGetLayoutProps {
  page: string;
  entity: string;
  layout?: string;
  list?: Array<string>;
}

export const getLayout = ({ page, entity, list }: IGetLayoutProps) => {
  return client.get("/secure/nav.json");
};


text:
Q: Android: How do I get a list of installed applications and show them to the user I've looked at many different variations of code on how to get a list of installed applications and show them in a ListView to the user but none have been successful for me. What I'd like to know is how to do this and how I'd add flags(?) to it so that I could just list curtain applications which have different intent-filters such as LONG_SEARCH_BUTTON and be able to view the package and launcher class of that application.. if this is do able?
I'd like a full java class if someone wouldn't mind sharing their knowledge as trying to piece together bits of code is becoming quite stressful! I've been coding android for a few months so I know most of the basic stuff (I'd like to think...) but not don't anything like this before.

A: I've written a short application which does exactly that... check it out here.

A: Here is the sample code from the Android documentation. Please be creative for your requirements.

/**  * This class holds the per-item data in our Loader.  */ public
  static class AppEntry {
      public AppEntry(AppListLoader loader, ApplicationInfo info) {
          mLoader = loader;
          mInfo = info;
          mApkFile = new File(info.sourceDir);
      }
public ApplicationInfo getApplicationInfo() {
    return mInfo;
}

public String getLabel() {
    return mLabel;
}

public Drawable getIcon() {
    if (mIcon == null) {
        if (mApkFile.exists()) {
            mIcon = mInfo.loadIcon(mLoader.mPm);
            return mIcon;
        } else {
            mMounted = false;
        }
    } else if (!mMounted) {
        // If the app wasn't mounted but is now mounted, reload
        // its icon.
        if (mApkFile.exists()) {
            mMounted = true;
            mIcon = mInfo.loadIcon(mLoader.mPm);
            return mIcon;
        }
    } else {
        return mIcon;
    }

    return mLoader.getContext().getResources().getDrawable(
            android.R.drawable.sym_def_app_icon);
}

@Override public String toString() {
    return mLabel;
}

void loadLabel(Context context) {
    if (mLabel == null || !mMounted) {
        if (!mApkFile.exists()) {
            mMounted = false;
            mLabel = mInfo.packageName;
        } else {
            mMounted = true;
            CharSequence label = mInfo.loadLabel(context.getPackageManager());
            mLabel = label != null ? label.toString() : mInfo.packageName;
        }
    }
}

private final AppListLoader mLoader;
private final ApplicationInfo mInfo;
private final File mApkFile;
private String mLabel;
private Drawable mIcon;
private boolean mMounted; }

/**  * Perform alphabetical comparison of application entry objects.
  */ public static final Comparator ALPHA_COMPARATOR = new Comparator() {
      private final Collator sCollator = Collator.getInstance();
      @Override
      public int compare(AppEntry object1, AppEntry object2) {
          return sCollator.compare(object1.getLabel(), object2.getLabel());
      } };
/**  * Helper for determining if the configuration has changed in an
  interesting  * way so we need to rebuild the app list.  */ public
  static class InterestingConfigChanges {
      final Configuration mLastConfiguration = new Configuration();
      int mLastDensity;
boolean applyNewConfig(Resources res) {
    int configChanges = mLastConfiguration.updateFrom(res.getConfiguration());
    boolean densityChanged = mLastDensity != res.getDisplayMetrics().densityDpi;
    if (densityChanged || (configChanges&(ActivityInfo.CONFIG_LOCALE
            |ActivityInfo.CONFIG_UI_MODE|ActivityInfo.CONFIG_SCREEN_LAYOUT)) != 0)

{
              mLastDensity = res.getDisplayMetrics().densityDpi;
              return true;
          }
          return false;
      } }
/**  * Helper class to look for interesting changes to the installed
  apps  * so that the loader can be updated.  */ public static class
  PackageIntentReceiver extends BroadcastReceiver {
      final AppListLoader mLoader;
public PackageIntentReceiver(AppListLoader loader) {
    mLoader = loader;
    IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
    filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
    filter.addDataScheme("package");
    mLoader.getContext().registerReceiver(this, filter);
    // Register for events related to sdcard installation.
    IntentFilter sdFilter = new IntentFilter();
    sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
    sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
    mLoader.getContext().registerReceiver(this, sdFilter);
}

@Override public void onReceive(Context context, Intent intent) {
    // Tell the loader about the change.
    mLoader.onContentChanged();
} }

/**  * A custom Loader that loads all of the installed applications.
  */ public static class AppListLoader extends AsyncTaskLoader> {
      final InterestingConfigChanges mLastConfig = new InterestingConfigChanges();
      final PackageManager mPm;
List<AppEntry> mApps;
PackageIntentReceiver mPackageObserver;

public AppListLoader(Context context) {
    super(context);

    // Retrieve the package manager for later use; note we don't
    // use 'context' directly but instead the save global application
    // context returned by getContext().
    mPm = getContext().getPackageManager();
}

/**
 * This is where the bulk of our work is done.  This function is
 * called in a background thread and should generate a new set of
 * data to be published by the loader.
 */
@Override public List<AppEntry> loadInBackground() {
    // Retrieve all known applications.
    List<ApplicationInfo> apps = mPm.getInstalledApplications(
            PackageManager.GET_UNINSTALLED_PACKAGES |
            PackageManager.GET_DISABLED_COMPONENTS);
    if (apps == null) {
        apps = new ArrayList<ApplicationInfo>();
    }

    final Context context = getContext();

    // Create corresponding array of entries and load their labels.
    List<AppEntry> entries = new ArrayList<AppEntry>(apps.size());
    for (int i=0; i<apps.size(); i++) {
        AppEntry entry = new AppEntry(this, apps.get(i));
        entry.loadLabel(context);
        entries.add(entry);
    }

    // Sort the list.
    Collections.sort(entries, ALPHA_COMPARATOR);

    // Done!
    return entries;
}

/**
 * Called when there is new data to deliver to the client.  The
 * super class will take care of delivering it; the implementation
 * here just adds a little more logic.
 */
@Override public void deliverResult(List<AppEntry> apps) {
    if (isReset()) {
        // An async query came in while the loader is stopped.  We
        // don't need the result.
        if (apps != null) {
            onReleaseResources(apps);
        }
    }
    List<AppEntry> oldApps = apps;
    mApps = apps;

    if (isStarted()) {
        // If the Loader is currently started, we can immediately
        // deliver its results.
        super.deliverResult(apps);
    }

    // At this point we can release the resources associated with
    // 'oldApps' if needed; now that the new result is delivered we
    // know that it is no longer in use.
    if (oldApps != null) {
        onReleaseResources(oldApps);
    }
}

/**
 * Handles a request to start the Loader.
 */
@Override protected void onStartLoading() {
    if (mApps != null) {
        // If we currently have a result available, deliver it
        // immediately.
        deliverResult(mApps);
    }

    // Start watching for changes in the app data.
    if (mPackageObserver == null) {
        mPackageObserver = new PackageIntentReceiver(this);
    }

    // Has something interesting in the configuration changed since we
    // last built the app list?
    boolean configChange = mLastConfig.applyNewConfig(getContext().getResources());

    if (takeContentChanged() || mApps == null || configChange) {
        // If the data has changed since the last time it was loaded
        // or is not currently available, start a load.
        forceLoad();
    }
}

/**
 * Handles a request to stop the Loader.
 */
@Override protected void onStopLoading() {
    // Attempt to cancel the current load task if possible.
    cancelLoad();
}

/**
 * Handles a request to cancel a load.
 */
@Override public void onCanceled(List<AppEntry> apps) {
    super.onCanceled(apps);

    // At this point we can release the resources associated with 'apps'
    // if needed.
    onReleaseResources(apps);
}

/**
 * Handles a request to completely reset the Loader.
 */
@Override protected void onReset() {
    super.onReset();

    // Ensure the loader is stopped
    onStopLoading();

    // At this point we can release the resources associated with 'apps'
    // if needed.
    if (mApps != null) {
        onReleaseResources(mApps);
        mApps = null;
    }

    // Stop monitoring for changes.
    if (mPackageObserver != null) {
        getContext().unregisterReceiver(mPackageObserver);
        mPackageObserver = null;
    }
}

/**
 * Helper function to take care of releasing resources associated
 * with an actively loaded data set.
 */
protected void onReleaseResources(List<AppEntry> apps) {
    // For a simple List<> there is nothing to do.  For something
    // like a Cursor, we would close it here.
} }

An example implementation of a fragment that uses the above loader to show the currently installed applications in a list is below.

public static class AppListAdapter extends ArrayAdapter {
      private final LayoutInflater mInflater;
public AppListAdapter(Context context) {
    super(context, android.R.layout.simple_list_item_2);
    mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public void setData(List<AppEntry> data) {
    clear();
    if (data != null) {
        addAll(data);
    }
}

/**
 * Populate new items in the list.
 */
@Override public View getView(int position, View convertView, ViewGroup parent) {
    View view;

    if (convertView == null) {
        view = mInflater.inflate(R.layout.list_item_icon_text, parent, false);
    } else {
        view = convertView;
    }

    AppEntry item = getItem(position);
    ((ImageView)view.findViewById(R.id.icon)).setImageDrawable(item.getIcon());
    ((TextView)view.findViewById(R.id.text)).setText(item.getLabel());

    return view;
} }

public static class AppListFragment extends ListFragment
          implements OnQueryTextListener, LoaderManager.LoaderCallbacks> {
// This is the Adapter being used to display the list's data.
AppListAdapter mAdapter;

// If non-null, this is the current filter the user has provided.
String mCurFilter;

@Override public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Give some text to display if there is no data.  In a real
    // application this would come from a resource.
    setEmptyText("No applications");

    // We have a menu item to show in action bar.
    setHasOptionsMenu(true);

    // Create an empty adapter we will use to display the loaded data.
    mAdapter = new AppListAdapter(getActivity());
    setListAdapter(mAdapter);

    // Start out with a progress indicator.
    setListShown(false);

    // Prepare the loader.  Either re-connect with an existing one,
    // or start a new one.
    getLoaderManager().initLoader(0, null, this);
}

@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // Place an action bar item for searching.
    MenuItem item = menu.add("Search");
    item.setIcon(android.R.drawable.ic_menu_search);
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
            | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    SearchView sv = new SearchView(getActivity());
    sv.setOnQueryTextListener(this);
    item.setActionView(sv);
}

@Override public boolean onQueryTextChange(String newText) {
    // Called when the action bar search text has changed.  Since this
    // is a simple array adapter, we can just have it do the filtering.
    mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
    mAdapter.getFilter().filter(mCurFilter);
    return true;
}

@Override public boolean onQueryTextSubmit(String query) {
    // Don't care about this.
    return true;
}

@Override public void onListItemClick(ListView l, View v, int position, long id) {
    // Insert desired behavior here.
    Log.i("LoaderCustom", "Item clicked: " + id);
}

@Override public Loader<List<AppEntry>> onCreateLoader(int id, Bundle args) {
    // This is called when a new Loader needs to be created.  This
    // sample only has one Loader with no arguments, so it is simple.
    return new AppListLoader(getActivity());
}

@Override public void onLoadFinished(Loader<List<AppEntry>> loader, List<AppEntry> data) {
    // Set the new data in the adapter.
    mAdapter.setData(data);

    // The list should now be shown.
    if (isResumed()) {
        setListShown(true);
    } else {
        setListShownNoAnimation(true);
    }
}

@Override public void onLoaderReset(Loader<List<AppEntry>> loader) {
    // Clear the data in the adapter.
    mAdapter.setData(null);
} }


text:
Q: Network adapter requires a reset every 20-25 minutes after installing mesh wifi After my household replaced their Nighthawk router with an Orbi mesh network, I have been experiencing regular network drops every 21 to 25 minutes on both my desktop and my laptop that require the network adapter to be reset in order for the connection to be restored.
Testing:

*

*These network outages appear to happen synchronously - when I boot up
my laptop halfway through the 21-minute period, it also loses
connection at roughly the same time my desktop does.

*The network issue does not happen when there are fewer
programs being run - killing everything in task manager and
monitoring the network does show some fluctuations every 21 or so
minutes, but my devices manage to restore the connection automatically without
requiring the adapter being reset if no or few programs are active.

*I haven't been able to isolate a singular program or application causing these issues - it just seems that at a certain point of adding programs to the pile, the network issues start to occur.

*I have confirmed that my Wifi-6 network card is compatible with the 802.11ax protocol used by the Orbi network, and signal strength has been consistently solid. Connection speeds are stable when the wifi is connected, as well.

*The network card has option "Turn device off to save power" turned off in its Advanced Settings.

I've been getting by by using a script that autodetects ping failures and resets the network adapter, but I'd really like to get to the bottom of this so I can support streaming and videoconferencing without having to worry about resetting the adapter three times an hour. Any ideas as to what's causing this or solutions for the issue would be very much appreciated!
System details:

*

*Windows 10 v2004 19041.630 64-bit

*Intel i9-9900K 3.60GHz

*Archer TX50E Wi-Fi 6 PCIe adapter

A: The article
Making Orbi Great Again
remarks that it's possible that the Orbi isn't the right choice for a medium-sized
house.
The solutions listed in the article:

*

*Force the 2.4Ghz channel to 6 or 1

*Set different SSIDs for 2.4 and 5 ghz

*Decrease the transmit power

*If you have a satellite connection, set a static IP for the satellite.


text:
Q: How do I set the table cell widths to minimum Asciidoc tables use equally sized column width by default. How can I tell asciidoc to use minumum column widths instead?
I am able to set relative column widths using
[cols="2,1,6,1,2"]

However, I want Asciidoc to automatically determine the min column width, so that columns with long text do not need extra line breaks.
I would expect something like
[width="min"]

but that does not work.

A: One way to do this is to set the non-minimum columns to extremely large numbers.  You can change your cols setting to this, for example:
[cols="200,1,600,1,200"]

This keeps your larger columns proportioned relatively, while shrinking the small columns as small as they can reasonably go.
(It will break those small columns on spaces, though, in its efforts to make them as small as possible.)


text:
Q: Adding Rows to DataFrame in Pandas - Error - ValueError: cannot set a row with mismatched columns Learning Pandas and trying to make a code for myself so noob in this.
I'm running into an error:

ValueError: cannot set a row with mismatched columns

I have an app created in PySimpleGui which would take input from user and create a database with columns predefined.
I'm unable to add the rows and running into this issue.
I've made sure I have 6 columns and therefore the number of data to be inserted is 6 but I still get this error.
The code I have at the moment is :
output_path_csv = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop\\Daily_Tracker.xlsx')
if os.path.exists(output_path_csv):
    pass
else:
    x_header = ['Date', 'Case Number', 'Serial Number', 'Product Name', 'Version', 'Issue']
    df = pd.DataFrame( columns=x_header )
    df.to_excel( output_path_csv, index=False)

p_name = prod_name(values['Serial_Num'])  # Determining the product name
values['Product_Name'] = p_name

v_name = ver_name(values['Serial_Num'])  # Determining the version type of the product selected
values['Product_Type'] = v_name
c_num = values.get('Case_Num')
s_num = values.get('Serial_Num')
c_Issue = values.get('Issue')

# to check for e-mail address
sp_char = "@"
if sp_char in values['Email_Add']:
    doc.render(values)
    output_path_doc = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop\\Notes.docx')
    try:
        doc.save(output_path_doc)
        popup("File Saved", f"File has been saved here : {output_path_doc}")
        os.startfile(output_path_doc)
    except PermissionError:
        popup('File seems to be opened! Please close the file!')
        pass
else:
    popup('Missing @ character in the e-mail. Please update')
    pass
df2 = pd.read_excel( output_path_csv )
df2.loc[len( df2.index )] = [to_date, c_num, s_num, p_name, v_name, c_Issue]
df2.to_excel( output_path_csv )


text:
Q: How to subclass QStandardItemModel to use my own Item type? How do I subclass QStandardItemModel to use my own Item type (e.g. MyItem instead of QStandardItem)? I mean I know I have to create a class and inherit QStandardItemModel but what next? How do I make it use MyItem everywhere? And yes, MyItem inherits after QStandardItem.

A: You don't need to subclass model, just item class. All you need is this:
class YourItem : public QStandardItem
{
// ...
public:
       virtual QStandardItem *clone() const;
};

QStandardItem *YourItem::clone() const
{
    return new YourItem(/*your constructor parameters to copy data if needed*/);
}

when installing model:
model->setItemPrototype(new MyItem());
ui->listView->setModel(model);

A: I think it is impossible. You can subclass QAbstractItemModel to implement a model that use your item class.
Also you can use default QStandardItemModel and add your additional object to items using QStandardItem::setData. Since it accepts QVariant, you can put any value in it, event QSharedPointer (you need to register appropriate meta type).


text:
Q: API JSON response using POST in PHP I have an API resources push.php which I am using for mobile application which requires the application to POST data in order to get response. Now the mobile applications are completed and now i am working on the website of the same application. Rather than writing the code again i would like to use the API calls i've created which resides on the same server.
My registration form resides on the root folder (root/index.php)
My API call for registration resides in API folder (root/API/push.php)
I want to send form data using POST and retrieve the JSON data from push.php successfully. Issue is in between the starred comments.
ROOT/index.php
<!DOCTYPE html>

    <title>Sign Up</title>

Register User

    <form name="signup" method="post" action="signup.php">

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

        <input type="password" name="password" placeholder="password">

        <input type="submit" value="Sign Up!">
    </form>

        <?php
            if (!empty($_POST)) {
                if (isset($_POST['username']) && isset($_POST['password'])) {
                    $output = NULL;
                    $username = $_POST['username'];
                    $username = $_POST['password'];

                    //********************************************
                    //Send values to API and receive output in JSON

                    $JSON = getResponseFromAPIbyPOST($username, $password);

                    //********************************************

                    $output = json_decode($JSON);
                    if ($output->response == "SUCCESS") {
                        echo "Registration Successful!";
                    } else {
                        echo "Registration Failed!";
                    }
                }
            }
        ?>

ROOT/API/push.php
error_reporting(E_ALL);
header('Content-Type: application/json');
include 'includes/dbcon.class.php';
$dbcon = new dbcon;
$conn = $dbcon->connect();
// Set Action
if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else {
    $action = NULL;
}
// Check if API call is valid
if ($action == "register") {
    $output = new stdClass();
    if (isset($_POST['username']) && isset($_POST['password'])) {
        $username = mysqli_escape_string($_POST['username']);
        $password = mysqli_escape_string($_POST['password']);
        $sql = "INSERT INTO dbuser(vuser,vpass) VALUES ('{$username}','{$password}') ";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            $output->data = "USER_CREATED";
            $output->response = "SUCCESS";
            echo json_encode($output, JSON_PRETTY_PRINT);
        } else {
            $output->data = "SQL Error $conn->errno : $conn->error";
            $output->response = "FAIL";
            echo json_encode($output, JSON_PRETTY_PRINT);
        }
    } else {
        $output->data = "INVALID_ARGUMENTS";
        $output->response = "FAIL";
        echo json_encode($output, JSON_PRETTY_PRINT);
    }
} else {
    $output->data = "INVALID";
    $output->response = "FAIL";
    echo json_encode($output, JSON_PRETTY_PRINT);
}

OUTPUT
{
    "data": "USER_CREATED",
    "response": "SUCCESS"
}

if you look at index.php between the starred comments, I am trying to figure out what function can i use here >> getResponseFromAPIbyPOST($username,$password) which will get me the response and save it tovariable $JSON.
What is the correct php function to achieve this goal?
Server is using HTTPS

A: You can do it by using curl or get_file_contents.
using cURL

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://www.yourdomain.com/api/push.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query([
'username' => $username,
'password' => $password
]));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);

curl_close ($ch);


text:
Q: is it possible to request UIWebView using user agent as Safari on iPhone? i try to request on my application via this url
http://reader.mac.com/mobile/v1/http%3A%2F%2Ffeeds.feedburner.com%2F9To5Mac-MacAllDay
and it also return that it available on iPhone only
how can i fix it?
mycode
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: myurl]];
    [urlRequest setValue: @"iPhone" forHTTPHeaderField: @"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"];
    [self.myWebView loadRequest:urlRequest];

A: UIWebView actually resets the user agent of the request just before it loads the URL. So, you may need to do method swizzling to actually change the user agent string that UIWebView loads in. Be warned, method swizzling could be dangerous.
There's a post that has the code for this.

A: The name of the http header field is User-Agent.
Try this:
    [urlRequest setValue: @"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"
      forHTTPHeaderField: @"User-Agent"];


text:
Q: How to Hover Over a Button, Cause the Box-Shadow of It's Containing Div To Get Darker With jQuery I can't seem to find an example of this even though I know I've seen it before. Basically, when you hover over the button, centered within a div (that already has a box shadow over it), the opacity of the div's box shadow gets darker.
So if you take a look at this JSFiddle, when you hover over "See My Work", the box shadow over .business-presentation should change from
box-shadow: inset 0 0 0 4000px rgba(27,61,88,.5);
to
box-shadow: inset 0 0 0 4000px rgba(27,61,88,.8);
Here is the HTML and CSS in question:
HTML:

        <button class="view-websites hover-darker">See My Work</button>

CSS:
.business-presentation {
    background: url("http://i.imgur.com/YzpXEYy.jpg");
    box-shadow: inset 0 0 0 4000px rgba(27,61,88,.8);
    height: 400px;
    background-size: cover;
    background-repeat: no-repeat;
    align-items: center;
    justify-content: center;
    display: flex;
}

.see-my-work {
    text-align: center;
    vertical-align: middle;
    padding: 10px 30px 10px 30px;
    font-family: 'proxima_novalight';
    color: #ffffff;
}

.view-websites {
    text-align: center;
    text-transform: uppercase;
    color: #ffffff;
    margin: auto;
    font-size: 30px;
    border: 2px solid #ffffff;
    padding: 10px 30px 10px 30px;
    background-color: transparent;
 }

 .hover-darker:hover {

 }

I've seen this example but it doesn't deal with changing the box shadow of one element when hovering over another. Will this require JavaScript? Thanks for your suggestions.

A: You can use the jQuery mouseenter() & mouseout().
See here https://jsfiddle.net/vk3qw09f/151/

A: You can't change a parents property with a child's selector. What you can do in this case is change box-shadow from .business-presentation, to a combination ofbackground-colourandbox-shadowon the.view-websites` button. See https://jsfiddle.net/james_wesc/y82kvbtc/
Or the changes are:
.business-presentation {
    /* box-shadow: .. */ /* remove box-shadow
    overflow: hidden;
}

.visit-websites {
    background-colour: rgba(27,61,88,.5);
    box-shadow: 0 0 0 400px rgba(27,61,88,.5);
}

.visit-websites:hover {
    background-colour: rgba(27,61,88,.8);
    box-shadow: 0 0 0 400px rgba(27,61,88,.8);
}


text:
Q: Primality of Fermat numbers associated with "tetration" A lot is known about the Fermat numbers $2^{2^k}+1$. For example, the first few
$$
2^1+1=3,\;2^2+1=5,\;2^4+1=17,\;2^8+1=257,\;2^{16}+1=65537
$$
are known to be prime, and Euler showed that the next ($2^{32}+1$) is not prime, being divisible by 641.
But what about the subset of special Fermat numbers formed by "tetration" or "power towers"?
$$
2+1 = 3\\
2^2+1 = 5\\
2^{2^2}+1 = 2^4+1=17\\
2^{2^{2^2}}+1 = 2^{16}+1=65537\\
2^{2^{2^{2^2}}}+1 = 2^{65536}+1
$$
I thought I had a vague memory of once reading that someone had conjectured that these are all prime (I guess people at one point conjectured that more generally all Fermat numbers were prime) and I also thought I had a vague memory of once reading that $2^{65536}+1$ had been proved composite.
However, I've been finding it difficult to get an answer to my question via a Google search. So, is it known whether $2^{65536}+1$ is prime or composite?

A: It's composite. It's divisible by 825753601.
Edit: It's also divisible by 188981757975021318420037633.


text:
Q: How to integated plupload into asp.net MVC2 project I try to use plupload in my asp.net MVC2 project, can I do it?
Please help me if it can.
Best regards!

A: it is same as normal file upload but i like plupload i will use on my project so following codes will work with plupload
[HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        // my project need single file upload so i get the first file
        // also you can write foreach statement to get all files
        HttpPostedFileBase postedFile = Request.Files[0];
        Image image = new Image();
        if (TryUpdateModel(image))
        {
            fRepository.AddImage(image);
            fRepository.Save();

            // Try to save file
            if (postedFile.ContentLength > 0)
            {
                string savePath = Path.Combine(Server.MapPath("~/Content/OtelImages/"), image.ImageID.ToString() +
                                                   Path.GetExtension(postedFile.FileName));
                postedFile.SaveAs(savePath);

                // Path for dbase
                image.Path = Path.Combine("Content/OtelImages/", image.ImageID.ToString() +
                                                   Path.GetExtension(postedFile.FileName));
            }

i didn't change the codes, but if you need any further help please ask, i'll explain


text:
Q: Prove that $0<\dfrac{1}{x}\ln(\dfrac{e^x-1}{x})<1$ for $x>0$ I have the following question before me:
Prove that $0<\dfrac{1}{x}\ln(\dfrac{e^x-1}{x})<1$ for $x>0$ using mean value theorem.
I took $f(x)=\ln(\dfrac{e^x-1}{x})$ and applied LMVT on $f(x)$ on the interval $[0,x]$.
This means that
there exists $c$ in interval $(0,x)$ such that
$\dfrac{f(x)-f(0)}{x-0}=f'(c)$
which further gives
$\dfrac{\ln\dfrac{e^x-1}{x}}{x}= f'(c)$
To prove the desired result, I now need to prove that $0<f'(c)<1$ by proving that $0<f'(x)<1$ for $x>0$.
For this I considered $f'(x)=g(x)=\dfrac{e^x}{e^x-1}-\dfrac{1}{x}$
But I could not really come up with a concrete proof for this.
You are requested to help me with this. Any help will be greatly appreciated.

A: Upon simplification we have to prove that $$1+x< e^x<\frac{1}{1-x}, \forall~ x\in (0,1)$$
Let $f(x)=e^x-1-x \implies f'(x)=e^x-1>0, \forall ~ x\in (0,1).$
This means $f(x)$ is an increasing function, so $f(x)>f(0) \implies e^x>1+x.$
Next, let $g(x)=(1-x)e^x-1\implies g'(x)=-e^x+(1-x)e^x=-xe^x <0$, so $g(x)$ is a decreasing function which implies $g(x)<g(0) \implies (1-x)e^x <1 \implies e^x <\frac{1}{1-x}$.

A: I think you're supposed to apply the MVT to $e^x$, using that $e^x - 1 = e^x - e^0 = x e^a$ for some $0 < a < x$. Then ${e^x - 1 \over x} = e^a$. Try taking it from there.

A: Equivalently, one has to prove that $$1+x<e^x<1+xe^x,\quad x\in (0,1). \tag{1}$$
Apply LMVT to $f(t)=e^t$, $\;t\in (0,x)$
$$\frac{e^x-1}{x-0}=f'(c)=e^c,\quad 0 <c<x. \tag{2}$$
Next, note that  $0<c<1 \implies 1 <e^c<e^x$, then from $(2)$, we can write
$$1<\frac{e^x-1}{x-0}<e^x,\quad x\in(0,1).$$
LHS gives both the results in $(1)$.

A: Note that for $x>0$,
$$
1 + x < 1 + x + \frac{{x^2 }}{{2!}} + \frac{{x^3 }}{{3!}} +  \ldots  < 1 + x + x^2  + \frac{{x^3 }}{{2!}} +  \ldots ,
$$
that is $1+x<e^x<1+xe^x$ for all $x>0$. This is equivalent to the desired inequality.


text:
Q: Chef and Three dog solution Recently I came across a question on Codechef known as Chef and Three dogs. The question look pretty easy but I'm not getting the logic. Question is as follow:
Chef has three dogs sitting at the vertices of an equilateral triangle. The length of each side of the triangle equals to s meters. Chef gives the command "Start!" and each dog starts to run with constant speed v meters per second. At each moment, each dog is running towards the dog just right to him (in counter-clockwise direction). Therefore, their trajectories are forming some spirals that converging to one point as illustrated below.

I have gone through some correct submission but i was unable to figure out why the answer is (2/3)*(s/v)?
here is the sample accepted code :
#include<stdio.h>
int main()
{
    int T,s,v;
    double t;
    scanf("%d\n",&T);
    while(T--)
    {
        scanf("%d%d",&s,&v);
        t = (2.0*s)/(3.0*v);
        printf("%f\n",t);
    }
        return 0;
}

A: This problem can be easily visualized by noticing the symmetry defined in the question.
The first step is to understand that because of the inherent symmetry in the positions and motions of the three dogs, their positions at any given time will always form equilateral triangle as shown in the figure.

Now assume that you are sitting on one of the dogs(It's strange, but assume it nevertheless. :P). For you, the equilateral triangle will keep on decresing in size till it finally collapses, the point where the dogs meet. So, this will be your view at any point of time.

To an observer sitting on one of the dogs, the components of velocities of its adjacent dog at any given point of time are
depicted in the third figure.

Thus, any given dog feel that
while it is moving towards its adjacent dog at a speed v, the adjacent dog is moving towards it at a speed v/2. Thus the dogs seem to approach each other at a constant rate of v + v/2 = 3v/2. Since the initial distance was s, the time takes to meet is given by, s/(3v/2) = 2s/3v.


text:
Q: Ensuring the patch was completed successfully I have struggled to apply this patch for a few days now. Yesterday was the closest I have come to completing the patch. I still get the notice "ERROR: Patch can't be applied/reverted successfully."
Here is what Putty returns:
Checking if patch can be applied/reverted successfully...
ERROR: Patch can't be applied/reverted successfully.

patching file .htaccess
patching file .htaccess.sample
patching file app/code/core/Mage/Admin/Model/Block.php
patching file app/code/core/Mage/Admin/Model/Resource/Block.php
patching file app/code/core/Mage/Admin/Model/Resource/Block/Collection.php
patching file app/code/core/Mage/Admin/Model/Resource/Variable.php
patching file app/code/core/Mage/Admin/Model/Resource/Variable/Collection.php
patching file app/code/core/Mage/Admin/Model/Variable.php
patching file app/code/core/Mage/Admin/etc/config.xml
patching file app/code/core/Mage/Admin/sql/admin_setup/upgrade-1.6.1.1-1.6.1.2.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block/Edit.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block/Edit/Form.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block/Grid.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Edit.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Edit/Form.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Grid.php
patching file app/code/core/Mage/Adminhtml/controllers/Permissions/BlockController.php
patching file app/code/core/Mage/Adminhtml/controllers/Permissions/VariableController.php
patching file app/code/core/Mage/Adminhtml/etc/adminhtml.xml
patching file app/code/core/Mage/Catalog/Model/Product/Option/Type/File.php
patching file app/code/core/Mage/Core/Controller/Front/Action.php
patching file app/code/core/Mage/Core/Controller/Varien/Router/Admin.php
patching file app/code/core/Mage/Core/Helper/UnserializeArray.php
patching file app/code/core/Mage/Core/Model/Email/Template/Filter.php
patching file app/code/core/Mage/Core/Model/Resource/Setup.php
patching file app/code/core/Mage/Core/etc/config.xml
patching file app/code/core/Mage/Core/etc/system.xml
patching file app/code/core/Mage/Customer/Block/Account/Changeforgotten.php
patching file app/code/core/Mage/Customer/Block/Account/Resetpassword.php
patching file app/code/core/Mage/Customer/controllers/AccountController.php
patching file app/code/core/Mage/Downloadable/Model/Product/Type.php
patching file app/code/core/Mage/Eav/Model/Resource/Attribute/Collection.php
patching file app/code/core/Mage/Sales/Model/Resource/Order/Item/Collection.php
patching file app/code/core/Mage/Sales/controllers/DownloadController.php
patching file app/code/core/Mage/SalesRule/Model/Resource/Coupon/Collection.php
patching file app/design/adminhtml/default/default/layout/admin.xml
patching file app/design/frontend/base/default/layout/customer.xml
patching file app/design/frontend/base/default/template/customer/form/register.phtml
patching file app/design/frontend/base/default/template/customer/form/resetforgottenpassword.phtml
patching file app/design/frontend/base/default/template/persistent/customer/form/register.phtml
patching file app/design/frontend/default/iphone/layout/customer.xml
Hunk #1 succeeded at 155 (offset 14 lines).
Hunk #2 succeeded at 174 (offset 14 lines).
patching file app/design/frontend/default/modern/layout/customer.xml
patching file app/design/frontend/rwd/default/layout/customer.xml
patching file app/design/frontend/rwd/default/template/customer/form/resetforgottenpassword.phtml
patching file app/design/frontend/rwd/default/template/persistent/customer/form/register.phtml
patching file cron.php
The next patch would delete the file dev/tests/functional/.htaccess,
which does not exist!  Assume -R? [n]
Apply anyway? [n]
Skipping patch.
1 out of 1 hunk ignored
patching file errors/processor.php
patching file lib/Unserialize/Parser.php
patching file lib/Unserialize/Reader/Arr.php
patching file lib/Unserialize/Reader/ArrKey.php
patching file lib/Unserialize/Reader/ArrValue.php
patching file lib/Unserialize/Reader/Bool.php
patching file lib/Unserialize/Reader/Dbl.php
patching file lib/Unserialize/Reader/Int.php
patching file lib/Unserialize/Reader/Str.php
patching file lib/Varien/Data/Collection/Db.php
patching file lib/Zend/Xml/Security.php

If it has been applied, what are the next steps I should take? I've cleared the cache yet "Enable Admin routing compatibility mode" does not appear where it should.
Any ideas?

A: Try to remove the dev/tests/functional/.htaccess from your patch stack / stash and apply the patch then.
It seems natural to me that a patch cannot be applied successfully if you skip a file.

A: Actually, I just figured it out. I downloaded a stock 1.9.2.1 Magento directory and my system was missing the dev file completely.
The person my company hired to set up their Magento didn't do a great job, and they did a 'custom' install making these things very difficult to do.
The patch applied successfully and the "Enable Admin routing compatibility mode" is visible on the backend.


text:
Q: Von Neumann Universe, difference between Ordinal and Successor Ordinal I'm having some difficulty understanding the difference between two ways that ordinals appear to be defined.  One way is an ordinal $\beta$ is defined by:
$V_\beta := \mathcal{P}(V_\beta)$
And results in the following ranked ordinals:
$V_0 := \emptyset = \emptyset$
$V_1 := \{0\} = \{\emptyset\} $
$V_2 := \{0, 1\} = \{\emptyset, \{\emptyset\}\} $
Then the successor ordinal $\alpha$ is defined slightly different (no power set) by:
$S(\alpha) = \alpha \space \cup \{\alpha\}$
Can anyone explain the difference between $V_\beta$  and $S(\alpha)$?  I would expect the successor to be the next ranked ordinal $V_\beta$, however after expanding $V_3$ these two definitions are not equal:
$V_{3a} = S(V_2) = \{0, 1, 2\} = \{\emptyset, \{\emptyset\}, \{\emptyset, \{\emptyset\}\}\}$
while:
$V_{3b} = \mathcal{P}(V_2) = \{0, 1, 2, ?\} = \{\emptyset, \{\emptyset\}, \{\{\emptyset\}\}, \{\emptyset, \{\emptyset\}\}\}$
Note:
$V_{3b} \backslash V_{3a} = \{\{\emptyset\}\}
$
I'm hoping to get this down as it seems like it forms a basis for future learning.  Any insight appreciated.  Thanks!

A: The $V_\alpha$ are not ordinals. They are the ranks of the Von Neumann hierarchy, which are indexed by the ordinals.
However, they do have a similarity. The ordinal $\alpha$ is the set of all ordinals less than $\alpha$. $V_\alpha$ is the set of all sets with rank less than $\alpha$.

A: The sets $V_\beta$ are not ordinals.  They are a family of sets indexed by ordinals: we have one set $V_\beta$ for each ordinal $\beta$.  As such, they are not an "alternate definition of ordinals" but are instead just certain sets that are related to but quite distinct from ordinals.

A: Your first equation should be $V_{\beta+1} := \mathcal{P}(V_\beta)$, but that is not for defining ordinals.  It is for defining levels of the cumulative hierarchy, which are indexed by ordinals, the subscipts.  $V_\beta$ is not the same thing as $\beta$.  Your definition of a successor ordinal is the usual one.  Your $V_{3a}$ is the usual set denoted by $3$, but is not a stage of the cumulative hierarchy.  Both of your definitions only work for successor ordinals.  You need a definition for limit ordinals.  The usual definitions are $V_\beta = \bigcup_{\alpha \lt \beta} V_\alpha$ for $\beta$ a limit and $\beta = \bigcup_{\alpha \lt \beta} \alpha$ for $\beta$ a limit


text:
Q: Problem from Purcell and Morin's Electricity and Magnetism: Holding the charge in place This is the problem given in Purcell and Morin's electricity and magnetism book. (Problem 3.2 If you have the book)

Figure:

I was able to figure out that the charges on A,B,C,D cant be held after connecting C and D because if you consider a loop from A to C and back to A through the wires, for a static electric field, from Kirchhoff's loop rule, $$\oint \vec{E}\cdot d\vec{l}=0$$
If the wires have no resistance, then the potential drops across A-C and B-D will add up and wont be zero. So the charges will disappear as soon as C and D are connected so as to make $\oint \vec{E}\cdot d\vec{l}=0$
But in what way will they cancel out? And I was not able to understand this (stated in the solution):

Won't induced charges have equal magnitude?

A: The picture in the book does not show all field lines. There will be some field lines from the positively charged sphere B to the negatively charged sphere A, also from the positively charged sphere C to the negatively charged sphere D. This can be seen from the superposition principle (electrostatics is all linear so superposition of fields and charges generally applies). Imagine there are only spheres A and B, then certainly there will be some electric field lines from B to A. The meaning of the puzzling comment from the book is that sphere A interacts with both spheres C and B. Interaction between A and D, and between C and B does not result in strong vertical component of electric field, can be neglected in this reasoning.
Here is an illustrative plot of distribution of electric potential, also showing some electric field lines, calculated with the standard formula, from four point charges, charged as in the problem statement. We can see the vertical electric field, upward on the left and downward on the right.

So, we conclude that in this setup there is some electric field from B to A and from C to D. As soon as we add the connecting wires this electric field will push the charges in the wires until all charges on the spheres cancel out.

A: I think the approach you should take is to show that the above situation is an unstable equilibrium.  Consider what will happen if sphere A has a small excess of negative charge.  This small excess will then move to sphere B, reducing its positive charge.  This will lead to sphere D having a small excess of negative charge, which will then lead to it moving to sphere C, reducing its positive charge.  Then sphere A will have a small excess of negative charge all over again.  This will continue until the charges have been neutralized.

A: Assuming charges on C induces same amount of charges on A until C and D are connected.

Once C and D are connected, since charges on C are more closed to each other than "the distance between charges on C and charges on A", hence the self-repulsing force on C win;
Hence then the self-repulsing force decrease the amount of charges on C; and then that causing the induced charges on A decrease respectively.
The process goes on and on till there is no net charges everywhere.


text:
Q: NS_ERROR_UNEXPECTED in FireFox on mozRTCPeerConnection() I am using adapter.js in my webrtc 1-1 video call application. It works fine on Google Chrome and both peers see each other's video and can hear audio. However, when I run the same application on FireFox, I get the following error on console which comes from adapter.js.
NS_ERROR_UNEXPECTED

This is the function from adapter.js which gives the above error on return statement:
var RTCPeerConnection = function(pcConfig, pcConstraints) {
  // .urls is not supported in FF yet.
  maybeFixConfiguration(pcConfig);
  return new mozRTCPeerConnection(pcConfig, pcConstraints);
};

This is what is inside pcConfig:
{"iceServers":[{"url":"stun:stun.l.google.com:19302"}]}

This is what is inside pcConstraints:
{"optional":[{"DtlsSrtpKeyAgreement":true},{"RtpDataChannels":true}],"mandatory":{}}

This is how the function maybeFixConfiguration(pcConfig) looks like:
function maybeFixConfiguration(pcConfig) {
  if (pcConfig == null) {
    return;
  }
  for (var i = 0; i < pcConfig.iceServers.length; i++) {
    if (pcConfig.iceServers[i].hasOwnProperty('urls')){
      pcConfig.iceServers[i]['url'] = pcConfig.iceServers[i]['urls'];
      delete pcConfig.iceServers[i]['urls'];
    }
  }
}

I don't understand what mistake I am doing here. Is something wrong with pcConfig and pcConstraints structure. I am using the latest FireFox I downloaded today.

A: This may be outdated but it may be of some help.
I had the same NS_ERROR_UNEXPECTED when creating the new RTCPeerConnection(config).
My problem was that my iceServers array had an invalid urls part that was giving problems to Firefox, specifically i had

urls: 'turn:someUsername@ipAddress:port'

I found out after some time that someUsername@ was not acceptable to FF although it works on Chrome.
Removing the username@ part of the string fixed the issue for me, hope it helps.

A: I found the mistake, it was in how we specify the iceServers.
Correction is :
{'iceServers': [
  createIceServer(isChrome
    ? 'stun:stun.l.google.com:19302'
    : 'stun:23.21.150.121', null, null)
]}

A: Update your browser. Fully qualified domain names in iceServer URLs have been supported since Firefox 22 (circa March 2013), and adapter.js does not generally cover browsers that old.
Also, note that createIceServer is no longer needed - and unavailable - in the latest version of adapter.js. There's still a polyfill in there for some changes in syntax, but it is handled transparently now, without needing to use this special function.


text:
Q: compiling entire Xilinx ISE unisims and XilinxCoreLib libraries (minus secure ip) with GHDL simulator I was curious if anybody has had any luck compiling the entire Xilinx ISE unisims library for GHDL simulator?  I tried to compile just the package file for unisims and it gives me an error.
I Was wondering if it will compile completely by commenting out the unsupported sections of VHDL code... or it there's something else that needs to be done such as compiling a difference vital library or using different version --std.
because I know I can pull out a single unisims component and compile with ghdl... just wondering how to complete 90% of the remaining components.
$ ghdl -a --std=08 --work=unisims C:/Xilinx/14.7/ISE_DE/ISE/vhdl/src/unisims/unisim_VCOMP.vhd

$ ghdl -a --std=08 --work=unisims C:/Xilinx/14.7/ISE_DE/ISE/vhdl/src/unisims/unisim_VPKG.vhd

ERROR: ../../src/vital2000/timing_p.vhdl:152:14: result subtype of a pure function cannot have access subelements

A: GHDl is delivered with scripts to precompile libraries like Xilinx ISE primitive libraries (unisim, unimacro, uniprim, ...).
See this documentation: https://ghdl.readthedocs.io/en/latest/building/PrecompileVendorPrimitives.html
You can run the scripts in verbose or debug mode, to see all command line calls to GHDL and the applied parameters.
Bash:
./compile-xilinx-ise.sh -d

PowerShell:
.\compile-xilinx-ise.ps1 -Debug