text:
Q: MVC Resource causes 404 Not Found with Spring MVC & Tiles I have a working MVC application with tiles.  However, I am having trouble with the MVC Resource.  If I do not include the mvc:resources in my xml file or refer to it in the html to the CSS files, I can successfully view the pages.  However, if I add the resource tags in, it gives me a "The requested resource is not available" error - preventing me from seeing the page at all.
Could you assist me in determining the cause for this?  I have tried to follow the documentation and the myriad of tutorials for it - however it doesn't seem to work.  Thanks!

EDIT: I know there are multiple questions addressing this - I have browsed through the vast majority of them (both on and off Stack Overflow) and tried solutions with no success.
EDIT: After some troubleshooting, I determined that my controllers are successfully accessed (by seeing the logging data).  It cannot find "/ContactManagement/WEB-INF/jsp/layout.jsp".  This only occurs once I refer to .  I commented out the CSS file references in my views; however, that does not fix it.
Mapping is completed for all the controllers now, as well as the mvc:resources mapping.  It's just the .jsp files that it is having trouble accessing.

In my configuration file, I include the MVC resources through
<mvc:resources mapping="/resources/**" location="/resources/" />

I refer to in in the html as
<link href="<c:url value='/resources/css/default.css'/>" rel="stylesheet" />

My file structure is
-WebContent
---resources
------css
------js
------images
---WEB-INF
------jsp
------spring-servlet.xml
------tiles.xml

Here is my spring-servlet.xml
    <?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages" />
    <property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="/WEB-INF/jdbc.properties" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.databaseurl}"
    p:username="${jdbc.username}" p:password="${jdbc.password}" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass">
        <value>
            org.springframework.web.servlet.view.tiles2.TilesView
        </value>
    </property>
</bean>
<bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/tiles.xml</value>
        </list>
    </property>
</bean>

<mvc:resources mapping="/resources/**" location="/resources/" />
<tx:annotation-driven transaction-manager="transactionManager" />

<context:component-scan base-package="mil.navy.navsupbsc" />

Here is the head of the HTML layout page
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="type" />
<meta http-equiv="X-UA-Compatible" content="IE=9">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%-- href="<c:url value="/resources/css/default.css"/>"  --%>
<link
 href="<c:url value='/resources/css/default.css'/>" rel="stylesheet" />

<title><tiles:insertAttribute name="title" ignore="true" /></title>
</head>

Here are my startup logs
Jan 31, 2014 9:16:26 PM com.springsource.tcserver.security.PropertyDecoder <init>
INFO: tc Runtime property decoder using memory-based key
Jan 31, 2014 9:16:26 PM com.springsource.tcserver.security.PropertyDecoder <init>
INFO: tcServer Runtime property decoder has been initialized in 392 ms
Jan 31, 2014 9:16:27 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-48080"]
Jan 31, 2014 9:16:27 PM com.springsource.tcserver.serviceability.rmi.JmxSocketListener init
INFO: Started up JMX registry on 127.0.0.1:46969 in 224 ms
Jan 31, 2014 9:16:27 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1393 ms
Jan 31, 2014 9:16:27 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jan 31, 2014 9:16:27 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: VMware vFabric tc Runtime 2.9.3.RELEASE/7.0.42.A.RELEASE
Jan 31, 2014 9:16:27 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor C:\Program Files\Spring Toolsuite\vfabric-tc-server-developer-2.9.3.RELEASE\base-instance\conf\Catalina\localhost\ContactManagement.xml
Jan 31, 2014 9:16:27 PM org.apache.catalina.startup.SetContextPropertiesRule begin
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:ContactManagement' did not find a matching property.
Jan 31, 2014 9:16:27 PM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(C:\Program Files\Spring Toolsuite\vfabric-tc-server-developer-2.9.3.RELEASE\base-instance\wtpwebapps\ContactManagement\WEB-INF\lib\servlet-api-2.5.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
Jan 31, 2014 9:16:30 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Jan 31, 2014 9:16:30 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'spring'
[localhost-startStop-1] INFO org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'spring': initialization started
[localhost-startStop-1] INFO org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'spring-servlet': startup date [Fri Jan 31 21:16:30 EST 2014]; root of context hierarchy
[localhost-startStop-1] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-servlet.xml]
[localhost-startStop-1] INFO org.springframework.beans.factory.config.PropertyPlaceholderConfigurer - Loading properties file from ServletContext resource [/WEB-INF/jdbc.properties]
[localhost-startStop-1] INFO org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: oracle.jdbc.OracleDriver
[localhost-startStop-1] INFO org.springframework.web.servlet.view.tiles2.TilesConfigurer - TilesConfigurer: adding definitions [/WEB-INF/tiles.xml]
[localhost-startStop-1] INFO org.apache.tiles.context.AbstractTilesApplicationContextFactory - Initializing Tiles2 application context. . .
[localhost-startStop-1] INFO org.apache.tiles.context.AbstractTilesApplicationContextFactory - Finished initializing Tiles2 application context.
[localhost-startStop-1] INFO org.apache.tiles.access.TilesAccess - Publishing TilesContext for context: org.springframework.web.servlet.view.tiles2.SpringTilesApplicationContextFactory$SpringWildcardServletTilesApplicationContext
[localhost-startStop-1] INFO org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'

    2014-01-31 21:01:01,513 INFO [org.hibernate.tool.hbm2ddl.SchemaValidator] - <HHH000229: Running schema validator>
    [...Database Validation...]

[localhost-startStop-1] INFO org.springframework.orm.hibernate4.HibernateTransactionManager - Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@1ca09d2] of Hibernate SessionFactory for HibernateTransactionManager
[localhost-startStop-1] INFO org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'spring': initialization completed in 11998 ms
Jan 31, 2014 9:16:42 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\Program Files\Spring Toolsuite\vfabric-tc-server-developer-2.9.3.RELEASE\base-instance\webapps\manager
Jan 31, 2014 9:16:42 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\Program Files\Spring Toolsuite\vfabric-tc-server-developer-2.9.3.RELEASE\base-instance\webapps\ROOT
Jan 31, 2014 9:16:42 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-48080"]
Jan 31, 2014 9:16:42 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 15126 ms

When I hit the page, it comes up with the following:
[tomcat-http--3] WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/ContactManagement/contact] in DispatcherServlet with name 'spring'

EDIT: I ran it without the mvc resource tags and it came up with these additional lines in the log (makes me think that for some reason it isn't mapping the controllers when i include the resource tags):
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addressType] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addressType.*] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addressType/] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addressType/.*] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addressType/add] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addressType/add.*] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addressType/add/] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addressType/delete/{addressTypeId}] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addressType/delete/{addressTypeId}.*] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addressType/delete/{addressTypeId}/] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addresstype] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addresstype.*] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addresstype/] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addresstype/.*] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addresstype/add] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addresstype/add.*] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addresstype/add/] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addresstype/delete/{addressTypeId}] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addresstype/delete/{addressTypeId}.*] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/addresstype/delete/{addressTypeId}/] onto handler 'addressTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/contact] onto handler 'contactController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/contact.*] onto handler 'contactController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/contact/] onto handler 'contactController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/contact/.*] onto handler 'contactController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/country] onto handler 'countryController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/country.*] onto handler 'countryController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/country/] onto handler 'countryController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/country/.*] onto handler 'countryController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/country/add] onto handler 'countryController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/country/add.*] onto handler 'countryController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/country/add/] onto handler 'countryController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/country/delete/{countryId}] onto handler 'countryController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/country/delete/{countryId}.*] onto handler 'countryController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/country/delete/{countryId}/] onto handler 'countryController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/emailtype] onto handler 'emailTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/emailtype.*] onto handler 'emailTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/emailtype/] onto handler 'emailTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/emailtype/.*] onto handler 'emailTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/emailtype/delete/{emailTypeId}] onto handler 'emailTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/emailtype/delete/{emailTypeId}.*] onto handler 'emailTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/emailtype/delete/{emailTypeId}/] onto handler 'emailTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/emailtype/add] onto handler 'emailTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/emailtype/add.*] onto handler 'emailTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/emailtype/add/] onto handler 'emailTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/phonetype] onto handler 'phoneTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/phonetype.*] onto handler 'phoneTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/phonetype/] onto handler 'phoneTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/phonetype/.*] onto handler 'phoneTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/phonetype/delete/{phoneTypeId}] onto handler 'phoneTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/phonetype/delete/{phoneTypeId}.*] onto handler 'phoneTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/phonetype/delete/{phoneTypeId}/] onto handler 'phoneTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/phonetype/add] onto handler 'phoneTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/phonetype/add.*] onto handler 'phoneTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/phonetype/add/] onto handler 'phoneTypeController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/salutation] onto handler 'salutationController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/salutation.*] onto handler 'salutationController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/salutation/] onto handler 'salutationController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/salutation/add] onto handler 'salutationController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/salutation/add.*] onto handler 'salutationController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/salutation/add/] onto handler 'salutationController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/salutation/delete/{salutationId}] onto handler 'salutationController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/salutation/delete/{salutationId}.*] onto handler 'salutationController'
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/salutation/delete/{salutationId}/] onto handler 'salutationController'


text:
Q: Cocos2D HighScore framework i'm a new developer working on a game project using Cocos2D, I need help in integrating HighScore in my game, is there a good framework for this? or should i do it from scratch using TableView? i tried to find something related to this using google but all the topics were from 2009/10.
Please help!

A: If you don't want to reinvent the wheel and cross-platform is not a concern, you can add a simple GameCenter leaderboard first (Apple provides a standard leaderboard view which your apps can use, you have to create the leaderboard on iTunes connect before implementing it).
Later, when you have the default version running, you can customize it to make it look like your game. You can read more about all this in the Game Center Programming Guide.
If on the other hand you want to avoid using Apple provided classes, see this thread on the Unity forums where some alternatives are mentioned.

A: I have recently done high score implementation in Cocos2D game and i did something like following. Hope this helps.
(I have stored only top 5 high scores.)

*

*Created HighScore.plist file with empty array (HighScoreArray) inside that.

*In AppDelegate.m Copy HighScore.plist if its not in User Documents Directory.

*When game is over you need to calculate and update HighScore.plist.

*

*First of all check if current Score is not 0 (Zero).

*

*Check if HighScore Array contains 5 scores.

*

*YES then insert current score. Sort array and remove last object update plist.

*NO then insert current score. Sort array and update plist file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Import multiple .mat files without headers
Currently trying to import the following via the following script:
files = dir('C:\Users\student\Desktop\pattern hw4\train\*.mat');

for i=1:length(files)
    A = load(files(i)); % <-- line 7
end

I get the error though:
Error using load
Argument must contain a string.

Error in hw4 (line 7)
    A = load(files(i));

After adding .name I get the error:
>> hw4
Error using load
Unable to read file 'class1_1.mat': no such file or directory.

Error in hw4 (line 7)
    A = load(files(i).name);

Ok fixed and final answer/solution:
files = dir('C:\Users\student\Desktop\pattern hw4\train\*.mat');

dname='C:\Users\student\Desktop\pattern hw4\train\';

for i=1:length(files)
    fname=fullfile(dname,files(i).name);
    A = load(fname);
end

A: The load command is expecting the filename whereas dir returns a structure.  Try:
A = load(files(i).name);

A: I think you need to use A = load(files(i).name); at line 7.
files is an array of structs


text:
Q: Using Lagrange multipliers to find the max and min I have the equation $$f(x,y)=x^2+y^2$$ and the constraint $$(x-1)^2+4y^2=4$$
So I must find the min and max. My try:
So I get the equations:
$$2x=λ(2x-2)$$
$$2y=λ8y$$
and I get λ=1/4 and x=1/3
Any help is appreciated

A: Outline
You have set it up right.
$L = x^2 + y^2 - \lambda\{(x-1)^2 + 4y^2 - 4\} = 0 $ and then find partial derivatives of $L$ with respect to $x$ and $y$. You have made a slight mistake in solving, you should get $\lambda = \frac14$ and $x = -\frac13$.
Now put back this value of $x$ in the constraint and solve for $y$, you should get $y = \pm \frac{\sqrt5}{3}$. I think you can take it from here.
You may also observe that this only gives the $\color{blue}{minimum}$ value of $x^2 + y^2 = \frac23$.
To get the maximum value, I would reason out that the constraint is an $\color{blue}{ellipse}$ and we are trying to find the largest $\color{blue}{circle}$ centered at the origin and at least touching, if not intersecting the ellipse. Touching because we want an extrimity. So, this ellipse intersects $X-$axis at $x = -1$ and $x = 3$. So the circle radius will be 3, i.e.. $x = 3$, and in order to satisfy the contraint, $y = 0$. So, the $\color{blue}{maximum}$value is $9$.
Summary
The minimum value of $x^2 + y^2$ is $\color{blue}{\frac23}$ and the maximum value is $\color{blue}{9}$.

A: Actually, there's no need to use multipliers.  You may solve the constraint easily for $y$ and plug this result in $f$. Having done this you'll see nearly instantly the extrema at $x=-1/3,-1,3$, even without using differentiation.

A: Easier to remember general derivation how LM comes about and then apply in our particular case.
$$ f = x^2 + y^2 ; g   = (x-1)^2 + 4y^2 - 4  $$
A LM can be chosen using partial derivatives:
$$ \lambda = \dfrac{ f_x}{ f_y} =   \dfrac{ g_x}{ g_y}. $$


text:
Q: Aligning a Point Cloud with the Floor (plane) Using Open3D Community,
I am trying to align a point cloud with the detected floor using Open3D. So far I implemented the following steps (partly of this answer):

*

*Detecting the floor using Open3D's plane segmentation

*Translating the plane to the coordinate center

*Calculating rotation angle between plane normal & z-axis

*Calculating the axis of rotation

*Rotating the point cloud using Open3Ds get_rotation_matrix_from_axis_angle function (see 3)

The results are OK, but I have to use an optimization-factor at the end for better results. Is there a mistake or a simpler/ more precise way for the alignment?
# See functions below

# Get the plane equation of the floor → ax+by+cz+d = 0
floor = get_floor_plane(pcd)
a, b, c, d = floor

# Translate plane to coordinate center
pcd.translate((0,-d/c,0))

# Calculate rotation angle between plane normal & z-axis
plane_normal = tuple(floor[:3])
z_axis = (0,0,1)
rotation_angle = vector_angle(plane_normal, z_axis)

# Calculate rotation axis
plane_normal_length = math.sqrt(a**2 + b**2 + c**2)
u1 = b / plane_normal_length
u2 = -a / plane_normal_length
rotation_axis = (u1, u2, 0)

# Generate axis-angle representation
optimization_factor = 1.4
axis_angle = tuple([x * rotation_angle * optimization_factor for x in rotation_axis])

# Rotate point cloud
R = pcd.get_rotation_matrix_from_axis_angle(axis_angle)
pcd.rotate(R, center=(0,0,0))

# FUNCTIONS
def vector_angle(u, v):
    return np.arccos(np.dot(u,v) / (np.linalg.norm(u)* np.linalg.norm(v)))

def get_floor_plane(pcd, dist_threshold=0.02, visualize=False):
    plane_model, inliers = pcd.segment_plane(distance_threshold=dist_threshold,
                                             ransac_n=3,
                                             num_iterations=1000)
    [a, b, c, d] = plane_model
    return plane_model


text:
Q: How to Deploy Ruby using Azure Pipelines to Azure App Services? I have been trying to deploy my Ruby on Rails application to Azure App Services for a couple days now. I'm getting really frustrated trying to figure this out. I'm new to Ruby and I've never used rbenv.
Goal
I am trying to use Azure Pipelines to deploy my code to an Azure App Services Deployment Slot.
Process
I observed the following:

*

*Azure App Service is using Ruby 2.6.2 managed by rbenv.

*Azure Pipelines is using Ruby 2.6.6.

In an attempt to ignore the minor version I had updated my azure-pipeline.yml to only reference Ruby 2.6.
steps:
- task: UseRubyVersion@0
  inputs:
    versionSpec: '~> 2.6'

I am using this AzureWebApp Task to do the deployment into the slot, which is uploading the code. I can tell by the error messages when I'm experimenting.
- task: AzureWebApp@1
  inputs:
    azureSubscription: 'WheelerLearning/wheeler146'
    appName: 'wheeler-verify-app-site'
    deploymentMethod: 'zipDeploy'
    package: $(System.DefaultWorkingDirectory)/$(appDir)
    slotName: 'stg'

https://github.com/wheelers-websites/CloudGuruChallenge_21.02/blob/main/azure-pipelines.yml
Azure Pipelines Error
When I tried to use 2.6.2 in my azure-pipeline.yml I saw the following error:
2021-04-01T03:26:44.8712433Z ##[section]Starting: UseRubyVersion
2021-04-01T03:26:44.8719527Z ==============================================================================
2021-04-01T03:26:44.8719967Z Task         : Use Ruby version
2021-04-01T03:26:44.8720409Z Description  : Use the specified version of Ruby from the tool cache, optionally adding it to the PATH
2021-04-01T03:26:44.8720799Z Version      : 0.182.0
2021-04-01T03:26:44.8721102Z Author       : Microsoft Corporation
2021-04-01T03:26:44.8721535Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/tool/use-ruby-version
2021-04-01T03:26:44.8722005Z ==============================================================================
2021-04-01T03:26:45.3163457Z ##[warning]It is not recommended to specify exact version on Microsoft-Hosted agents. Patch version of Ruby can be replaced by new one on Hosted agents without notice and build stops to work. it is recommended to specify only major or major and minor version (Example: `2` or `2.4`)
2021-04-01T03:26:45.3185530Z ##[error]Version spec 2.6.2 for architecture %25s did not match any version in Agent.ToolsDirectory.
Available versions: /opt/hostedtoolcache
2.5.8,2.6.6,2.7.2,3.0.0
If this is a Microsoft-hosted agent, check that this image supports side-by-side versions of Ruby at https://aka.ms/hosted-agent-software.
If this is a self-hosted agent, see how to configure side-by-side Ruby versions at https://go.microsoft.com/fwlink/?linkid=2005989.
2021-04-01T03:26:45.3229225Z ##[section]Finishing: UseRubyVersion

Azure App Service Error
When I built the code with 2.6.6 then my Pipeline is working. However, my application is failing to start and the App Logs show me this error:
2021-04-02T04:27:01.516359889Z   _____
2021-04-02T04:27:01.516391591Z   /  _  \ __________ _________   ____
2021-04-02T04:27:01.516396291Z  /  /_\  \___   /  |  \_  __ \_/ __ \
2021-04-02T04:27:01.516400091Z /    |    \/    /|  |  /|  | \/\  ___/
2021-04-02T04:27:01.516403592Z \____|__  /_____ \____/ |__|    \___  >
2021-04-02T04:27:01.516407092Z         \/      \/                  \/
2021-04-02T04:27:01.516410492Z A P P   S E R V I C E   O N   L I N U X
2021-04-02T04:27:01.516413692Z
2021-04-02T04:27:01.516416692Z Documentation: http://aka.ms/webapp-linux
2021-04-02T04:27:01.516419892Z Ruby quickstart: https://aka.ms/ruby-qs
2021-04-02T04:27:01.516423093Z Ruby version 2.6.2
2021-04-02T04:27:01.516426193Z Note: Any data outside '/home' is not persisted
2021-04-02T04:27:02.189573568Z Starting OpenBSD Secure Shell server: sshd.
2021-04-02T04:27:03.195641038Z Bundle install with no 'without' options
2021-04-02T04:27:03.202609004Z Defaulting gem installation directory to /tmp/bundle
2021-04-02T04:27:03.202897520Z Defaulting site config directory to /home/site/config
2021-04-02T04:27:03.204055381Z Generating a secret key base
2021-04-02T04:27:03.692631856Z RAILS_ENV not set, default to production
2021-04-02T04:27:03.692659357Z Removing any leftover pids if present
2021-04-02T04:27:03.692723961Z rbenv: version `ruby-2.6' is not installed (set by /home/site/wwwroot/.ruby-version)
2021-04-02T04:27:03.744540384Z Running bundle check
2021-04-02T04:27:04.261191335Z rbenv: version `ruby-2.6' is not installed (set by /home/site/wwwroot/.ruby-version)
2021-04-02T04:27:04.682632482Z rbenv: version `ruby-2.6' is not installed (set by /home/site/wwwroot/.ruby-version)
2021-04-02T04:27:04.692844319Z missing dependencies, try redeploying
2021-04-02T04:27:05.282227084Z rbenv: version `ruby-2.6' is not installed (set by /home/site/wwwroot/.ruby-version)

I've read online that the same environment you're developing, building, and running your application should be the same, but that's not possible given my requirements. Is there any other option to get this to work?
Other Attempts
Finally, I was reading that rbenv can take it's Ruby version from an environment variable. I set this variable in the Azure App Service from the Console, yet it didn't change the error above.

Please take a look at my GitHub repo if you have the time to try and help me resolve this painful issue.
https://github.com/wheelers-websites/CloudGuruChallenge_21.02/tree/main/verify-app

A: You can run this task on a self-hosted agent with your own Ruby versions. To run this task on a self-hosted agent, set up Agent.ToolsDirectory by following the instructions below. The tool name to use is "Ruby."


text:
Q: Symfony2 form submitting on page refresh I have a form in Symfony2 framework. On successful submission of the page it renders another twig template file and returns the values by passing the parameters in an array. But after submission, if I refresh the page, again it is submitting the form and the table entry is created. Here is the code that is executed after submission in the controller,
$this->get('session')->setFlash('info', $this->get('translator')->trans('flash.marca'));

return $this->render('NewBundle:Backend:marca.html.twig', array(
                                        'active' => 1,
                                        'marca' => $marca,
                                        'data' => $dataCamp,
                                        'dataMarca' => $this->getMarcas($admin->getId()),
                                        'admin' => $admin,
            ));

I want the form to be redirected to the twig files mentioned there with the parameters and the alert message mentioned above. But I don't want the form to be submitted on page refresh.
Thanks

A: This worked for me:
return $this->redirectToRoute("route_name");

A: You should save submitted data in session and redirect user. Then you will be able to refresh page as much as you want without additional submission.
Example code - your action algorithm should be similar:
...
/**
 * @Route("/add" , name="acme_app_entity_add")
 */
public function addAction()
{
    $entity = new Entity();
    $form = $this->createForm(new EntityType(), $entity);
    $session = $this->get('session');

// Check if data already was submitted and validated
if ($session->has('submittedData')) {
    $submittedData = $session->get('submittedData');
    // There you can remove saved data from session or not and leave it for addition request like save entity in DB
    // $session->remove('submittedData');

    // There your second template
    return $this->render('AcmeAppBundle:Entity:preview.html.twig', array(
        'submittedData' => $submittedData
        // other data which you need in this template
    ));
}

if ($request->isMethod('POST')) {
    $form->bindRequest($request);

    if ($form->isValid()) {
        $this->get('session')->setFlash('success', 'Provided data is valid.');
        // Data is valid so save it in session for another request
        $session->set('submittedData', $form->getData()); // in this point may be you need serialize saved data, depends of your requirements

        // Redirect user to this action again
        return $this->redirect($this->generateUrl('acme_app_entity_add'));
    } else {
        // provide form errors in session storage
        $this->get('session')->setFlash('error', $form->getErrorsAsString());
    }
}

return $this->render('AcmeAppBundle:Entity:add.html.twig', array(
    'form' => $form->createView()
));
}

Redirect to same page is preventing additional data submission. So lean of this example modify your action and you will be fine.
Also instead save data in session you can pass it through redirect request. But I think this approach is more difficult.

A: *

*Save your data (session/db/wherever you want it saved)

*redirect to a new action, retreiving the new data in that action, and rendering the template

this way, refreshing the new action, will only refresh the template, as the saving of your data happened in the previous action
understand ?
so basically replace your
return $this->render....

by
return $this->redirect($this->generateUrl('ROUTE_TO_NEW_ACTION')));

and in this new action, you put your
return $this->render....


text:
Q: Flexbox: How to prevent an item's height from exceeding other element's height? https://jsfiddle.net/nr7b2qtk/1/
HTML:

    something

CSS:
.flex{
  display:flex;
  align-items:center
}
.text{
  font-size:40px;
  line-height:1.5
  margin-left:auto;
  background:red;color:white
}

In the above code, I want the image size to scale down to match the height of the text element (which in this case is 45px), besides manually setting the image's width/height, is there any other way to do this in pure CSS?


text:
Q: Do well with something Can I use "do well with something" to mean "someone is getting better at something"?
For example:
A person doesn't follow rules, but he tries hard and begins following the rules.
So he asks:
Am I doing well with rules?
Does this mean that the person is getting better at following the rules,or he's started following rules?
And if a person is not good at something but starts learning it and asks:
Am I doing well with crafting?

A: Yes,

I am doing better with rules.

or more generally:

I am doing better with/at X-ing/X."

is perfectly idiomatic informal English.
A slightly more formal way of saying this is:

I am getting better at following rules.

or

I am getting better at X-ing.

or

I am getting better at Y-ing X.

(e.g. "following rules", "correcting errors"


text:
Q: Adding to PS1 in bash_profile In my .bash_profile currently, I have PS1='\[\e[1;91m\][\u@\h \w]\$\[\e[0m\] '. I am trying to follow these commands to show branch name on iTerm terminal.
I changed my
PS1='\[\e[1;91m\][\u@\h \w]\[\e[0m\][\033[32m\]\$(parse_git_branch)\[\033[00m\]$'

and the method at the end of the file
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

which shows now as:
[ava@GM12673 ~/blog][$(parse_git_branch) $

How to correctly add something to PS1?

A: I use the parse_git_branch function myself and I've found the following works well and gives me lots of info (and a carriage return!):
parse_git_branch () {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'
}
PS1='\033[01;31m\]\t\033[00m\]:'
PS1=$PS1'\[\033[01;32m\]\u@\h\[\033[00m\]:'
PS1=$PS1'\[\033[01;34m\]\w\033[00m\]:\033[01;33m\]$(parse_git_branch)\[\033[00m\]\n\$ '
PS2='\[\033[01;36m\]>'

for

A: Your quoting is broken. Change it to
PS1='\[\e[1;91m\][\u@\h \w]\[\e[0m\]\[\e[32m\]$(parse_git_branch)\[\e[00m\]$'


text:
Q: How do i fire an event after a few seconds? I am making a application where i would like to log in with a face detection. But this is not real, its just to make ik look like its scanning.
So when i press the LOG IN button, the kinect takes my picture and show me the picture, on top of it is showing me in a text that its scanning.
Now i am stuck with the following issue, when i press the login button, the scanning label appears, but i would like to fire an other event that takes me to the next page, the homepage.
So i want the SCANNING label appearing for 3 seconds, and then the page should change.
This is what i tried, i worked with a timer, but that doesnt do annything.
    private void ActionButton_Click(object sender, System.EventArgs eventArgs)
    {

        _main.TakePicture();
        identifyBox.Source = _main.source.Clone();
        scanningLabel.Visibility = Visibility.Visible;
        _storyboard = (Storyboard)FindResource("scanningSB");
        //_storyboard.Begin();
        Start();
    }

    private void Start()
    {
        _tm = new Timer(3000);
        _tm.Elapsed += new ElapsedEventHandler(_tm_Elapsed);
        _tm.Enabled = true;
    }

    void _tm_Elapsed(object sender, ElapsedEventArgs e)
    {
        if (_tm == new Timer(3000))
        {
             ((Timer)sender).Enabled = false;
            _main.ContentPage.Children.Clear();
            _main.ContentPage.Children.Add(_homeScreen);
        }
    }

Okay i removed the if statement, but now it fires every 3 seconds a method.
How can i make it work 1 time.
Ok even this works, now i my ContentPage wont change? It gives me this error: The calling thread cannot access this object because a different thread owns it.
What can be wrong?

A: I think you can remove condition
if (_tm == new Timer(3000))

and keep it simple
void _tm_Elapsed(object sender, ElapsedEventArgs e)
{

    ((Timer)sender).Enabled = false;

    _main.ContentPage.Children.Clear();
    _main.ContentPage.Children.Add(_homeScreen);

}

when you set _tm = new Timer(3000); it will set the time to fire event after 3 seconds..

A: Change the _tm_Elapse to this:
void _tm_Elapsed(object sender, ElapsedEventArgs e)
    {
        if (_tm == (sender as Timer))
        {
            _main.ContentPage.Children.Clear();
            _main.ContentPage.Children.Add(_homeScreen);
        }
    }

Edit for answering:
"I just want it 1 time to fire after 3 sec"
void _tm_Elapsed(object sender, ElapsedEventArgs e)
    {
        if (_tm == (sender as Timer))
        {
            _tm.Stop();
            _main.ContentPage.Children.Clear();
            _main.ContentPage.Children.Add(_homeScreen);
        }
    }

A: This is even simpler, and it will only run once per call, the three second timer is built in, and furthermore, it won't disable other program functionalities while it is running:
async Task Start()
{
    await Task.Delay(3000);
    _main.ContentPage.Children.Clear();
    _main.ContentPage.Children.Add(_homeScreen);
}


text:
Q: sudo apt-get update doesn't work after uninstalling python2.7 I uninstalled python2.7 from my Ubuntu 16.04 system using command
sudo apt-get remove python2.7 but after doing this sudo apt-get update and sudo apt-get install returns error. While python 2.7 is still installed because doing python2.7 opens up python2.7 interpreter. I think I deleted important python packages but I am not sure.
 Errors were encountered while processing:
 python-pymysql
 python-xdg
 deluge-common
 deluge-gtk
 gimp
 gnome-tweak-tool
 gyp
 inkscape
 python-simplegeneric
 ipython
 python-pycurl
 python-tornado
 python-zmq
 ipython-notebook
 python-antlr
 python-appindicator
 python-bs4
 python-cvxopt
 python-six
 python-html5lib
 python-imaging
 python-lxml
 python-pyparsing
 python-tz
 python-matplotlib
 python-nose
 python-openpyxl
 python-pandas
 python-pil.imagetk:amd64
 python-pip
 python-ptyprocess
 python-py
 python-pyasn1
 python-pyasn1-modules
 python-pygame
 python-pyglet
 python-pytest
 python-serial
 python-setuptools
 python-simplejson
 python-sklearn
 python-sympy
 python-tables
 python-urwid
 python-wheel
 python-xlrd
 python-xlwt
 python-statsmodels
 python-zope.interface
 trash-cli
 xia
 Processing was halted because there were too many errors.
 E: Sub-process /usr/bin/dpkg returned an error code (1)

A: Once after you have uninstalled any package do a
sudo apt-get autoremove

which will remove all the packages that are associated with the one you have uninstalled. So that if you want it to be again installed it would not give any error and would reinstall everything.


text:
Q: IBM Wepshere JET Transformation pageLayout Unavailable This is my first question and I am really sorry if I made any mistakes.
So, I've been trying to follow the instruction on the following page http://www-01.ibm.com/support/knowledgecenter/SSZLC2_7.0.0/com.ibm.commerce.pagecomposerframework.doc/tasks/tpzwidgetcreatesrccd.htm?lang=en to make a Websphere Widget. However, I'm stucked at step 4e, which says "In the Transformation section, select com.ibm.commerce.toolkit.internal.pattern.pageLayout for the value of the ID field."
I'm stucked at that step because I don't have that particular ID in my JET Transformation. These are the only available selections that I have:

*

*com.ibm.commerce.toolkit.internal.pattern.componentprojects

*com.ibm.commerce.toolkit.internal.pattern.rest

*com.ibm.xtools.jet2.newproject

*com.ibm.xtools.jet2.transforms.projectupdater

*org.eclipse.jet.transforms.taglibdoc

My IBM Rational Application Developer version is 8.0.4.2 iFix1 in IBM WebSphere Commerce Server 7.0.
Is there anything I need to do first so I can have the com.ibm.commerce.toolkit.internal.pattern.pageLayout ID to show up in my JET Transformation? Thank you very much in advance for all the helps.

A: It's seems that this feature is available only in FEP7+. So you need to find com.ibm.commerce.toolkit.internal.pattern.pageLayout in JET ID.


text:
Q: Border Image with Linear Gradient I not expert in Jquery, but I tried build underline color with random color for each li like example this is a rough structure : Jsfiddle here
I use function random color in Jquery, how to set Linear gradient in function random color to looks like example ?
I try
FROM
return 'radial-gradient(at top left, '+c1.rgb+'25%,'+c2.rgb+'50%,'+c3.rgb+'100%)';

TO
return 'linear-gradient(left, '+c1.rgb+'25%,'+c2.rgb+'50%,'+c3.rgb+'100%) 0 0 100% 0/0 0 5px 0 stretch';

And change function Jquery from background to border, but not working
Could you please tell me where I am doing wrong?
Thanks Advance

A: try this
 return 'radial-gradient(at bottom, '+c1.rgb+'25%,'+c2.rgb+'50%,'+c3.rgb+'100%)';

Here may help you :
Bottom Gradient Border

A: There is a css property called border, it takes as a param the thickness, the type of border and the color of the border
if you want to use a gradient use the css property border-image
<div class="box">

  hey there
</div>

css:
.box{
      width: 250px;
      height: 20px;
      background: transparent;
      border-bottom: 5px solid transparent;
      -moz-border-image: -moz-linear-gradient(left,  rgba(0,0,0,0) 1%, rgba(0,0,0,0.65) 24%, rgba(0,0,0,0.65) 50%, rgba(0,0,0,0.65) 51%, rgba(0,0,0,0.65) 75%, rgba(0,0,0,0) 100%);
      -webkit-border-image: -webkit-linear-gradient(left,  rgba(0,0,0,0) 1%, rgba(0,0,0,0.65) 24%, rgba(0,0,0,0.65) 50%, rgba(0,0,0,0.65) 51%, rgba(0,0,0,0.65) 75%, rgba(0,0,0,0) 100%);
      border-image: linear-gradient(left,  rgba(0,0,0,0) 1%, rgba(0,0,0,0.65) 24%, rgba(0,0,0,0.65) 50%, rgba(0,0,0,0.65) 51%, rgba(0,0,0,0.65) 75%, rgba(0,0,0,0) 100%);
      border-image-slice: 1;
    }

http://jsfiddle.net/agkety8w/
in your case do the following:
the gradient:
 return 'linear-gradient(to left,  '+c1.rgb+' 0%, '+c2.rgb+' 50%, '+c1.rgb+'

the function:
function PPAP() {
    elements = $('li');
    elements.each(function() { $(this).css({"borderImage":random(), "borderImageSlice": "1","borderBottom": "5px solid transparent"}); });
}

https://jsfiddle.net/tdeqvoaa/


text:
Q: PHP search engine for text files with indexing I have some text files inside a directory (and its sub directories). The number of text files will be (50000+) and the directory is outside 'public_html':
text_root_dir
|-- |-- `001
           |-- text0003.txt
           |-- text0004.txt
           |-- text0005.txt
           |-- `001_a
                   |-- text0006.txt
                   |-- text0007.txt
                   |-- text0008.txt
    |-- text0001.txt
    |-- text0002.txt

The text file details are saved in a MySQL table (with the 'art_textfile' storing the text file name and 'art_path' column storing the file path):
CREATE TABLE `stxt_articles` (
  `art_id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `art_title` VARCHAR(127) NOT NULL,
  `art_author`  VARCHAR(255) NOT NULL,
  `art_textfile`  VARCHAR(255) NOT NULL, /* TEXT FILE NAME */
  `art_path` VARCHAR(255) NOT NULL, /* TEXT FILE PATH */
    PRIMARY KEY(`art_id`)
  ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

I am using PHP/MySQL (LAMP) and want to do a string search on the text files (with regular expressions if possible). The methods that will work logically are:

*

*Storing the contents in the MySQL database and perform a search with MySQL query (LIKE 's%')

*Scan the directory by PHP and search within each text file for a search expression.

But with a large dataset of 5000 +files (tend to grow over time), the above options are not practical. It will be too slow to use.
What I am looking for is a PHP/MySQL search idea which creates index for text files and do a search. Pretty much what Lucene does in JAVA. Maybe I can refer it as a lucene alternative in PHP with MySQL.
Thanks for reading this far. Also thanks for your thoughts.

A: Using something like AJAX seems to be pretty fast, I'm sorry if I misunderstood your post. (Code will need tweaks for doing exactly what you want but should be a good starting point)
index.html

<form>
<input type="text" size="30" onkeyup="showResult(this.value)">

</form>

search.php
<?php
//get the q parameter from URL
$files = scandir("FOLDER")
$q=$_GET["q"];

//lookup all links from the xml file if length of q>0
if (strlen($q)>0) {
  $hint="";
  $directory = 'Directory';
  $results_array = array();

  if (is_dir($directory)) {
  if ($handle = opendir($directory)) {
    while(($file = readdir($handle)) !== FALSE) {
      $results_array[] = $file;
    }
    closedir($handle);
  }
}

foreach($results_array as $value) {
  if(str_starts_with($value, $q)){
    echo $value;
  }
}

A: 50000 file opens, alone, would take a long time.  That does not include the time to search the text in each.
Load the data into a MySQL table with ENGINE=InnoDB (not the deprecated MyISAM).  Then you can do very fast queries that are "word oriented" -- this is meeting FULLTEXT's limitation.
You can also do LIKEs (slow) or REGEXPs (even slower).
What I do in such situations is allow the user to use either LIKE syntax or REGEXP syntax or simple word(s).  Add FULLTEXT(txt) (assuming txt contains all the text you need to search).  Then my code goes something like:
If it looks like "word(s)" of at least 3 letters, stick a '+' in front of each word and build MATCH(txt) AGAINST ("+John +Doe" IN BOOLEAN MODE).  In most situations it will be very fast.
Else, if I see %, then I build a LIKE expression and assume the user knows LIKE syntax.
Else, if I assume it is a regexp and go down that path.
It's imperfect, but it covers a lot of bases.
If the users understand that "words" are faster, they will gravitate that way.


text:
Q: UICollectionView Reloading cells backwards I am using a UICollectionView as a square grid layout for a crossword. The user will 'create' the puzzle by first tapping each cell to change the colour, press the 'insert numbers button' then add the numbers for each square and finally press the 'get clues button'. When the 'insert numbers button' is pressed, the cells are reloaded to 'fix' the colour and a textfield for each square's number is unhidden (for white cells only). The problem arises when I reload the cells to make the square's number un-editable, the cells reload in reverse. I.e. if the first cell (index 0) has a number, the last cell is updated (index 63). Pressing the button twice puts the cells in the correct position.
I have printed the indexPath to see which cell has the text and it is always the reverse...
Code:
import UIKit

class gridSetup: UIViewController, UICollectionViewDataSource,
UICollectionViewDelegate {

var setColours: Bool = true
var setNumbers: Bool = false
var numbers: Array = [Int]()
var whiteSquares:Array = [IndexPath]()
var gridSizer: Int?    //value passed in from previous screen

@IBOutlet weak var getCluesButton: UIButton!
@IBOutlet weak var insertNumbersButton: UIButton!
@IBOutlet weak var grid: UICollectionView!

let reuseIdentifier = "cell"

override func viewDidLoad() {
    super.viewDidLoad()
    setColours = true
    setNumbers = false
    getCluesButton.isHidden = true

    self.navigationController?.isNavigationBarHidden = false
    // Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - UICollectionViewDataSource protocol

// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //return (self.gridSizer * self.gridSizer)
    return (self.gridSizer! * self.gridSizer!)
}

// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

    cell.backgroundColor = UIColor.white

    if setColours == true {
        whiteSquares.append(indexPath) //initalise whiteSquares by adding all the squares
        cell.cellGuess.isHidden = true  //hide the letter guesses
        cell.squareNumber.isHidden = true   //hide the sqaure numbers
    }

    //redraw cells to fix the colours

    // if we are on a white cell and are done setting colours
    if setColours == false && whiteSquares.contains(indexPath) == true {
        if setNumbers == true {
            cell.squareNumber.isHidden = false
        }
        else {
            if cell.squareNumber.text != "" {

                print("I have a number inside, Index: ", indexPath.row)

            }
            cell.squareNumber.isUserInteractionEnabled = false
            cell.squareNumber.placeholder = ""
            cell.cellGuess.isHidden = false
            return cell
        }
        }

    // on a black square
    else if setColours == false && whiteSquares.contains(indexPath) == false {
        cell.squareNumber.isHidden = true
        //print("on a black square", indexPath)
        cell.backgroundColor = UIColor.black
        cell.squareNumber.isHidden = true
        cell.cellGuess.isHidden = true
    }
        //initial grid setup
    else {

        cell.backgroundColor = UIColor.white
        cell.layer.borderColor = UIColor.black.cgColor
        cell.squareNumber.isHidden = true
    }

    cell.layer.borderWidth = 1
    cell.layer.cornerRadius = 8
    return cell
}

// MARK: - UICollectionViewDelegate protocol

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    //print("You selected cell #\(indexPath.item)!")

}

// change background color back when user releases touch
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {

    let cell = collectionView.cellForItem(at: indexPath)

    if setColours == true {
        if cell?.backgroundColor == UIColor.black {
            //print("add", indexPath.row)
            cell?.backgroundColor = UIColor.white
            var k: Int = 0
            for i in whiteSquares {

                if indexPath.row < i.row {
                    whiteSquares.insert(indexPath, at: k)
                    break
                }
                else {
                    k += 1
                }
            }

            }
        else {
            //print("remove", indexPath.row)
            cell?.backgroundColor = UIColor.black
            var k: Int = 0
            for i in whiteSquares {

                if indexPath.row == i.row {
                    whiteSquares.remove(at: k)
                }
                else {
                    k += 1
                }
            }

        }
    }
}

@IBAction func getClues(_ sender: Any) {
    setNumbers = false
    grid.reloadData()   //problem comes from/after calling this function
}

@IBAction func insertNumbers(_ sender: Any) {
    setColours = false
    insertNumbersButton.isHidden = true
    setNumbers = true
    getCluesButton.isHidden = false
    grid.reloadData()

}
}
// some layout stuff, (not important)
extension gridSetup: UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let width = collectionView.frame.size.width / (CGFloat(gridSizer! + 1))
    //let width = collectionView.frame.size.width / (CGFloat(gridSizer! + 1))
    let height = width

    return  CGSize(width: width, height: height)
}
}

The '1' should be in the 1st row, second column


text:
Q: Accented characters and regular expression I have this regexp:
(\b)(emozioni|gioia|felicità)(\b)

In a string like the one below:
emozioni emozioniamo felicità felicitàs

it should match the first and the third word. Instead it matches the first and the last. I assume it is because of the accented character. I tried this alternative:
(\b)(emozioni|gioia|felicità\s)(\b)

but it matched "felicità" only if there is an other word after it. So for being specific only if it is in this context:
emozioni emozioniamo felicità felicitàs

and not in this other:
emozioni emozioniamo felicitàs felicità

I've found an article about accented characters in French (so at the beginning of the word) here, i followed the second answer. If anyone knows a better solution it is very welcome.

A: A word boundary \b works only with characters that are in \w character class, i.e [0-9a-zA-Z_], thus you can't put a \b after an accentued character like à.
You can solve the problem in your case using a lookahead:
felicità(?=\s|$)

or shorter:
felicità(?!\S)

(or \W in place of \s as suggested @Sniffer, but you take the risk to match something like :felicitàà)

A: Try the following alternative:
\b(emozioni|gioia|felicità)(?=\W|$)

This will match any of your listed words, as long as any of those words is followed by either a non-word character \W or end-of-string $.
Regex101 Demo


text:
Q: Linq to SQL OrderBy based on selectedvalue from DropDownList I have a list of 10 articles which gets displayed with the following Linq to SQL query in the page load event:
if (!Page.IsPostBack)
        {
            MyDataClassesDataContext db = new MyDataClassesDataContext();

            var pressRelease = from pr in db.PressReleases
                orderby pr.DatePublished ascending
                where pr.Published == true
                select pr;

            int i = 0;

            foreach (var release in pressRelease)
            {
                Literal literal = new Literal();
                literal.Text = "

" +
                               release.Title + "
" + Server.HtmlDecode(release.Content) + "
" +
                               "Read article...

";
                pnlPressReleaases.Controls.Add(literal);
            }
        }

On my web page, I have a dropdownlist with the following values and the autopostback set to true.
<asp:DropDownList ID="ddlPressSortBy" AutoPostBack="True" runat="server" OnSelectedIndexChanged="ddlPressSortBy_SelectedIndexChanged">
                <asp:ListItem Value="pr.DatePublished descending">Date Published Desc</asp:ListItem>
                <asp:ListItem Selected="True" Value="pr.DatePublished ascending">Date Published Asc</asp:ListItem>
                <asp:ListItem Value="pr.Title ascending">Alphabetical</asp:ListItem>
            </asp:DropDownList>

Once I change the value of the dropdownlist, the data returned has no orderby on the corresponding select statement.  Here is my code for the OnSelectIndexChanged event:
protected void ddlPressSortBy_SelectedIndexChanged(object sender, EventArgs e)
    {
        MyDataClassesDataContext db = new MyDataClassesDataContext();

        var pressRelease = from pr in db.PressReleases
            orderby ddlPressSortBy.SelectedValue
            where pr.Published == true
            select pr;

        foreach (var release in pressRelease)
        {
            Literal literal = new Literal();
            literal.Text = "

" +
                           release.Title + "
" + Server.HtmlDecode(release.Content) + "
" + "Read article...

";
            pnlPressReleaases.Controls.Add(literal);
        }
    }

I'm a little unsure why it is not firing with the orderby.
Any help would be greatly appreciated.
Thanks
Rob

A: You cannot do sorting this way:
var pressRelease = from pr in db.PressReleases
        orderby ddlPressSortBy.SelectedValue
        where pr.Published == true
        select pr;

because resulting query would be something like (suppose you selected the first item):
SELECT * FROM PressReleases
WHERE Published = 1
ORDER BY 'pr.DatePublished descending'

ORDER BY clause would be by a fixed value, resulting in default sorting.
Linq OrderBy takes an Expression<Func<T, object>>, that would be something like pr => pr.DatePublishing, if you are using Fluent syntax. Query syntax just hides that in pretty form, but it how it works.
Accordingly to this article, you could create an extension method for IQueryable that allows you to sort using property names:
public static class extensionmethods
{
    public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
    {
        var param = Expression.Parameter(typeof(T), "p");
        var prop = Expression.Property(param, SortField);
        var exp = Expression.Lambda(prop, param);
        string method = Ascending ? "OrderBy" : "OrderByDescending";
        Type[] types = new Type[] { q.ElementType, exp.Body.Type };
        var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
        return q.Provider.CreateQuery<T>(mce);
    }
}

and then use it in your code like this:
var sortingInfo = ddlPressSortBy.SelectedValue.Split(' ');
var sortingProperty = sortingInfo[0];
var descending = sortingInfo[1] == "descending";

var pressRelease = from pr in db.PressReleases
        where pr.Published == true
        select pr;
pressRelease = pressRelease.OrderByField(sortingProperty, descending);
// rest of code


text:
Q: S3: No 'Access-Control-Allow-Origin' for AJAX POST This issue is driving me a little nuts.  I'm trying to upload files via AJAX POST to an S3 bucket.
I have all the credentials correct because when I do normal HTTP POSTs it creates the resource in the S3 bucket just fine.  But I would really like to upload multiple file at once with progress bars, hence I need AJAX.
I have CORS setup on my S3 bucket:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>http://localhost:3000</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

Right now I'm just trying to get it working in my development environment (localhost:3000, using standard Rails 4.1).
From my understanding, the above CORS rule should allow AJAX requests from localhost:3000 to the S3 bucket.
However, every time I submit a file via AJAX, I get the following error:
XMLHttpRequest cannot load https://s3.amazonaws.com/<BUCKET>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

This doesn't make any sense to me because localhost:3000 IS granted access via the CORS rule.
I've also provided a snippet of the JS I used to submit the form:
  $.ajax({
    method: "POST",
    crossDomain: true,
    url: "https://s3.amazonaws.com/<BUCKET>",
    data: $(this).serialize() # Contains S3 necessary values
  })

The form has inputs for the Amazon S3 keys/etc necessary.  I know they work because when I do normal HTTP POSTs it creates the asset properly in S3.  All I'm trying to do is AJAXify the process.
Am I missing something obvious here?
Using: Rails 4.1, jquery-file-upload, fog gem (for S3)

A: you can try by changing
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

A: Your question seems very similar to a problem I had, which was never properly (precisely) answered either and seemed to be an issue related to a browser limitation instead of the actual transfer technology behind it.
Here's a link to my original question and the answers I received here on SO:
Why Doesn't Microsoft Skydrive Download Multiple Files via API?
Hopefully this may offer some insight into your problem and isn't just noise.


text:
Q: Jenkins: Aborting postbuild actions when build is aborted I have a groovy script to cancel a running job (behaves similar to "cancel" in the jenkins gui). I want to abort build in a way that nothing to be executed afterwards.
Using build.doStop() I am able to abort the build steps but aborting the build does not stop executing the post build actions. Is there any way that we can abort the postbuild action as well?
I appreciate any help or suggestions, thanks

A: Maybe it's a late reply, but better ever than never
Try adding a Groovy Postbuild or Execute a set of scripts (and then in Build Steps select Execute System Groovy Script) as a first post build action. You can use either method, stop() or interrupt().
Nevertheless, the build always finishes as failed (couldn't figure out why).
Tested on Jenkins 2.73.1


text:
Q: How do I set up FirePHP version 1.0? I love FirePHP and I've been using it for a while, but they've put out this massive upgrade and I'm completely flummoxed trying to get it to work. I think I'm copying the "Quick Start" code (kind of guessing at whatever changes are necessary for my server configuration), but for some reason, FirePHP's "primary" function, FirePHP::to() isn't doing anything. Can anyone please help me figure out what I'm doing wrong? Thanks.
<?php

define('INSIGHT_IPS', '*');
define('INSIGHT_AUTHKEYS', '290AA9215205F24E5104F48D61B60FFC');
define('INSIGHT_PATHS', __DIR__);
define('INSIGHT_SERVER_PATH', '/doc_root/hello_firephp2.php');

set_include_path(get_include_path . ":/home8/jayharri/php/FirePHP/lib");  // path to FirePHP library

require_once('FirePHP/Init.php');

$inpector = FirePHP::to('page');
var_dump($inspector);
$console = $inspector->console();
$console->log('hello firephp');

?>

Output:
NULL
Fatal error: Call to a member function console() on a non-object in /home8/jayharri/public_html/if/doc_root/hello_firephp2.php on line 14

A: The inspector variable is spelled wrong where you are assigning it and you are missing a bracket when getting the include path.
Try the following:
define('INSIGHT_IPS', '*');
define('INSIGHT_AUTHKEYS', '290AA9215205F24E5104F48D61B60FFC');
define('INSIGHT_PATHS', __DIR__);
define('INSIGHT_SERVER_PATH', '/doc_root/hello_firephp2.php');

set_include_path(get_include_path() . ":/home8/jayharri/php/FirePHP/lib");

require_once('FirePHP/Init.php');

$inspector = FirePHP::to('page');
$console = $inspector->console();
$console->log('hello firephp');

Also, according to the INSIGHT_SERVER_PATH constant make sure you have a script with FirePHP installed at:
http:://<hostname>/doc_root/hello_firephp2.php


text:
Q: PreferenceFragment not saving values - with test case and screenshot I have prepared a simple test case at GitHub for my question and have a feeling, that only few lines of code are missing to make it working.
In an Android app I have 1 activity (MainActivity.java) and 2 fragments (MainFragment.java and PrefFragment.java) - and when I change values in the preferences fragment, they are not saved.
Also the default values are not loaded and the summaries not updated:

Here is my PrefFragment where I register a shared prefs listener - in order to update the summaries - but for some reason it is never called:
public class PrefFragment extends PreferenceFragment
    implements OnSharedPreferenceChangeListener {

    public static final String BOOL_1 = "bool_1";
    public static final String STR_1 = "str_1";
    public static final String STR_2 = "str_2";

    private CheckBoxPreference mBool1;
    private EditTextPreference mStr1;
    private EditTextPreference mStr2;
    private SharedPreferences mPrefs;
    private Editor mEditor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(false);
        addPreferencesFromResource(R.xml.preferences);
        mBool1 = (CheckBoxPreference) findPreference(BOOL_1);
        mStr1 = (EditTextPreference) findPreference(STR_1);
        mStr2 = (EditTextPreference) findPreference(STR_2);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
        mEditor = mPrefs.edit();
        mPrefs.registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mPrefs.unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences prefs,
                                          String key) {
        Log.d("onSharedPreferenceChanged", key); // XXX is never called

        if (BOOL_1.equals(key)) {
            boolean bool1 = prefs.getBoolean(key, false);
            mBool1.setSummary(bool1 ? "Enabled" : "Disabled");
        } else if (STR_1.equals(key)) {
            String str1 = prefs.getString(key, "");
            mStr1.setSummary(str1);
        } else if (STR_2.equals(key)) {
            String str2 = prefs.getString(key, "");
            mStr2.setSummary(str2);
        }
    }
}

And here is preference.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory
        android:title="Category 1"
        android:key="category_1">

        <CheckBoxPreference
            android:key="bool_1"
            android:title="Boolean 1"
            android:summary="XXX how to set this? XXX"
            android:defaultValue="false" />
        <EditTextPreference
            android:dependency="bool_1"
            android:key="str_1"
            android:title="String 1"
            android:summary="XXX how to set this? XXX"
            android:defaultValue="change me" />
        <EditTextPreference
            android:dependency="bool_1"
            android:key="str_2"
            android:title="String 2"
            android:summary="XXX how to set this? XXX"
            android:defaultValue="change me too" />
        </PreferenceCategory>

</PreferenceScreen>

So my question is how to handle (load, save) values in PreferenceFragment? Do I really have to extend EditTextPreference and implement onDialogClosed method in my custom class? This seems like an overkill approach to me.

A: Ok, the following seems to work in PrefFragment.java:
@Override
public void onResume() {
    super.onResume();

    SharedPreferences prefs = getPreferenceManager().getSharedPreferences();

    // CHANGE 1: load saved values to set the summaries
    onSharedPreferenceChanged(prefs, BOOL_1);
    onSharedPreferenceChanged(prefs, STR_1);
    onSharedPreferenceChanged(prefs, STR_2);

    // CHANGE 2: register shared prefs listener in onResume
    prefs.registerOnSharedPreferenceChangeListener(this);
}

@Override
public void onPause() {
    super.onPause();
    SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
    prefs.unregisterOnSharedPreferenceChangeListener(this);
}


text:
Q: Mathematical notation in algorithms I am currently reading the Algorithm Design Manual, but my mathematical notation has become a little rusty.
What does

mean?

A: Combination is the first thing that comes to mind...but without context, there are probably other meanings for the same notation.

A: Combination.

A: Binomial coefficient? (also, see combination)

A: It means "n choose k", or in this case, "a choose b". It is a shorthand for the formula a!/(b!((a-b)!)).
Sorry for the many parenthesis, just didn't want amibuity. ! means factorial, 5! = 5*4*3*2*1, etc.
It is used for binomial expansion, and Pascal's Triangle.


text:
Q: How to display json data into datatable and in tabs? I am trying to display json data into php.
Can you tell me how can I sort this into a datatable also with tabs?
as  I am going to Display this into each tab as well Like Bitcoin List with Icon and text and  ETH list with icon and Text etc
so they can pick what ever coin they like then it shows them the faucet list  for that coin
So i need This for each Tab with Datatable
Also yes I looked Google why I would not be posting here
faucetlist.json

[{"name": "Bitcoin",
  "shorthand": "BTC",
  "faucets": [
        {"faucet name":"gr8 Faucet",
        "minutes": "5",
        "reward": "~3000",
        "claim": "http://namefaucet.net"},
        //Next Faucet here
   ]
   },

  {"name": "ETHcoin",
  "shorthand": "ETH",
  "faucets": [
        {"faucetname":"eth Faucet",
        "minutes": "5",
        "reward": "~10000",
        "claim": "http://ethwebsite.com"},
    ]
 }
]

datatable

                faucet name
                Minutes
                reward
                Claim

        test
        test
        test
        test

also javascript here

A: It looks like you did not define your columns or your data.
Assign your JSON to a variable:
var data = {
..faucetlist JSON here
}

Example borrowed from: https://datatables.net/manual/data/
$('#faucetlist').DataTable( {
    data: data,
    columns: [
        { data: 'column-1' },
        { data: 'column-2' },
        { data: 'column-3' },
        { data: 'column-4' }
    ]
} );

I purposefully did not fill out the column names.


text:
Q: Pass cookie back to the server I am writing a single-page application with CanJS. For one of models, every time I save a new item, the application sends the normal POST request. However, there is a specific cookie that is returned in the HTTP response that I would like to send back to the server on GET requests when fetching an item.

A: All cookies specific to an application are passed automatically to server in request header. Make sure that the cookie which you want to send is of the same application.
This you can check by looking into the cookies of your browser. Make sure that the cookie which you want to send has Domain as your application name. Like all stackoverflow cookie will have domain value as .stackoverflow.com
You can refer to this tutorial which talks about creation and setting of cookie in JavaScript : http://www.w3schools.com/js/js_cookies.asp


text:
Q: Hibernate sending superfluous queries to the database I have an odd problem where Hibernate is running more queries than I've asked for, and can't see the need for.
Here is my controller:
@Autowired UserService users;

@RequestMapping("/test")
@ResponseBody
public String test() {
    User user = users.findUser(1L);
    return "Found user: "+user.getEmail();
}

Here is the UserService:
@Component
public class UserService {

    @javax.persistence.PersistenceUnit private EntityManagerFactory emf;

    private JpaTemplate getJpaTemplate() {
        return new JpaTemplate(emf);
    }

    public User findUser(long id) {
        long start = System.currentTimeMillis();
        JpaTemplate jpaTemplate = getJpaTemplate();
        User user = jpaTemplate.find(User.class, id);
        System.out.println(System.currentTimeMillis() - start);
        return user;
    }
}

The call to findUser() takes about 140ms... Rather baffling. The database performs just fine for other queries, including this one in some handlers (I suspect when it is not the first query run).
JProfiler suggests that every time it is called, four queries are sent to the database (not necessarily in this order):

1) [5ms] select user... (the actual query)

2) [7ms] SHOW COLLATION

3) [14ms] /* mysql-connector-java-5.1.7 ( Revision: ${svn.Revision} ) */SELECT @@session.auto_increment_increment

4) [70ms] /* mysql-connector-java-5.1.7 ( Revision: ${svn.Revision} ) */SHOW VARIABLES WHERE Variable_name ='language' OR Variable_name = 'net_write_timeout' OR Variable_name = 'interactive_timeout' OR Variable_name = 'wait_timeout' OR Variable_name = 'character_set_client' OR Variable_name = 'character_set_connection' OR Variable_name = 'character_set' OR Variable_name = 'character_set_server' OR Variable_name = 'tx_isolation' OR Variable_name = 'transaction_isolation' OR Variable_name = 'character_set_results' OR Variable_name = 'timezone' OR Variable_name = 'time_zone' OR Variable_name = 'system_time_zone' OR Variable_name = 'lower_case_table_names' OR Variable_name = 'max_allowed_packet' OR Variable_name = 'net_buffer_length' OR Variable_name = 'sql_mode' OR Variable_name = 'query_cache_type' OR Variable_name = 'query_cache_size' OR Variable_name = 'init_connect'

Its clear that the actual query takes no time at all, and most of the time is spend in that fourth one. What can I do about this? It doesn't show up in the hibernate log output, only the first, actual query does. Incidentally, all the time is spent after the call to getJpaTemplate() - i.e actually in the jpa.find() method.
Any ideas?
UPDATE: I've worked out that it is hibernate doing some sort of initial connection to the database multiple times, since somebody else posted the same set of queries (http://ondra.zizka.cz/stranky/programovani/java/hibernate_netbeans_howto_tutorial.texy). Why would hibernate make its initial connection repeatedly, isn't it using a connection pool - how can I check?

A: I've solved it. I had a non-pooled datasource:
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

From the Javadoc at: http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/jdbc/datasource/DriverManagerDataSource.html

Simple implementation of the standard JDBC DataSource interface, configuring the plain old JDBC DriverManager via bean properties, and returning a new Connection from every getConnection call.
  NOTE: This class is not an actual connection pool; it does not actually pool Connections. It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface, but creating new Connections on every call.

So I've now replaced this with:
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql://server.domain/database"/>
    <property name="user" value="theUsername"/>
    <property name="password" value="thePassword"/>
</bean>

I had to throw in c3p0-0.9.1.2.jar too, since it uses that connection pool.


text:
Q: TestDisk image vs ddrescue for recovering data from a defective hard drive I am trying to duplicate a "defective" hard drive (making strange noises after it fell on the floor).
After some research, I discovered TestDisk and the "Image Creation" tool to clone the disk. I successfully managed to make an image from the drive.
Nevertheless, it annoys me they don't mention their own solution in the "Damaged Hard Disk" section of their website they advise to use ddrescue.
I understand that I need to use tools especially created for damaged drive, in order to protect it.
What are the differences between the two tools (TestDisk image creation tool and ddrescue)? ddrescue more appropriate in my case?

A: This can all seem confusing, but the best way to understand it is this: One tool is designed to deal with logical level issues and the other is designed to deal with block level issues.

*

*Logical Level: TestDisk is designed to deal with logical-level partition issues

*Block Level: DDRescue is designed to go deeper on the disk, past the partition layer, to recover data on a raw block level.

Here is how each tool describes itself from it's own homepage:

*

*TestDisk: "TestDisk is powerful free data recovery software! It was primarily designed to help recover lost partitions and/or make non-booting disks bootable again when these symptoms are caused by faulty software: certain types of viruses or human error (such as accidentally deleting a Partition Table). Partition table recovery using TestDisk is really easy."

*DDRescue: "GNU ddrescue is a data recovery tool. It copies data from one file or block device (hard disc, cdrom, etc) to another, trying hard to rescue data in case of read errors."
Which tool is "best" or most appropriate in your case where your drive has fallen on the floor and now makes odd noise? My guess would be DDRescue would be your best bet. Your are not dealing with a logical disk issue but rather a physical failure and DDRescue is designed to work around physical issues that might make other data recovery packages choke and die.


text:
Q: Fine-tuning HTML5 Phonegap app Have managed to build an HTML5 application. following libraries have used for that:

*

*jquery.mobile-1.1.1.min.js

*jquery.mobile-1.1.1.min

*lawnchair.js

Every thing works fine Wrapped it with Phonegap cordova-2.0.0
But have noticed the application is very slow.
My application actually does ajax request gets Json and loads the UI (Mostly listviews)
Are there any performance improving techniques to make my application work faster?
Also any Tools to test the same?
Targeting Platforms : Android and iOS .
EDIT:
one thing have noticed is cache size of the application is increasing on every click and page transition (times it reaches in MB's).. though have disabled ajax cache.. do i need to take care of someother things?

A: You Can increase speed of app by:
1. Using minified versions of js which you have included in you project.
2. Avoid using images with bigger size. tune them with web compatible PNG files
Optimize Images
Use CSS Sprite Sheets

   .icon {
      width: 14px; height: 14px;
      background-image: url("glyphicons-halflings.png");
    }
    .icon-glass {
      background-position: 0 0;
    }
    .icon-music {
      background-position: -24px 0;
    }
    .icon-search {
      background-position: -48px 0;
    }

Use the right image size (don't scale images in HTML)
Host images on scalable, distributed systems (i.e. S3)
Avoid 404s for images

3. Avoid using much of CSS.Limit Shadows and Gradients link box-shadow,border-radius,gradients,text-align
Try disabling some of the CSS that slows it down(Simon MacDonald's idea). In your jquery mobile .css file add this to the bottom:
* {
text-shadow: none !important;
-webkit-box-shadow: none !important;
-webkit-border-radius:0 !important;
-webkit-border-top-left-radius:0 !important;
-webkit-border-bottom-left-radius:0 !important;
-webkit-border-bottom-right-radius:0 !important;
-webkit-border-top-right-radius:0 !important;
}

4. Use CSS Transitions + Hardware Acceleration Use Native Scrolling
5. If you are using any Live url to get JS better download them and use locally.
6. FastClick FastClick is a simple, easy-to-use library for eliminating the 300ms delay between a physical tap and the firing of a click event on mobile browsers.(jjsquared's idea)
7. use Slpash screen.
8. Avoid using framework use only if necessary. Try to make responsive design.
9. Don't generate the UI on the server.Create the UI in JavaScript at the client-side
10. Minimize Reflows

*

*Reduce the number of DOM elements.

*Minimize access to the DOM Update    elements "offline" before
reinserting into DOM.

*Avoid tweaking    layout in JavaScript

slow
$("#header a.back").on("click", clickHandler);
$("#header a.back").css("color", "white");
$("#header a.back").css("text-decoration", "none");
$("#header a.back").attr("href", "#");

Fast
var $backButton = $("#header a.back");
$backButton.on("click", clickHandler);
$backButton.css("color", "white");
$backButton.css("text-decoration", "none");
$backButton.attr("href", "#");

11. Avoid Network Access
Dont make network dependend apps for getting content
$.ajax({url: "services/states"}).done(function(data) {
    states = data;
});

use Cache Static Data LocalStorage, Database & File
slow
$.ajax({url: "slow/feed"}).done(function(data) {

});

fast
dataAdapter.getItems().done(function(data) {

});

12. Don't wait for the data to display the UI
// Display view
displayView();

// Get data
$.ajax({url: "product/101"}).done(function(product) {
    // Update view
});

A: If you want to make it more performant on Android you should disable some of the CSS:
https://stackoverflow.com/a/12081339/41679

A: There is a mechanism called pre-fetch, it loads the page before you click it. So that redirection is faster. But you are using more transfer.
It is used like this:
 ...

Check this site:
http://jquerymobile.com/test/docs/pages/page-cache.html

A: To increase click performance and to avoid the 300ms browser delay that's natively built into mobile browsers, you should use a library such as FastClick.  This will drastically reduce the lag in between mobile.changePage calls.
https://github.com/ftlabs/fastclick


text:
Q: Restarting and resetting variables mid script python I am currently making a minesweeper bot and when it detects that a game is done I would like it to restart the script and reset all the variables so it can restart completely the same as if I were to ctrl c then restart except inside of the script. (on a mac)
TLDR:
completely restart script mid script
Example:
    def restart(self):
        if locateOnScreen('images/finish/gamefinish.png', grayscale = True) != None:
            click('images/finish/gamefinish.png')
            **CODE TO RESTART HERE**
        else:
            pass

A: The answer to this is
os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)

credit: @SangminKim (and @DavidCamp for suggesting)
https://stackoverflow.com/a/48130152/19079252


text:
Q: Favorite non-constructive proofs. There are many results for which a constructive proof exists but is not as nice as the non-constructive proof. For example the explicit construction of a continuous nowhere-differentiable function is rather technical compared to the proof of existence invoking the Baire category theorem.
What are your favorite non-constructive proofs or methods?

A: I have always liked:
Claim:  There exist  irrational numbers $\alpha,\beta$, possibly equal, such that $\alpha^{\beta}$ is rational.
Pf:   Consider $\sqrt 2 ^{\sqrt 2}$.  If it is rational then we are done.  If it is irrational, then call it $\alpha$ and consider $\alpha^{\sqrt 2}=2$.  And we are done.

A: Strategy Stealing is another classic example that applies to a number of turn-based games. It shows that either the first player always wins or that the game will end in a tie, assuming perfect play from both sides. The proofs never actually exhibit the strategies in question.
For example take Tic Tac Toe (on an arbitrarily large board of size $n\times n$). Suppose player 2  has a winning strategy $S$, regardless of player 1's first move. Then we make a number of observations:
1) Regardless of where player 1 plays the first $X$, player 2 supposidly has a winning strategy, which is a function of the position of the first $X$.
2) There is never a disadvantage to having one of your pieces already on the board, meaning that if player 1 already has an $X$ on a given square, then that cannot the worse than not having an $X$ on that square.
3) By 1), player 1 can adopt player 2's strategy by randomly placing an $X$, and then after player 2 responds with their strategy $S$, player 1 applies $S$ to player 2's response, with $X$ and $O$ switched. If $S$ ever calls to play on the first $X$ that player 1 had to place, then player 1 can make a random move by 2).
So player 2 could not possibly have a winning strategy $S$, which means either player 1 always wins or the game always ends in a tie.

A: Shout out for Brouwer's Fixed Point theorem, if only because Brouwer's other major claim to fame is being such a strict constructivist.


text:
Q: Get a sibling div with specific class and is not disable I want to find a div with a class associated with it, but it must not be disabled.
I am using following code for getting the next sibling, but it will return the next element with the "menuDiv" class.
var nextDiv=jQuery('div.subMenuBarhover').nextAll('.menuDiv:first');

but now I need the element which is not disable and id of all element is unkown.
How can I achieve this?

A: You said you are using a custom attribute to mark a div as disabled. I would recommend to always use data-* attributes for custom attributes, i.e.
<div data-disabled="true">

To select the next div without that attribute, use the negation pseudo class (aka :not selector) and the attribute selector:
jQuery('div.subMenuBarhover').nextAll('.menuDiv:not([data-disabled]):first');

If you want to find the next element where the data-disabled attribute has a certain value, use the attribute-equals selector:
jQuery('div.subMenuBarhover').nextAll('.menuDiv[data-disabled=false):first');

In general, have a look at all the existing selectors have try them out!

A: Try adding .not(':disabled') to your code as required.
not
disabled selector


text:
Q: Atomic Updates in Solr - multiple shards We are currently working on atomic update feature in solr using solrJ. Will solr update the record correctly if it is distributed across shards?
If the record is in shard2, will it be updated or it will create new record in shard1?

A: If you're handling the sharding yourself, you'll have to update the exact shard in question (as you're the one responsible for distributing documents).
If you're using Solr in SolrCloud mode, Solr will route the document to the correct shard for you, based on the document routing strategy.


text:
Q: ServiceStack.Ormlite Postgres case insensitive queries I am looking to cleanly implement a mechanism to override all where clauses that compare strings to do the following
[Column].Value.ToLower() == SqlParam.ToLower()
effectively overcoming the case sensitivity of Postgres.

A: OrmLite's INamingStrategy allows you to customize how Schemas, Tables and Columns are named and OrmLite's PostgreSQL Provider is already configured to use the PostgreSqlNamingStrategy which converts or .NET's PascalCase names to PostgreSQL-friendly snake_case.


text:
Q: Undefined control sequence error when using gtsummary package to publish table in pdf I try publishing a table in a pdf format using the gtsummary package in Rmarkdown. The code in Rmarkdown is as below:
---
title: "test"
author: "Tengku Hanis"
date: "`r Sys.Date()`"
output: pdf_document
---

```{r pressure, echo=FALSE}
mod <- lm(mpg ~ ., data = mtcars)
summary(mod)

```

```{r message=FALSE, error=FALSE, warning=FALSE}
library(tidyverse)
library(gtsummary)
```

```{r}
tbl_regression(mod, intercept = TRUE) %>% as_gt()
```

When I try to knit, I get the following error:
! Undefined control sequence.
<argument> ...al \expandafter \let \cmrsideswitch
                                                  \@tempa \fi \fi
l.164 (Intercept)
                  & 12 & -27, 51 & 0.5 \\

Error: LaTeX failed to compile test.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See test.log for more info.
Execution halted

Is there any way to publish a table using tbl_regression() in pdf format while setting the intercept = TRUE? I think this argument somehow in conflict with as_gt()?


text:
Q: Deserializing no array json object to dictionary in c# I am trying to deserilaize json to a c# class. I am not sure how I can get the ErrorContent into Dictionary of key value pair? Since Error Content is not an array, can I still convert it to Dictionary?
When I try below code, I keep getting ErrorContent as null..
    var response = JsonConvert.DeserializeObject<SearchResponse>(jsonResponse);

The class Search Response looks like
public class SearchResponse
{
    public ErrorContent Errors { get; set; }
}

public class ErrorContent
{
    public Dictionary<int, string> Errors { get; set; } = new Dictionary<int, string>();
}

Sample json looks like
    {
    "statusCode": 1233,   "status": "ERROR",   "payloadType": "ERROR", "payload": {
    "ErrorContent":{
       "101": "Value cannot be null",
       "102": "Value should always be integer"
    }}}

A: Change your model like this. Your JSON and C# model are not correctly binding due to wrong models
  public class SearchResponse
    {
        [JsonProperty("payload")]
        public PayLoad PayLoad { get; set; }
    }

    public class PayLoad
    {
        public Dictionary<int, string> ErrorContent { get; set; }

    }

Binding Steps

*

*First your model will look for SearchResponse  class

*Then it will look for a class named payload

*Then it will look for a dictionary with name ErrorContent


text:
Q: Reduce the Appbar Button Size in Bottom appbar In windows Universal app For the Mobile View I am working on the project of  windows universal platform(UWP).In this Project I have a issued regarding to the bottom Appbar.
I designed a bottom Appbar and add a 7 Appbar Button.which is displayed Properly in desktop and tabulate view, but in mobile view its not properly displayed. I captured a bottom Appbar photo of the both Mobile and Desktop view.
so kindly give a solution for mobile view how i manage all 7 appbar button?
how to reduce appbar button size ? so it will display proper in mobile view.
Code:
<Page.BottomAppBar>
    <AppBar x:Name="applicationbar" Background="#FFE45427">
        <StackPanel x:Name="bottombar"   Orientation="Horizontal" HorizontalAlignment="Center">

            <AppBarButton Label="HOME" x:Name="appbarhome" Click="appbarhome_Click">
                <AppBarButton.Icon>
                    <BitmapIcon UriSource="Images/DashboardImages/product-default-small.png" />
                </AppBarButton.Icon>
            </AppBarButton>

            <AppBarButton Label="Sales" x:Name="appbarsales" Click="appbarsales_Click">
                <AppBarButton.Icon>
                    <BitmapIcon UriSource="Images/DashboardImages/menu_sales.png"/>
                </AppBarButton.Icon>
            </AppBarButton>
            <AppBarButton Label="Product" x:Name="appbarproduct" Click="appbarproduct_Click">
                <AppBarButton.Icon>
                    <BitmapIcon UriSource="Images/DashboardImages/menu_product.png" />
                </AppBarButton.Icon>
            </AppBarButton>

            <AppBarButton Label="POS" x:Name="appbarpos" Click="appbarpos_Click">
                <AppBarButton.Icon>
                    <BitmapIcon UriSource="Images/DashboardImages/menu_pos.png"/>
                </AppBarButton.Icon>
            </AppBarButton>

            <AppBarButton Label="Customer" x:Name="customer" Click="customer_Click">
                <AppBarButton.Icon>
                    <BitmapIcon UriSource="Images/DashboardImages/menu_customers.png"/>
                </AppBarButton.Icon>
            </AppBarButton>

            <AppBarButton Label="About US" x:Name="aboutUs" Click="aboutUs_Click">
                <AppBarButton.Icon>
                    <BitmapIcon UriSource="Images/DashboardImages/menu_aboutus.png"/>
                </AppBarButton.Icon>
            </AppBarButton>
            <AppBarButton Label="Logout" x:Name="mobile_logout_commandbar" Click="mobile_logout_commandbar_Click">
                <AppBarButton.Icon>
                    <BitmapIcon UriSource="Images/DashboardImages/menu_logout.png"/>
                </AppBarButton.Icon>

            </AppBarButton>

        </StackPanel>

    </AppBar>

</Page.BottomAppBar>

Image:

A: I would recommend change in design. If thats not an option go for horizontal scrollviewer that contains all your appbar buttons.

A: We can provide Minheight and MaxHeight to reduce button size but it will not look better in Mobile view so we need to use Menuflylaouts.
Code:
<AppBarButton Icon="OpenWith" Label="More.."  x:Name="more_item">
                    <AppBarButton.Flyout>
                        <MenuFlyout>
                            <MenuFlyout.MenuFlyoutPresenterStyle>
                                <Style TargetType="MenuFlyoutPresenter">
                                    <Setter Property="Margin" Value="0,-31,0,0" />
                                    <Setter Property="Background" Value="#FFE45427" />
                                    <Setter Property="FontSize" Value="12" />
                                    <Setter Property="BorderBrush" Value="Transparent" />
                                    <Setter Property="MaxWidth" Value="70"/>
                                </Style>
                            </MenuFlyout.MenuFlyoutPresenterStyle>
                            <MenuFlyoutItem Text="Logout" FontSize="13" Padding="8,8,0,8"   Click="logout_Click" />
                            <MenuFlyoutItem Text="About Us" FontSize="13" Padding="8,8,0,8"  Click="aboutus_click" />
                        </MenuFlyout>
                    </AppBarButton.Flyout>
                </AppBarButton>

and this way we can easily add muliple button in app bar and it will look better in mobile view.


text:
Q: ImportError: No module named subprocess it is quite a long time now, that on my installation of python 2.7 on ubuntu 12.10 the subprocess module is missing, I do not need to use it, but many programs I use do it, then they do not work any more, googling quite a lot, I realized that in my installation there is something that is in conflict, but I have not been able to understand what. I have other version of python installed, but I can't  remove them with synaptic, because with I would have to remove too many other packages.

A: Using dpkg you can find to which package subprocess.py belonged:
dpkg -S /usr/lib/python2.7/subprocess.py

Then use the --reinstall option to get the package python2.7-minimal back without breaking dependencies:
apt-get install --reinstall python2.7-minimal