text:
Q: How to align an input box with an image in a Next.js app I want to horizontally align the input box with the image on the right along their centers, but the input box is always offset downwards. These elements are in a navigation bar.
I have tried applying CSS properties to the .leftel class, including vertical align: center; and   changing the line-height. However, the output has remained unaffected. I have also tried modifying the padding, border, and margin for input.
This is how it appears: navigation bar image
In the navigation bar component,

  <Link href="/">
    <Image src="/logo.png" width={78} height={35}/>
  </Link>
  <input className="searchBar" placeholder="Search here..."/>

This is the CSS for each of the classes:
.leftel{
  float: left;
}

.leftel Image, .leftel input{
  vertical-align: middle;
}

.searchBar {
  margin-left: 10px;
  padding: 7px;
  border-radius: 30px;
  border: none;
  width: 600px;
  height: 20px;
  font-size: 16px;
  text-align: flex-end;
  background-color: #3A4466;
  font-family: "Nunito";
}


text:
Q: You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors. when called using $.getScript() Prelog:
I have implemented Google maps and Geolocation as a independent widgets, Now the user have the ability to add the widget as much as he wants in a page he is owns.
I am using $.getScript(URl, callback) to load the script for that URL to work.
Problem :
When the user add both the widgets or the same widget multiple times in a same page , the check windows.google fails and the $.getScript(url, callback) gets executed twice. Due to which I get an error from the Google Script

You have included the Google Maps JavaScript API multiple times on
  this page. This may cause unexpected errors. when called using
  $.getScript()

if(window.google !== undefined && window.google !== null) {
    onScriptLoad(null, null, 200);
} else {
    $.getScript(googleUrl, onScriptLoad);
}

The above line exists in both the widget and both the widgets are independent of each other. It always goes into the else block of both the functions.
Looking forward for some work around here, like to load the script synchronously using javascript or jquery

A: when your code runs in the first widget, it initiates the loading of the google API, however window.google isn't created until the script completes loading. This is asynchronous
Now, the second widget tests if window.google exists, but this is still happening before the google API loads, therefore, it too thinks it needs to load google API
so, instead of this:
if(window.google !== undefined && window.google !== null) {
    onScriptLoad(null, null, 200);
} else {
    $.getScript(googleUrl, onScriptLoad);
}

try
window.loadingGoogleApi = window.loadingGoogleApi || $.getScript(googleUrl);
window.loadingGoogleApi.then(onScriptLoad);

the loadingGoogleApi can be any name you choose (just don't use something that will be clobbered by other code)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't suggest an edit for specific question I found this question, and it has horrid spelling/grammar/formatting that I'd like to correct. Usually I find an Edit link under a question so I can suggest a revision to it. In this case, it's missing, as pictured here:

Why can't I suggest an edit for this question?

A: There was already a suggested edit for the question. Now that it has been approved, the edit link should reappear.


text:
Q: ValueError: too many values to unpack (expected 2) on a simple Python function I'm coding this password manager program and keep getting this error message when I use the view function:
    File "c:\Users\user\Desktop\password_manager.py", line 7, in view
    user, passw = data.split("|")
ValueError: too many values to unpack (expected 2)

This is the program so far:
master_pwd = input("What is the master password?")

def view():
    with open("passwords.txt", "r") as f:
        for line in f.readlines():
            data = line.rstrip()
            user, passw = data.split("|")
            print("User:", user, "Password:", passw)

def add():
    name = input("Account name: ")
    pwd = input("Password: ")

    with open("passwords.txt", "a") as f:
        f.write(name + "|" + pwd + "\n")

while True:
    mode = input("Would you like to add a new password or view existing ones (view, add)? Press q to quit. ").lower()
    if mode == "q":
        break
    if mode == "view":
        view()
    elif mode == "add":
        add()
    else:
        print("Invalid mode.")
        continue

I tried using the .split() method to one variable at a time but it also resulted in the error.
I thought the problem could be caused by the comma in  user, passw = data.split("|") being deprecated, but I failed to find an alternative.

A: The .split() function is returning more than 2 values in a list and therefore cannot be unpacked into only 2 variables. Maybe you have a password or username with a | in it which would cause that.
I suggest to simply print(data.split('|')) for a visual of what is happening. It will probably print out a list with more than two values.

A: Check your password file to be sure there aren't  "|" characters in a username or password that are creating additional splits.
If your data is good, you could catch the remaining elements in a list:
user, passw, *other = data.split("|")


text:
Q: IQueryable неправильно трактует Linq запрос в MongoDB Есть бд с товарами, делаю вот такое linq query:
//норм, вернуло все товары в бд.
var queryable = Repository.GetQueryable();

//норм, вернулись только активные
queryable = queryable.Where(x => x.IsActive == true);

//норм, вернулись только с categoryId = 1234
queryable = queryable.Where(x => x.Category.CategoryId = "1234");

//не норм, возвращает даже те, которые меньше чем minPrice.
queryable = queryable.Where(x => x.Price >= minPrice && x.Price <= maxPrice);

Что делать? Как правильно запрос на LINQ составить? IQueryable возвращает вот такой запрос в mongo:
{aggregate([{ $match : { IsActive : true } }, { $match : { "Price" : { $gte : "10000", $lte : "60000" } } }])}

Пытался его в mongoDb Compass вставить, он работает неправильно, возвращает товары с неправильной ценой.


text:
Q: TwitPic image upload  I want to implement TwitPic image uploads (in PHP) using OAuth.
In that the flow is like

*

*login amd allow or deny (application)

*then return image upload

That image upload is used for all the users.
Is there any code or link to help full to me?
Is there any link to guide me?

A: You can find the documentation here.
If you are not comfortable with using their API then you could use one of the following libraries.
PHP
TwitPic API for PHP - created by @meltingice
Services_TwitPic - created by Bill Shupp
Javascript
TwitPic API for JavaScript - by @meltingice
And you need to register for an API Key for making request.


text:
Q: Is there a generalized Birkhoff ergodic theorem? Is there a Birkhoff ergodic theorem for two measure preserving transformations $T$ and $S$ where $S\circ T= T \circ S$ so that $\frac{1}{n+1}\frac{1}{m+1}\sum_{i=0}^{n}\sum_{j=0}^{m}f \circ T^{i}\circ S^{j} \to E(f|C)$ for $\mu$-a.e. points where $C$ is $\sigma$-algebra of $S,T$-invariant sets and $E(f|C)$ is conditional expectation of $f$ with the respect to the $\sigma$-algebra $C$?

A: The classical Birkhoff ergodic theorem considers a map $T$ acting on a probability space $(X,\mathcal{F},\mu)$. This could alternatively be thought of as an action of $\mathbb{N}$ on $(X,\mathcal{F},\mu)$ by the transformations $T,T^2,T^3,\ldots,T^n,$ et cetera, where $n \in \mathbb{N}$ is identified with the transformation $T^n$. Since at least the 1960s there has been a general effort to extend the Birkhoff theorem to more general groups and semigroups of transformations. A recent high point of this program was a version of the pointwise ergodic theorem due to Lindenstrauss which treats amenable groups of measure-preserving transformations acting on $(X,\mathcal{F},\mu)$. The literature for semigroups of transformations as opposed to groups (since you did not mention whether $T$ and $S$ are invertible) is slightly more sparse but seems to be adequate for your purposes.
In your case, since the transformations commute, you are considering the action of $\mathbb{N}^2$ on $(X,\mathcal{F},\mu)$ given by $(i,j)\mapsto T^iS^j$. For this purpose you could use the results of Bewley ("Extension of the Birkhoff and von Neumann ergodic theorems to semigroup actions",  Ann. Inst. H. Poincaré Sect. B (N.S.) 7 (1971), 283–291) with $G=\mathbb{N}^2$, $\gamma$ being counting measure, and $A_n$ being some sort of rectangle in $\mathbb{N}^2$ containing $(1,1)$. Note that you must be precise about the manner in which $n$ and $m$ separately tend to infinity: to apply Bewley's theorem I think it is sufficient to assume that $n/m$ is bounded away from zero and infinity.


text:
Q: Wordpress calculator form without resubmit and using custom field value I am currently trying to solve a problem on my Wordpress website. I do not have any code just yet (as I have re-written 4 different forms before I gave up), so I will just state what I want to do, I am pretty sure it's quite simple and I'm just missing something.
I need to build a form on the front-end that works like this: user inputs some value, chooses some other value from dropdown, than clicks on the submit button, page does NOT reload, instead a value is calculated and shown (I know how to show a value after click using jQuery), BUT the value that will be shown is calculated using not only form inputs and hardcoded variables, but also Wordpress custom field values using PHP function get_field().
The problem is that if I use ajax to get values from the form without reloading the page, those values are in javascript and I need to use them with PHP get_field() function.
So, to repeat what I intend to do, so It's easier to understand more quickly:

*

*Form where user inputs some values

*User clicks submit

*The page does not reload

*New value is calculated based on user input and custom field value (using get_field())

*New DIV is shown using JQuery on submit click (I know how to do this one, but its important because this is the reason why the page must not be reloaded).

If you could just point me in the right direction, I will be able to code everything else.

A: Why not just inject the custom fields inside javascript variables when building the page template in php? Then you would have all the data available in javascript when the page loads. Something like this:
<?php

    echo '
        <script type="text/javascript">

            var custom_field_1 = '.json_encode(get_field('custom_field_1')).';
            var custom_field_2 = '.json_encode(get_field('custom_field_2')).';

        </script>
    ';

?>


text:
Q: SoapUI Pro 3.0.1 SocketTimeOut Exception:ReadTimeout I am using SOAP UI Pro and when accessing any of the exposed methods in the services it always gives me SocketTimeOut Exception:ReadTimeout
Any idea???

A: I had the same problem until I changed the endpoint binding from "wsHttpBinding" to "basicHttpBinding" in the config file. "wsHttpBinding" incorporates a lot of the newer web services standards, which means that older clients may have trouble using this binding. "basicHttpBinding" works a lot like the older asmx web services. Here is a good link describing the differences: http://www.codeproject.com/KB/WCF/HttpBinding.aspx


text:
Q: make hit Enter key same as onclick="function()" **Page <input type="text" id="page#" value={{Page_id}} style="width:50px; display:inline-block" > out of {{total}}
<input type="button" class="btn btn-outline-success" onclick="getDirection()" value="Go" style="display:inline">
<script>
   function getDirection(){
   var input = document.getElementById("page#").value;
   var new_id ="http://159.203.172.178/page/{{current_page.id_tei}}" ;
   new_id = new_id.slice(0,-3);
   new_id = new_id+input;
   console.log(new_id);
   window.location=new_id;
   }

**
Hello, I am new to javascript. I am trying to make my django application take input from users and turn to the page based on their input. Right now, it works when I click on the button "Go". Is there a way I can make it work when I hit Enter key as well? I tried to use EventListener, but it tells me EvetListener is not a function. Great thanks.

A: You can make it a form and have the function be called 'onSubmit'.


text:
Q: calling self test case does not increment the number of tests passed? Suppose I have a unittest like this
class TestABC(unittest.TestCase):
  def setUp(self):
    ....

  def test001_abc(self):
    ....

  def test002_abc(self):
    ....

  def test003_bac(self):
    ....
    self.test001_abc()

But the output shows Run 3 tests in 10.962s. I believe that the last self.test001_bac() had been ran, but can we indicate this in the test count?
Thanks.

A: The last "test" was run as part of test_003_bac, so unittest does not see it as a separate test.  I'm not sure what you're trying to achieve with this, but running one test inside another is not a good idea.  nose supports the concept of Test Generators, which might do what you want.

A: Your question doesn't make sense. There are just three tests in your code; the fact that the last test calls another test doesn't magically "split" the test case into two, independent tests - test003_bac is still just one, single test.


text:
Q: Standalone tikz seems to become "squished" in document I'm creating tikz UML diagrams using the standalone package to draw them separately without compiling my whole document to see of the image looks correct.
I'm using tikzEdt (www.tikzedt.org) to create the image and the \includestandalone{"path to tex file"} to insert it into my document. My problem is that the image positioning in tikzEdt seems to be adjusted upon inclusion into the whole document. To illustrate: The tikzEdt output:
and code:
\documentclass{standalone}

\usepackage{tikz-uml}
\begin{document}

%\thispagestyle{empty}

\begin{tikzpicture}[x=1cm,y=1cm]

% loads
\umlclass[type = Abstract, y=-2.5]{Loads}{
  $Name$\\
  $Load$ $case$ $name$\\
  $Node$\\
  $Degree$ $of$ $freedom$\\
  $Magnitude$
}{$Copy$ $functionality$}

\umlclass[x=-5, y=-2]{PointLoad}{
  $DOF = 1 -3$
}{$Copy$ $functionality$}

\umlclass[x=-5, y=-5]{PointMoment}{
  $DOF = 4 -6$
}{$Copy$ $functionality$}

\umlclass[x=0, y=-8]{LineLoad}{
    $Name$\\
  $Load$ $case$ $name$\\
  $Direction$\\
  $Element$\\
  $Magnitude$
}{$Copy$ $functionality$\\
   $Divide$ $into$ $PointLoads$\\
   $Divide$ $into$ $PointMoments$
}

% connectors

\umlinherit[]{Loads}{PointLoad}
\umlinherit[]{Loads}{PointMoment}

%% Load cases
\umlclass[x=5, y=-2]{LoadCase}{
   $Name$\\
  $Loads$\\
  $LineLoads$\\
  $Resutling$ $reactions$\\
  $Resutling$ $displacements$\\
}{$Copy$ $functionality$}

\umlclass[x=5, y=-7]{LoadCombination}{
   $Load$ $cases$\\
  $Loads$\\
  $LineLoads$\\
  $Resutling$ $reactions$\\
  $Resutling$ $displacements$\\
}{$Copy$ $functionality$}

% connectors

\umlinherit[]{LoadCase}{LoadCombination}

%% Manager
\umlclass[x=0, y=2]{LoadManager}{
   $Load$ $cases$\\
  $Load$ $combinations$\\
}{$Copy$ $functionality$}

\end{tikzpicture}

\end{document}

While once compiled in my main document it looks like this
I included it with this code:
\begin{figure}[H]
\centering
\includestandalone{Software_implementation/loadsUML}
%Hello figure!
\caption{UML diagram illustrating the loads package}
\label{fig: loadsUML}
\end{figure}

Any idea why this happens? I tried specifying the tikz units, but it didn't seem to work.
EDIT:
A MWE to show what happens (Its caused by font size)
%\documentclass[]{article}
\documentclass[12pt]{article} % produces "squishing"

%% Latex bib package
\usepackage[backend=biber]{biblatex} % using biber build

\usepackage{float}
\usepackage[subpreambles=true]{standalone} % outsource figure to their own files

\begin{document}

\begin{figure}[H]
\centering
\includestandalone{loadsUML}
\caption{UML diagram illustrating the loads package}
\label{fig: loadsUML}
\end{figure}

\end{document}

How can this be fixed?

A: Turns out, I was creating my tikz drawing using a different font size than my document. The issue can be resolved by specifying the font size in the first line of the tikz drawing's file. i.e. \documentclass[12pt]{standalone}. Now I can create my figures exactly as they will appear in the document (If they are not too wide that is).


text:
Q: Migration from Spring 2.5 to 4 I want to migrate my project from Spring 2.5 to Spring 4.1
The old versions of Spring and Hibernate jars used in my project are:
spring 2.5.6
spring-webmvc 2.5.6
spring-webflow 2.0.7.RELEASE
hibernate-annotations 3.4.0.GA
hibernate-commons-annotations 3.1.0.GA
hibernate-core 3.3.1.GA
hibernate ejb3-persistence 1.0.2.GA
I wanted to know if there is a way I could find the latest version of Hibernate which is compatible with Spring ie 4.1
Secondly I would like to know what configuration changes should I make in applicationContext.xml.
My applicationContext looks like this
<?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

  <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
          <property name="location" value="classpath:jdbc.properties"/>
          <property name="ignoreUnresolvablePlaceholders" value="true"/>
   </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${dataSource.driverClassName}"></property>
        <property name="url" value="${dataSource.url}"></property>
        <property name="username" value="${dataSource.username}"></property>
        <property name="password" value="${dataSource.password}"></property>
        <property name="initialSize" value="1"></property>
        <property name="maxActive" value="10"></property>
        <property name="maxIdle" value="14"></property>
        <property name="minIdle" value="2"></property>
        <property name="maxWait" value="15000"></property>
        <property name="validationQuery" value="SELECT 1"></property>
        <property name="minEvictableIdleTimeMillis" value="5000"></property>
        <property name="testOnBorrow" value="true"></property>
        <property name="testOnReturn" value="true"></property>
        <property name="removeAbandoned" value="true"></property>
        <property name="removeAbandonedTimeout" value="5"></property>
    </bean>

  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- Limit uploads to small (5KB) files for this sample -->
        <property name="maxUploadSize" value="809000" />
  </bean>

    <!-- Default Connection -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>/WEB-INF/hibernate.cfg.xml</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${dataSource.dialect}</prop>
                <prop key="hibernate.default_batch_fetch_size">30</prop>
                <prop key="hibernate.jdbc.fetch_size">20</prop>
                <prop key="org.hibernate.cache">info</prop>
                <prop key="org.hibernate.transaction">debug</prop>
                <prop key="hibernate.jdbc.batch_size">100</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.use_sql_comments">true</prop>
                <prop key="hibernate.max_fetch_depth">3</prop>
                <prop key="hibernate.jdbc.batch_versioned_data">true</prop>
            </props>
        </property>
        <property name="schemaUpdate" value="false" />

    </bean>

  <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
  </bean>

  <tx:annotation-driven transaction-manager="txManager"/>

  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
  </bean>

 <bean id="baseService" abstract="true" lazy-init="true">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="sessionFactory" ref="sessionFactory"/>

  </bean>
</beans>

and at last, I'm using HibernateTemplate for my queries. Can I continue using the same after migration.?
Many thanks for every tip in advance...

A: In theory it should be a drop in replace. However before migrating I strongly suggest you first change the xml files you use. Currently you have versioned xsd in your headers i.e. spring-beans-2.5.xsd remove the versions i.e. spring-beans.xsd.
Next your PropertyPlaceHolderConfigurer is best replaced with a <context:property-placeholder /> instead of the plain bean.
The hibernate integration has been highly refactored for Hibernate4 so I would stick with the latest hibernate 3.x version (3.6.10) and make that a separate migration (to either plain Hibernate 4 or JPA). If you have it running again then upgrade to the latest hibernate version (4.3.6) as that will require some code changes and depending on the amount of code can hurt considerably.
You are using the spring jar which doesn't exists anymore so you need to figure out which modules you need (judging from your setup at least jdbc and orm). I really hope that you are using Maven to manage your dependencies else you are in for a treat looking for the correct bundle of related dependencies.
Spring Web Flow will also require an upgrade to the latest 2.4.0, not sure if that is a drop in replacement though.
After updating I guess most of it will still work (or you must have some other unlisted dependencies here that also require an upgrade).
One thing to keep in mind is that also the minor java versions got upgraded so when upgrading to Spring 4.x your project needs to be at least java 1.6 if you are still on 1.5 or lower it will not work.
I also strongly recommend reading the migration guide which contains some valuable information. (You might want to skim through the history of the document to retrieve the 2.5 -> 3.x version).


text:
Q: How to run code in a separate thread? I want to spawn a thread and run code in that thread. What are the options in Scala?
Example usage would be something like this:
Thread.currentThread setName "MyThread"

val myThreadExecutor = ???

val threadNamePromise = Promise[String]

future {
  myThreadExecutor run {
    val threadName = "MySpecialThread"
    Thread.currentThread setName threadName
    threadNamePromise success threadName
  }
}

Await.result(threadNamePromise.future, Duration.Inf)

future {
  myThreadExecutor run {
    println(Thread.currentThread.getName) // MySpecialThread
  }
}

future {
  myThreadExecutor run {
    println(Thread.currentThread.getName) // MySpecialThread
  }
}

println(Thread.currentThread.getName)   // MyThread

Is there anything in the built-in Scala library that I can use?
Edit
I updated the snippet to better reflect intent

A: Yes, there is. You can use the scala.concurrent from the standard library. More specifically, you can use futures - highly composable asynchronous computations.
import java.util.concurrent.Executors
import concurrent.{ExecutionContext, Await, Future}
import concurrent.duration._

object Main extends App {

  // single threaded execution context
  implicit val context = ExecutionContext.fromExecutor(Executors.newSingleThreadExecutor())

  val f = Future {
    println("Running asynchronously on another thread")
  }

  f.onComplete { _ =>
    println("Running when the future completes")
  }

  Await.ready(f, 5.seconds) // block synchronously for this future to complete

}

Futures run in an execution context, which is an abstraction for thread pools. This context can be passed implicitly. In the above example, we used a global one, defined by the Scala library - but you can control this aspect of your program by allocating many execution contexts.
The snippet only does what you asked - running code concurrently. However, futures are much more than that - they allow you to compute values asynchronously, compose multiple futures to obtain results with dependencies amongst them, or in parallel.
Here's an intro: http://docs.scala-lang.org/overviews/core/futures.html

A: Using the answer of @alexwriteshere as a basis I created this implementation:
import java.util.concurrent.Executors
import scala.concurrent.future
import scala.concurrent.JavaConversions.asExecutionContext

class ApplicationThread {
  protected implicit val context =
    asExecutionContext(Executors.newSingleThreadExecutor())

  def run(code: => Unit) = future(code)
}

Update
Thanks to @Dth for pointing out that this is the modern version:
import java.util.concurrent.Executors
import scala.concurrent.{ExecutionContext, Future}

class ApplicationThread {
  protected implicit val context =
    ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor())

  def run(code: => Unit) = Future(code)
}

A: Besides the standard concurrency library, there's a few more. For example, there's com.twitter / util-core library that lets you do:
val pool = FuturePool.unboundedPool
pool {
   <code>
}

Your example would look like:
Thread.currentThread setName "MyThread"

// because you have to be using a single-threaded one to get the same name
val pool = FuturePool(Executors.newSingleThreadExecutor())

pool {
  Thread.currentThread setName "MySpecialThread"
}

pool {
  println(Thread.currentThread.getName) // MySpecialThread
}

println(Thread.currentThread.getName)

A: Based on @EECOLOR'S answer, here's a generic, reusable method that executes arbitrary code on a separate thread:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def executeParallelTask[T](code: => T): Future[T] = Future(code)

A: ExecutionContext
  .fromExecutorService(Executors.newSingleThreadExecutor())
  .execute(() => {
    // your code here
  })


text:
Q: The module is square-free iff every factor is summand-square-free Recall that a right $R$-module $M_R$ is called square-free if whenever $A,B\leq M$ are submodules with $A\cap B=0$ and $A\cong B=0$ then $A=B=0$.
A submodule $N$ of a module $M$ is called a summand (written $N \leq^{\oplus}M$) if $M$ is the internal direct sum $M=N\oplus K$ for some submodule $K\leq M$.
$M_R$ is called summand-square-free if whenever $A,B$ are summands with $A\cap B=0$ and $A\cong B$ then $A=B=0$.
If $M$ is a module, by a factor module of $M$ we mean a quotient $M/N$ for some $N\leq M$.
Indeed, any square-free module is summand-square-free but the converse is not necessarily true.
We have the following characterization:
$M_R$ is square-free $\iff$ Every factor module of $M$ is summand-square-free.
How can I prove this statement?!.
I appreciate any help. Thanks in advance.

A: Only if part
Assume that $M_R$ is summand-square-free.
Let $A,B\leq M$ be submodules such that $A\cap B=0$ and $A\cong B$.
Then $\frac{A+B}{B}$ and $\frac{A+B}{A}$ are factor modules and they are isomorphic since $\frac{A+B}{B}\cong A$ and $\frac{A+B}{A}\cong B$.
It also follows that $\frac{A+B}{B}\cap\frac{A+B}{A}=0$ since $A\cap B=0$.
Then, by assumption, $\frac{A+B}{B}=\frac{A+B}{A}=0$. This implies $A=B=0$.
If part
Assume that $M_R$ is square-free.
Let $A=\frac{N_1}{M_1}$ and $B=\frac{N_2}{M_2}$ be two factor modules with $A\cap B=0$ and and $A\cong B$.
Then, if $A'=\frac{N_1+N_2}{M_1+N_2}$ and $B'=\frac{N_1+N_2}{M_2+N_1}$ then $A'\cong B'$ and $A'\cap B'=0.$ So without loss of generality we may assume that $A=\frac{N}{M_1}$ and $B=\frac{N}{M_2}$.
Then, if $A''=\frac{\frac{N}{M_1\cap M_2}}{\frac{M_1}{M_1\cap M_2}}$ and $B''=\frac{\frac{N}{M_1\cap M_2}}{\frac{M_2}{M_1\cap M_2}}$ then $A''\cong B''$ and $A''\cap B''=0.$ So without loss of generality we may assume that $A=\frac{N}{M_1}$ and $B=\frac{N}{M_2}$ such that $M_1\cap M_2=0$.
Without loss of generality we assumed that $A=\frac{N}{M_1}$ and $B=\frac{N}{M_2}$ such that $M_1\cap M_2=0$. We have also the conditions $A\cong B$ and $A\cap B=0$. It then follows that $M_1\cong M_2$.
Now, $M_1\cong M_2$ and $M_1\cap M_2=0$ imply that $M_1=M_2=0$ since $M_R$ is square-free.
Then, $A\cap B=N\cap N=N=0$. Hence, $A=B=\frac{0}{0}=0$.


text:
Q: App has stopped unexpectedly, and i don't know why I get no errors but when I run the app it crashes and I don't know why!
Here is the code, I am sure the error is here because it was working until here.
I've been trying to search for the problem for about 4 hours and still have no clue!
public class MainActivity extends Activity implements OnClickListener {

    EditText et1, et2, usuario1, password1, password2;
    Button ingresar, borrar, ajustes, cancelarBtn, okusBtn;
    Dialog dialog;
    Context context = this;
    String usuario = "";
    String password = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et1=(EditText)findViewById(R.id.et1);
        et2=(EditText)findViewById(R.id.et2);
        ingresar=(Button)findViewById(R.id.ingresar);
        borrar=(Button)findViewById(R.id.borrar);
        ajustes=(Button)findViewById(R.id.ajustesBtn);
        cancelarBtn =(Button)dialog.findViewById(R.id.cancelarUs);
        okusBtn =(Button)dialog.findViewById(R.id.okUs);
        password1=(EditText)dialog.findViewById(R.id.password1);
        password2=(EditText)dialog.findViewById(R.id.password2);
        usuario1=(EditText)dialog.findViewById(R.id.usuario1);

        borrar.setOnClickListener(this);
        ingresar.setOnClickListener(this);
        ajustes.setOnClickListener(this);
        cancelarBtn.setOnClickListener(this);
        okusBtn.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View arg0) {
        switch(arg0.getId()){
        case R.id.ingresar:
            String usRecibido=et1.getText().toString();
            String pasRecibido=et2.getText().toString();

            if(usRecibido.equals(usuario) && pasRecibido.equals(password)){
                Intent pancar = new Intent("com.example.iniciosesion.Iniciado");
                Bundle bolsa = new Bundle();
                bolsa.putString("NombreKey", usRecibido);
                pancar.putExtras(bolsa);
                startActivity(pancar);
            }else{
                Toast ts=Toast.makeText(this, "Usuario o contraseña incorrecto", Toast.LENGTH_LONG);
                ts.show();
            }
            break;
        case R.id.borrar:
            et1.setText("");
            et2.setText("");
            break;
        case R.id.ajustesBtn:
             dialog = new Dialog(context);
             dialog.setContentView(R.layout.controlusuario);
             dialog.setTitle("Modificar usuario");
             if(usuario == "" && password == ""){
             password1.setHint("Crear password");
             }else{
             password1.setHint("Password actual");
             }
            break;
        case R.id.cancelarUs:
             dialog.dismiss();
            break;
        case R.id.okUs:
            if(usuario == "" && password == "" && password1.getText().toString() == password2.getText().toString()){
                 usuario = usuario1.getText().toString();
                 password = password1.getText().toString();
            }
            if(usuario1.equals(usuario) && password1.equals(password))
                 password = password2.getText().toString();
                 usuario = usuario1.getText().toString();
            break;
        }
    }
}

A: Try this code I have initialized the dialog in the onCreate() method
public class MainActivity extends Activity implements OnClickListener{

EditText et1, et2, usuario1, password1, password2;
Button ingresar, borrar, ajustes, cancelarBtn, okusBtn;
Dialog dialog;
Context context = this;
String usuario = "";
String password = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

et1=(EditText)findViewById(R.id.et1);
et2=(EditText)findViewById(R.id.et2);
ingresar=(Button)findViewById(R.id.ingresar);
borrar=(Button)findViewById(R.id.borrar);
ajustes=(Button)findViewById(R.id.ajustesBtn);
dialog = new Dialog(getBaseContext);
         dialog.setContentView(R.layout.controlusuario);
         dialog.setTitle("Modificar usuario");
cancelarBtn =(Button)dialog.findViewById(R.id.cancelarUs);
okusBtn =(Button)dialog.findViewById(R.id.okUs);
password1=(EditText)dialog.findViewById(R.id.password1);
password2=(EditText)dialog.findViewById(R.id.password2);
usuario1=(EditText)dialog.findViewById(R.id.usuario1);

borrar.setOnClickListener(this);
ingresar.setOnClickListener(this);
ajustes.setOnClickListener(this);
cancelarBtn.setOnClickListener(this);
okusBtn.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onClick(View arg0) {
    switch(arg0.getId()){
    case R.id.ingresar:
        String usRecibido=et1.getText().toString();
        String pasRecibido=et2.getText().toString();

    if(usRecibido.equals(usuario) && pasRecibido.equals(password)){
        Intent pancar = new Intent("com.example.iniciosesion.Iniciado");
        Bundle bolsa = new Bundle();
        bolsa.putString("NombreKey", usRecibido);
        pancar.putExtras(bolsa);
        startActivity(pancar);
    }else{
        Toast ts=Toast.makeText(this, "Usuario o contraseña incorrecto", Toast.LENGTH_LONG);
        ts.show();
    }
    break;
case R.id.borrar:
    et1.setText("");
    et2.setText("");
    break;
case R.id.ajustesBtn:
     if(usuario == "" && password == ""){
     password1.setHint("Crear password");
     }else{
     password1.setHint("Password actual");
     }
    break;
case R.id.cancelarUs:
     dialog.dismiss();
    break;
case R.id.okUs:
    if(usuario == "" && password == "" && password1.getText().toString() == password2.getText().toString()){
         usuario = usuario1.getText().toString();
         password = password1.getText().toString();
    }
    if(usuario1.equals(usuario) && password1.equals(password))
         password = password2.getText().toString();
         usuario = usuario1.getText().toString();
    break;
}

}


text:
Q: Mysql like to match pattern at end of string I have the following strings in the following pattern in a table in my db:
this_is_my_string_tester1
this_is_my_string_mystring2
this_is_my_string_greatstring

I am trying to match all strings that start with a specific pattern split by underscores i.e.this_is_my_string_ and then a wildcard final section
Unfortunately there is an added complication where some strings like the following:
this_is_my_string_tester1_yet_more_text
this_is_my_string_mystring2_more_text
this_is_my_string_greatstring_more

Therefore taking the following as examples:
this_is_my_string_tester1
this_is_my_string_mystring2
this_is_my_string_greatstring
this_is_my_string_tester1_yet_more_text
this_is_my_string_mystring2_more_text
this_is_my_string_greatstring_more

I am trying to have returned:
this_is_my_string_tester1
this_is_my_string_mystring2
this_is_my_string_greatstring

I have no idea how to do this with a like statement.  Is this possible if so how?
EDIT
There is one final complication:
 this_is_my_string

needs to be supplied as a list i.e in
(this_is_my_string,  this_is_my_amazing_string, this_is_another_amazing_string)

A: SELECT * FROM atable WHERE afield REGEXP 'this_is_my_string_[a-z]+'

It might be faster if you have an index on afield and do
SELECT * FROM atable WHERE afield REGEXP 'this_is_my_string_[a-z]+'
                     AND afield LIKE 'this_is_my_string_%'

After edit of question:
Either
SELECT * FROM atable
WHERE afield REGEXP '(this_is_my_string|this_is_my_amazing_string)_[a-z]+'

or maybe you want something like having a table with the prefixes:
SELECT *
FROM atable AS t,
    prefixes AS p
WHERE afield REGEXP CONCAT(p.prefix, '_[a-z]+')

As by the reference documentation this should not be possible, as a pattern (string literal) is required. Give it a try nevertheless.
There the answer of @KayNelson with LIKE (?) and INSTR might do instead of REGEXP.

A: try this
SELECT * FROM db.table WHERE strings LIKE 'this_is_my_string_%' AND instr(Replace(strings,"this_is_my_string_",""),"_") = 0;

It checks if more _ occurs after replacing the standard "this_is_my_string_"


text:
Q: For some reason I don't have an 'Automatically Add to iTunes' folder. Is that normal? I'm reading that a lot of people have this folder under their ~/Music/iTunes/ folder called Automatically Add to iTunes that lets them put files in and have iTunes reorganize them within the library and remove them.
I don't have this folder for some reason. Here's my command line list of files in that folder:
[teddyknox@teddyknox iTunes]$ ls -la
total 47960
drwxr-xr-x+ 14 teddyknox  staff       476 Dec 19 12:10 .
drwxr-xr-x@ 12 teddyknox  staff       408 Dec 17 16:44 ..
-rw-r--r--@  1 teddyknox  staff     12292 Dec 19 10:44 .DS_Store
drwxr-xr-x+  6 teddyknox  staff       204 Nov 30 10:15 Album Artwork
drwxr-xr-x+ 10 teddyknox  staff       340 Mar 31  2012 Mobile Applications
drwxr-xr-x+ 13 teddyknox  staff       442 Nov 30 10:14 Previous iTunes Libraries
-rw-r--r--+  1 teddyknox  staff    538607 Dec 20  2011 Temp File.tmp
-rw-r--r--+  1 teddyknox  staff   3685049 Dec 20  2011 iT.tmp
-rw-r--r--+  1 teddyknox  staff    172032 Dec 19 10:26 iTunes Library Extras.itdb
-rw-r--r--+  1 teddyknox  staff    528384 Nov 30 10:14 iTunes Library Genius.itdb
-rw-r--r--@  1 teddyknox  staff   4022157 Dec 19 12:10 iTunes Library.itl
lrwxr-xr-x   1 teddyknox  staff        56 Sep 13 19:37 iTunes Media ->       /Volumes/root/Users/teddyknox/Music/iTunes/iTunes Media/
-rw-r--r--@  1 teddyknox  staff  15579060 Dec 19 12:10 iTunes Music Library.xml
-rw-r--r--@  1 teddyknox  staff         8 Dec 19 10:26 sentinel
[teddyknox@teddyknox iTunes]$ pwd
/Users/teddyknox/Music/iTunes

I've tried manually adding a folder with that name and restarting iTunes, but the process still doesn't work.
Why am I missing this folder, and what I can I do to get it in place and working OK?

A: It's in the iTunes Media folder, no?
iTunes Media % pwd
/Users/paul/Music/iTunes/iTunes Media
iTunes Media % ls -la                                                                                total 8
drwxr-xr-x   6 paul  staff  204 31 Oct 10:37 .
drwxr-xr-x  11 paul  staff  374 19 Dec 16:37 ..
-rw-r--r--@  1 paul  staff  305 20 Aug  2010 .iTunes Preferences.plist
drwxr-xr-x   2 paul  staff   68 20 Aug  2010 Automatically Add to iTunes
drwxr-xr-x   7 paul  staff  238 31 Oct 11:21 Mobile Applications
drwxr-xr-x   4 paul  staff  136  5 Jan  2012 Music


text:
Q: Is the below xml file right? Is the below xml file right? I am trying to display information that I have fetched from sqlite in recycler view.
Is the below xml file right? I am trying to display information that I have fetched from sqlite in recycler view.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="150dp">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/textView2"
                android:layout_width="3dp"
                android:layout_height="23dp"
                android:textSize="20sp"
                android:textStyle="bold"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.2"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.3" />

            <TextView
                android:id="@+id/semester"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.15"
                app:layout_constraintStart_toEndOf="@+id/textView2"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.3" />

            <TextView
                android:id="@+id/textView32"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="SGPA"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.2"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.7" />

            <TextView
                android:id="@+id/textView33"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Percentage"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.6"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.70" />

            <TextView
                android:id="@+id/textV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintBottom_toBottomOf="@+id/textView32"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.08"
                app:layout_constraintStart_toEndOf="@+id/textView32"
                app:layout_constraintTop_toTopOf="@+id/textView32"
                app:layout_constraintVertical_bias="0.0" />

            <TextView
                android:id="@+id/textVw"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintBottom_toBottomOf="@+id/textView33"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.08"
                app:layout_constraintStart_toEndOf="@+id/textView33"
                app:layout_constraintTop_toTopOf="@+id/textView33" />

            <TextView
                android:id="@+id/scheme1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="10sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.95"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.95" />

            <ImageButton
                android:id="@+id/btndelete1"
                android:layout_width="30dp"
                android:layout_height="40dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.96"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.05"
                app:srcCompat="@android:drawable/ic_menu_delete" />

        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>

This is what I want:

And this is what I am getting:

I don't know why. Can someone help me out?
Also, if needed, this is where I am calling the recycler view:
 <?xml version="1.0" encoding="utf-8"?>

        <FrameLayout xmlns:android="http://schemas.android

.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".drawernav.bottom_navi.recycler_view.sgpa_frag">

        <!-- TODO: Update blank fragment layout -->
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rc1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

        </androidx.recyclerview.widget.RecyclerView>

        <TextView
            android:id="@+id/else2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="It's a bit lonely here..."
            android:gravity="center"
            android:visibility="gone"/>

    </FrameLayout>

A: Try to use this layout:
   <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="0dp">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.2" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="1"
        android:textSize="20sp"
        android:textStyle="bold"

        app:layout_constraintBottom_toBottomOf="@+id/btndelete1"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/btndelete1"
        app:layout_constraintVertical_bias="0.3" />

    <TextView
        android:id="@+id/semester"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="2"
        app:layout_constraintBottom_toBottomOf="@+id/textView2"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.15"
        app:layout_constraintStart_toEndOf="@+id/textView2"
        app:layout_constraintTop_toTopOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.3"
        app:layout_constraintWidth_percent="0.1" />

    <TextView
        android:id="@+id/textView32"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="SGPA"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="@+id/textView2"
        app:layout_constraintHorizontal_bias="0.2"
        app:layout_constraintStart_toStartOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.7"
        app:layout_constraintWidth_percent="0.1" />

    <TextView
        android:id="@+id/textView33"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="Percentage"
        app:layout_constraintBottom_toBottomOf="@+id/textView32"
        app:layout_constraintEnd_toStartOf="@+id/btndelete1"
        app:layout_constraintHorizontal_bias="0.6"
        app:layout_constraintStart_toEndOf="@+id/semester"
        app:layout_constraintTop_toTopOf="@+id/textView32"
        app:layout_constraintVertical_bias="0.70"
        app:layout_constraintWidth_percent="0.18" />

    <TextView
        android:id="@+id/textV"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="3"
        app:layout_constraintBottom_toBottomOf="@+id/textView32"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="@+id/semester"
        app:layout_constraintHorizontal_bias="0.08"
        app:layout_constraintStart_toStartOf="@+id/semester"
        app:layout_constraintTop_toTopOf="@+id/textView32"
        app:layout_constraintVertical_bias="0.0"
        app:layout_constraintWidth_percent="0.1" />

    <TextView
        android:id="@+id/textVw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="5"
        app:layout_constraintBottom_toBottomOf="@+id/textView33"
        app:layout_constraintEnd_toStartOf="@+id/btndelete1"
        app:layout_constraintHorizontal_bias="0.08"
        app:layout_constraintStart_toEndOf="@+id/textView33"
        app:layout_constraintTop_toTopOf="@+id/textView33" />

    <TextView
        android:id="@+id/scheme1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="4"
        android:textSize="10sp"
        app:layout_constraintEnd_toEndOf="@+id/btndelete1"
        app:layout_constraintStart_toStartOf="@+id/btndelete1"
        app:layout_constraintTop_toTopOf="@+id/guideline" />

    <ImageButton
        android:id="@+id/btndelete1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.96"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.05"
        app:layout_constraintWidth_percent="0.1"
        app:srcCompat="@android:drawable/ic_menu_delete" />

</androidx.constraintlayout.widget.ConstraintLayout>

I have used those attributes to make your layout responsive:
app:layout_constraintGuide_percent="0.2"
app:layout_constraintDimensionRatio="1:1"

In addition, I added Guideline
And it will look like this:


text:
Q: Prevent LuaLaTeX from splitting umlauts Here's a minimal example:
\documentclass{minimal}
\usepackage{fontspec}\setmainfont{Cambria}
\begin{document}aöz\end{document}

Compiling this into a PDF using lualatex and extracting the text using pdftotext, I get the string aö z, that is:
U+0061(a) U+006f(o) U+0308(combining diaeresis) U+0020(space) U+007a(z)

Two problems with this: there's an unnecessary space (due to some PDF formatting trickery, the uncompressed datastream shows Tm[<…>125<01C5>-124<…>]TJ), and I don't want the umlaut to be split into base and combining character because for some reason that renders weirdly when changing the font size. I want the output to be
U+0061(a) U+00f6(ö) U+007a(z)

And the worst thing: with \setmainfont{Lucida Grande}, I get exactly that. Just not with Cambria.
Both are in TTF format. Checking the fonts in fontforge shows that both their U+00f6 glyphs are defined as composed of U+006f U+0308, only difference being that Cambria defines its OTF Class as "Base Glyph" while in Lucida Grande it's "Automatic" (no idea what that means).

It is a fontspec specific problem:
\documentclass{minimal}
\usepackage{luaotfload}
\font\foo={name:Cambria} at 10pt
\begin{document}
aöz \foo aöz
\end{document}

generates what I expect, first umlaut missing as expected, too:
U+0061(a) U+007a(z) U+0020(space) U+0061(a) U+00f6(ö) U+007a(z)

but
\documentclass{minimal}
\usepackage{fontspec}
\begin{document}
aöz \fontspec{Cambria} aöz
\end{document}

generates
U+0061(a) U+00f6(ö) U+007a(z) U+0020 U+0061(a) U+006f(o) U+0308 U+0020 U+007a(z)

Same when using \DeclareUTFcharacter{x00F6}{\foo} and replacing ö with \foo{}, so I guess it's not xunicode's fault?

A: From this answer I learned there is a Renderer=Basic option that causes an unknown number of side-effects.
\documentclass{minimal}
\usepackage{fontspec}
\defaultfontfeatures{Renderer=Basic}
\begin{document}
aöz \fontspec{Cambria} aöz ffi
\end{document}

The font doesn't seem to use ligatures anyway, where I want to use special features like VerticalPosition=Numerator for vulgar fractions, I can just switch to Renderer=Full.
A way to keep it from messing around in my unicode while keeping all functionality would be better though…

I've been using the Basic renderer since and it seems to support the font's built in ligatures after all (for Cambria look at ti), no TeX-ligatures like --- for dashes though, need to enter those as unicode —


text:
Q: python zip file hit userwarning: Duplicate name I have a python script that exclude the folder and zip the rest into zip file. However my script zip all the files in the same directory level
it gives the following error:
C:\Program Files\Python39\lib\zipfile.py:1505: UserWarning: Duplicate name: '1.txt'
  return self._open_to_write(zinfo, force_zip64=force_zip64)
C:\Program Files\Python39\lib\zipfile.py:1505: UserWarning: Duplicate name: '2.txt'
  return self._open_to_write(zinfo, force_zip64=force_zip64)

the folder structure to be zip
-test
 -file1
   -1.txt
   -2.txt
 -file2
   -1.txt
   -2.txt
 -dump
 -file3

My python script
import os
from zipfile import ZipFile
from datetime import date
from os.path import basename

# format the dd/mm/y
today = date.today()
todayDate = today.strftime("%d-%m-%y")

# path to zip
pathZip = "C:\\PY\\Project\\Self\\python-zip\\test"
# get the final forler name
forlderToZip = basename(pathZip)

# format the zip file name
zipFileName = todayDate + " " + forlderToZip + ".zip"
# create a ZipFile object
zipObj = ZipFile(zipFileName, "w")
# exclude the folder to be zip
exclude_folder = "dump"

print("Zip start...")
for dirname, subdirs, files in os.walk(pathZip):
    if exclude_folder in subdirs:
        subdirs.remove(exclude_folder)
    # Add empty folder to zip
    zipObj.write(dirname)
    for filename in files:
        # create complete filepath of file in directory
        filePath = os.path.join(dirname, filename)
        # Add file to zip
        zipObj.write(filePath,basename(filePath))
        print("Zip " + filePath)
# close the Zip File
zipObj.close()
print("Zip done !")

A: The duplicate name warning comes from the input directory files, of the same name, all being written to the same place of the output zip. The below get overwritten and you are left with two text files in the zip.
-Output Zip
    -1.txt
    -1.txt
    -2.txt
    -2.txt

The arcname argument is expanded below to retain the nesting structure of your original directory. The arcname arg modifies the name and placement of a file when writing to a zip. The 'if continue' is used to skip child files with 'dump' in their path.
import os
from zipfile import ZipFile

path_to_dir = ''
path_to_zip = ''

output_zip = ZipFile(path_to_zip, "w")
for dirpath, dirnames, filenames in os.walk(path_to_dir):
    if 'dump' in dirpath:
        continue
    for f in filenames:
        outpath = os.path.join(dirpath, f)
        arcname = outpath[len(path_to_dir):].lstrip(os.sep)
        output_zip.write(outpath, arcname)
output_zip.close()

-Output Zip
    -folder1
        -1.txt
        -2.txt
    -folder2
        -1.txt
        -2.txt

Alternatively, rename the files from the original directory such that they are unique. One way to do this is by replacing backslashes in the arcname path.
arcname = outpath[len(path_to_dir):].lstrip(os.sep).replace('\\', '_')

-Output Zip
    -folder1_1.txt
    -folder1_2.txt
    -folder2_1.txt
    -folder2_2.txt

For more info see nested directory appear while creating zip file


text:
Q: Tutorial for QPushButton graphics Does anyone know some good tutorial to learn how to do some graphics/animation/design for the Qt QPushButton?
I've been looking for one suitable for me, but I find none really interesting or well explained.
I've read the documentation, but I want some application and some example. Plus it can be a good source of inspiration.

A: So when you are looking at a QPushButton, or any QWidget for that matter, there are a ton of things you can animate on it.
And anything that isn't an explicit property, you can make a wrapper for it and make a property of it.
You first should examine all the properties on the List of all members, including inherited members for any class.
http://qt-project.org/doc/qt-5/qwidget-members.html
http://qt-project.org/doc/qt-5/qpropertyanimation.html
Some ones that are nice for animations include:
pos() / move()

size() / resize()

And then if you add on a QGraphicsEffect, and you animate a property of the effect, you can get some neat things, too.
And then you combine some of the animations to start when a particular event happens, like the first time it is shown, or when it is hiding, or when it is hovered/entered, or when it is left, you can also get some neat effects.
And if you put the animation on a loop instead of on a single shot, or do a parallel animation you can get a great effect.
Mix in some delayed timing and multiple animations getting launched with easing curves and you get some classy interactions.
If you subclass your paintEvent, you can put in any sort of variable that you change over time, and send it to an QPropertyAnimation, too.
http://qt-project.org/doc/qt-5.0/qtcore/properties.html
One of the best places to learn about what can be done with animations are the Qt examples.
http://qt-project.org/doc/qt-5/examples-animation.html
http://qt-project.org/doc/qt-5/qtwidgets-animation-animatedtiles-example.html
The Animated Tile's example is fantastic and is a great place to start.
If you don't need animation, but just a simple hover styling change, setting the stylesheet is a much simpler way to go to achieve this effect.
Hope that helps.


text:
Q: Determine angular position from two potentiometers I am trying to generate a continuous angle based on the output of the two potentiometers that are inside my device. The pots are shifted by 180 degrees and are capable of spinning continuously. How can I use the signals from both pots to determine direction while also getting a continuous angle function? I understand how to do this with rotary encoders but am having difficulties doing the same with this device.

A: There will be a gap in each of the two pots near where they (ideally) instantaneously switch from 95% to 5% or vice-versa depending on the direction of rotation.
I suggest using the center range of each- switching from one to the other when the current one goes out of the center of the range, in this case it would be 50% +/- 22.5%. There will tend to be a smallish glitch at the transition. If you need to eliminate that you could blend the two readings together with a function that weights the two readings in a variable fashion. You still want to ignore the output that is too close to the transition, but to blend the two inputs in the intermediate range.

A: You don't need two potentiometers to determine direction. These aren't quadrature encoders. The reason you need two signals from a quadrature encoder (which are 90° out of phase, not 180°) is because they output pulses which do not carry any inherent position information.
Potentiometers outright give their absolute position every time you take a reading from them. You only need one pot to determine direction. Just compare the current position with the previous position.

As for tracking direction and cumulative changes in angle, "just" calculate the difference in angle between the present and past position and add it into a counter that keeps track of angular displacement.
This sounds pretty simple and if you knew what you were doing then everything I have already said makes sense. Where you are getting stuck is probably the next part: Actually calculating the difference in angle between present and past position in a way that reflects the actual direction of rotation.
There are two difficulties here:

*

*Between two points on a circle, you can always take two paths
between the points. Which is the one the rotation actually took?

*Even if you knew which path to pick between the two points, how do
you calculate the distance between the two points if the path
crosses the "wraparound point" (i.e. zero degrees, 360 degrees,
etc.)

Assuming that you are sampling fast enough relative to rotational speed that the shortest path around the circle is indeed equivalent to the movement between previous and present angular position, then the shortest path of the two paths is always the one representative of the angle that was traversed.
Therefore, you will need code that decides which way around the circle is shortest.  The most straightforward way to do this is to literally calculate the distance of both paths (one of which will always cross through zero), and compare the two.
Calculating the path between two points around a circle is easy if the path does not cross through the wraparound angle. You just subtract their angular positions.
But it is trickier if the path does cross over the wraparound point.
Whaty you do is find the distance from one point to the zero, then find the distance from the other point to the zero and add those distances together. Of course, when finding these two distances between each point to zero you also pick the shortest path around the circle since, they make up the shortest path around the circle between those two points. In this case, it is easy to know which is the shortest path since you can just compare the angular position to 180 degrees and you always know which direction is the shortest path to zero.
It's tricky, I know. But really, what you need to do is sit down with a pencil and paper, draw a few circles with two points on them in different scenarios (shortest path does not cross through zero, shortest path does cross through zero, etc) and work out each case. Then you write branching code to handle each case.
You can also use modulus math for a mathematically rigorous solution, but it is much more abstract.
What I ultimately did in my code, was I wrote a library that made classes of a "wrapping integer type" with operator overloading where each integer had three values: it's actual value, maximum value, and a minimum value (that is often, but not always zero for the sake of generality). That formed a circle of numbers that the actual value traveled around as you added to it or subtracted from it causing it to overflow or underflow. The subtraction in this case was made to always return the length of the shortest path. Both addition and subtraction also wrapped around the result if required. I was using those operations a lot in my code and it was unwieldly enough that and did not want to have distinct code every time it popped up. That would have been unmanageable.

EDIT: If you want to combine the two potentiometers so that the deadpoint around zero is ignored, it's easy once you have the above figured out. Just pick the encoder where the shortest path between the past and present point does not cross through zero and calculate the length of that path. Then add it to a counter. You can choose whether you want the counter to wraparound between 0 and 360 or to count to infinite. Or you can just calculate the distances for both potentiometers and average them before adding them to the counter, rejecting one of the pots if either its present or past position was too close to zero.

A: Part of the problem seems to be the 'unwrapping' of the phase information. The other part perhaps merging the readings from the two pots.
Assuming the two pots are read by ADCs, and then the results processed in an MCU, the following may at first seem a bit heavy-handed and slow, but it's conceptually rigorous.
A good representation for angle is a complex number. It can be rotated continuously, without having any discontinuity at the +/- 180 point.
I suggest then first mapping the potentiometer readings to complex numbers. This would involve a scaling and a sine and cosine lookup. In order to merge the two readings really neatly, one could reduce the magnitude of the complex number when it was close to the extremes of the potentiometer reading. Say have unity magnitude in the middle 50% of the range, then taper to zero magnitude at the ends. The two angle readings are now combined by averaging. The resultant vector will be more strongly weighted by the pot in the middle of its range, and the final reading will transition smoothly from one to the other, with no discontinuities.
You could probably achieve the same sort of result with simple angle processing, if then elses, and interpolation, with fewer machine cycles than involved in the sin/cos generation, but the complex route is clearer and less prone to error, and IMHO somewhat cooler.


text:
Q: Multiple Points attribute information into one Point in QGIS I have three points from two layers ( Point 2539 and 2538 from one layer lets say X and point AL101974 from layer Y ) ( Refer figure-1 below).
Point 2539 and 2538 has multiple attribute information ( figure-2) i wanted to add those information into point AL10974 along with distance of each point from AL10974 ( this distance we need to create not already in attribute)
I have used the Distance to nearest hub (Points) tool to get distance and other information but this will populate two columns ( when i am putting source layer as as layer X ) - fig 3 for reference.
I wanted to all these in one row so i will calculate further statistical analysis on it.

A: You can use Menu Processing / Toolbox / Join attributes by nearest. It will create a new layer joined layer - a copy of Y, but if you set Maximum nearest neighbors to 2, you will get two duplicate features with the attributes from both points from X. You also get an attribute for the distance. You can now copy the attributes from line 2 to line 1.
To add the attribute values of feature no. 2 to feature no. 1, use Refactor fields (see documentation Refactor fields). Create new fields with the same name, but a prefix (like 2_) and this expression: attribute (get_feature_by_id (@layer,2), '[attribute_name]'), where you have to replace [attribute_name] with the name of the attribute to be copied (screenshot 2).
If you have a lot of attributes to copy, you can run Refactor fields in batch mode.
The result looks like this: Values form line 2 are copied at the end of line 1. You can now delete the second feature:

Screenshot 2, Refactor fields dialog window: the joined attributes coming from layer X in the joined layer are copied so that the values of the 2nd feature will be copied as new attributes with the prefix 2_ to the first feature:

A: Finally there is solution:
Using MMQGIS plugin we can create the hub distance as there is dropdown from where we can specify common field.
MMQGIS Plugin > Create > Hub distance


text:
Q: Exception trying to convert String to UTC date format I tried to convert the string date to UTC date with below Java code snippet but getting Unparseable date format exception. Please find the code below and help me fix this issue.
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm-SSSZ");
    String strDate= "2017-06-01T01:30-0400";
    try {
        Date date = formatter.parse(strDate);
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        date = new Date(formatter.format(date));
        System.out.println(date+"gmt");

    } catch (ParseException e) {
        e.printStackTrace();
    }

Thanks in advance.

A: Cannot parse the
"yyyy-MM-dd'T'HH:mm-SSSZ"

Becuase of did not match with your
strDate= "2017-06-01T01:30-0400"

Try this:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm-SSS'Z'");
String strDate= "2017-06-01T01:30-040Z";


text:
Q: Conflict when using Sass and CSS at the same time When I add css to rules along with sass, it gives an error. And if you remove the rules for CSS, then everything is fine. I am tried to use node-sass and sass, but there is no difference. Here is the my config file:
'use strict';

const path = require('path');
const htmlPlugin = require('html-webpack-plugin');
const cleanPlugin = require('clean-webpack-plugin').CleanWebpackPlugin;
const miniCSS = require('mini-css-extract-plugin');

module.exports = function (undefined, { mode }) {
    const EnvDevelopment = mode === 'development';
    const EnvProduction = !EnvDevelopment;
    // Configuration
    return {
        // Paths context
        context: path.resolve(__dirname),
        // Entry points
        entry: {
            app: './src/scripts/app.js',
        },
        output: {
            // Output path (absolute)
            path: path.resolve(__dirname, 'dist'),
            // Generate hashes on production
            filename: EnvDevelopment
                ? 'js/[name].js'
                : 'js/[name].[contenthash:8].js',
            // Generate filename comments on development
            pathinfo: EnvDevelopment,
        },
        devtool: EnvDevelopment ? 'cheap-source-map' : false,
        module: {
            rules: [
                // If remove this rule then all is fine
                {
                    test: /.css$/,
                    use: [miniCSS.loader, 'css-loader'],
                },
                {
                    test: /.s[ac]ss$/,
                    use: [
                        miniCSS.loader,
                        'css-loader',
                        {
                            loader: 'sass-loader',
                            options: {
                                outputStyle: 'compressed',
                                sourceMap: EnvDevelopment,
                            },
                        },
                    ],
                },
            ],
        },
        plugins: [
            new htmlPlugin({
                template: './src/index.html',
            }),
            new miniCSS({
                filename: EnvDevelopment
                    ? 'css/[name].css'
                    : 'css/[name][contenthash:8].css',
            }),
            new cleanPlugin(),
        ],
    };
};

And there is a node js log:
0 verbose cli [
0 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
0 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
0 verbose cli   'run',
0 verbose cli   'dev'
0 verbose cli ]
1 info using npm@7.0.3
2 info using node@v15.0.1
3 timing config:load:defaults Completed in 2ms
4 timing config:load:file:C:\Program Files\nodejs\node_modules\npm\npmrc Completed in 1ms
5 timing config:load:builtin Completed in 1ms
6 timing config:load:cli Completed in 1ms
7 timing config:load:env Completed in 1ms
8 timing config:load:file:C:\Users\nurme\OneDrive\Documents\Projects\webpack-config\.npmrc Completed in 0ms
9 timing config:load:project Completed in 1ms
10 timing config:load:file:C:\Users\nurme\.npmrc Completed in 1ms
11 timing config:load:user Completed in 1ms
12 timing config:load:file:C:\Users\nurme\AppData\Roaming\npm\etc\npmrc Completed in 0ms
13 timing config:load:global Completed in 0ms
14 timing config:load:cafile Completed in 0ms
15 timing config:load:validate Completed in 0ms
16 timing config:load:setUserAgent Completed in 1ms
17 timing config:load:setEnvs Completed in 1ms
18 timing config:load Completed in 10ms
19 verbose npm-session 30a9861e250e9739
20 timing npm:load Completed in 25ms
21 timing command:run-script Completed in 2744ms
22 verbose stack Error: command failed
22 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\promise-spawn\index.js:63:27)
22 verbose stack     at ChildProcess.emit (node:events:327:20)
22 verbose stack     at maybeClose (node:internal/child_process:1048:16)
22 verbose stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:288:5)
23 verbose pkgid webpack-config@0.1.0
24 verbose cwd C:\Users\nurme\OneDrive\Documents\Projects\webpack-config
25 verbose Windows_NT 10.0.19041
26 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "dev"
27 verbose node v15.0.1
28 verbose npm  v7.0.3
29 error code 1
30 error path C:\Users\nurme\OneDrive\Documents\Projects\webpack-config
31 error command failed
32 error command C:\WINDOWS\system32\cmd.exe /d /s /c "webpack --mode development"
33 verbose exit 1

A: The problem was solved easily. It turns out that I forgot to put a backslash in regular expressions. It was /.s[ac]ss$/ when it was necessary /\.s[ac]ss$/


text:
Q: How to Give Amazon SES Permission to Write to Your Amazon S3 Bucket I want my SES(AWS) can receive emails, so I follow the following tutorial,
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-getting-started-receipt-rule.html
When I am at last step - creating rule, it comes with following error,
Could not write to bucket: "email-receiving"
I google and found this information on (http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-permissions.html) can fix the issue.
However, when adding my policy statement, it comes with an error - This policy contains the following error: Has prohibited field Principal For more information about the IAM policy grammar, see AWS IAM Policies.
My policy statement is,
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "GiveSESPermissionToWriteEmail",
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "ses.amazonaws.com"
                ]
            },
            "Action": [
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::mybulketname/*",
            "Condition": {
                "StringEquals": {
                    "aws:Referer": "my12accountId"
                }
            }
        }
    ]
}
If I take off

"Principal": {
                "Service": [
                     "ses.amazonaws.com"
                 ]
             }

Validate policy will pass.
Thanks

A: I follow this advice but I was still having the issue.   After much debugging, I realized that SES was failing to write because I had default server-side encryption (on the bucket) set to "AWS-KMS"
I did a 5 minute google search and couldn't find this incompatibility documented anywhere.
You can work around this by updating your default encryption setting on the target bucket to either "AES-256" or "None".

A: Find bucket->permission->bucketPolicy
{
    "Version": "2012-10-17",
    "Statement": [
       {
           "Sid": "AllowSESPuts",
           "Effect": "Allow",
           "Principal": {
               "Service": "ses.amazonaws.com"
           },
           "Action": "s3:PutObject",
           "Resource": "arn:aws:s3:::BUCKEN_NAME/*",
           "Condition": {
            "StringEquals": {
                   "aws:Referer": "YOUR ID"
                }
           }
       }
   ]
}

Read more here https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-permissions.html
To find your AWS account ID number on the AWS Management Console, choose Support on the navigation bar on the upper-right, and then choose Support Center. Your currently signed-in account ID appears in the upper-right corner below the Support menu.
Read more here https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html

A: This problem has been resolved.
Create the policy on the bucket you want to grant the SES permission, not in the IAM

A: Note, I continued to have this error even after correctly specifying permissions. If you are using cross-region (e.g. SES is in N Virginia and S3 Bucket is in Africa) then you either need to specify the bucket name with the region or else just make the bucket in the same region.

A: I have the same problem, if I only delete the "Condition"
the policy passes and the "RuleSet" is Ok:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "GiveSESPermissionToWriteEmail",
            "Effect": "Allow",
            "Principal": {
                "Service": "ses.amazonaws.com"
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::mybulketname/*"
        }
    ]
}


text:
Q: Adding a custom CA Root certificate to GCloud utility (or Python generally) on Windows I'm using gcloud on Windows to develop GAE stuff. The network here has a MITM root certificate by design so all SSL traffic can be snooped; I can install the root cert easily into a browser or Windows certificate store, but can't successfully get this work for Python, or more specifically, gcloud (which has its own Python bundled). The answers at How to add a custom CA Root certificate to the CA Store used by Python in Windows? don't work - I've tried setting SSL_CERT_DIR and SSL_CERT_FILE environment variables to no avail, and the pip.ini solution isn't applicable as I'm not using pip.

A: Assuming all your credential setup is in order, for MITM you likely also need to set proxy settings, for instance
gcloud config set proxy/address 127.0.0.1
gcloud config set proxy/port 8080
gcloud config set proxy/type http

replacing address/port for your MITM and then either one of these:
gcloud config set auth/disable_ssl_validation  True

or
gcloud config set core/custom_ca_certs_file cert.pem

Test by running some command, for example
gcloud projects list

You can use --log-http additional gcloud flag and/or tools like burp to further debug what certs/proxies are being used.

A: The previous answer works for gcloud, but does not work with gsutil. gsutil currently ignores whatever value for ca certificates you have in the gcloud config, so you must add it to your boto config file. (on a gcp instance it's /etc/boto.cfg). Add these lines:
   [Boto]
   ca_certificates_file = /path/to/cert.pem


text:
Q: How can I show a image preview in the browser without uploading the image file to the server? In my application I want that when a user uploads an image file then I want to show the user the image immediately before submitting the form. This is so that they can preview the image before they submit the form.
Is there any way in HTML5 that the file uploader can show the image on the client side before the actual form is submitted?
I want to allow the user to preview the image file without uploading the file to the server (so no uploading to the temp directory either), but somehow just show the image on the client side in the client browser.

A: It sure is possible with the HTML5 File API.

A: Since this was the first result for google("html5 image preview"), I thought I'd flesh out a contentful answer.  I hope it's helpful.
<img id="preview" src="placeholder.png" height="100px" width="100px" />
<input type="file" name="image" onchange="previewImage(this)" accept="image/*"/>
<script type="text/javascript">
  function previewImage(input) {
    var preview = document.getElementById('preview');
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        preview.setAttribute('src', e.target.result);
      }
      reader.readAsDataURL(input.files[0]);
    } else {
      preview.setAttribute('src', 'placeholder.png');
    }
  }
</script>


text:
Q: Objective-C: atomic property is fully retrieved With regards to atomic property, Apple's documentation has this below:

This means that the synthesized accessors ensure that a value is
  always fully retrieved by the getter method or fully set via the
  setter method, even if the accessors are called simultaneously from
  different threads.

What does "fully retrieved" or "fully set" mean?
Why is "fully retrieved" or "fully set" not enough to guarantee thread safety?
Note: I am aware there are many posts regarding atomicity on SO, please don't tag this as duplicate unless the ticket specifically address the question above.  After reading the posts, I still do not fully understand atomic property.

A: Atomic means that calls to the getter/setter are synchronized. That way if one thread is setting the property at the same time as another thread is getting it, the one getting the property is guaranteed to get a valid return value. Without it being atomic, it would be possible that the getter retrieves a garbage value, or a pointer to an object that is immediately deallocated. When it's atomic, it will also ensure that if two threads try to set it at the same time, one will wait for the other to finish. If it weren't atomic and two threads tried to set it at the same time, you could end up with a garbage value being written, or possibly objects being over/under retained or over/under released.
So basically, if the property is being set, any other calls to set it or get it will wait for the method to return. Same for if the property is being gotten, any other calls to get it or set it will wait until that get finishes.
This is sometimes sufficient for thread safety depending on what it's being used for. But often you want more than this level of synchronization for thread safety. For example if one block of code on a thread gets the value, makes some change to it, and wants to set it again without some other thread changing it in the meantime. You would have to do additional synchronization to make sure that you have a lock on it from before you get it until after you subsequently set it. You would want to do the same if you wanted to get an object and make some changes to that object without another thread trying to make changes at the same time on it.

A: "Fully set" and "fully retrieved" means the code below will always print "0x11111111" or "0x22222222". It will never print things like "0x11112222" or "0x11221122". Without atomic or some other appropriate thread synchronization, those sorts of partial reads or partial updates are allowed for some data types on some CPU architectures.
// Thread 1
while (true) x = 0x11111111;

// Thread 2
while (true) x = 0x22222222;

// Thread 3
while (true) printf("0x%x\n", x);

A: It means the value will never be accessed when it's halfway through being written. It will always be one intended value or another, never an incompletely altered bit pattern.
It isn't enough to guarantee thread-safety because ensuring that the value of a variable is either fully written or nor written at all is not enough to make all the code that uses that variable thread-safe. For example, there might be two variables that need to be updated together (the classical example is transferring credits from one account to another), but code in another thread could see one variable with the new value and one with the old.
Very often, you'll need to implement synchronization for whole systems, so the guarantees offered by atomic variables end up almost not mattering a lot of the time.


text:
Q: How to show global header(array type) parameter in Swagger UI I use springfox swagger ui of version 2.9.2. I want to display a header in all the APIs and I followed the example as shown here. The example worked with header parameter of type String. However, I require a header parameter of type array of strings.
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.xyz"))
        .paths(PathSelectors.regex("/.*"))
        .build()
        .apiInfo(apiInfo())
        .globalOperationParameters(getParameters());
}

private List<Parameter> getParameters() {
    ParameterBuilder parameterBuilder = new ParameterBuilder();
    List<Parameter> parameterList = new ArrayList<>();

    parameterList.clear();
    parameterBuilder.name("testHeader").modelRef(new ModelRef("String"))
        .allowMultiple(true).parameterType("header").required(true).build();
    parameterList.add(parameterBuilder.build());
    return parameterList;
}

How do I get a header of type array in UI? Right now this renders a single text box in UI for the testHeader.


text:
Q: Cosine series as a Fourier series. Theorem:
Let $a_{n}\downarrow 0$ and suppose that $\left(a_{n}\right)$ is a
      quasi-convex. Then $\displaystyle \frac{a_{0}}{2}+\sum a_{n}\cos nx$ is the Fourier series of the $L^{1}$ function $\displaystyle f(x)=\sum_{n=0}^{\infty}(n+1)\Delta ^{2}a_{n}\frac{1}{2} K_{n}(x),
      x\not \equiv 0 \pmod {2\pi} $. Further, $S_{N}(x)\to f(x)$ except at $x\equiv 0 \pmod {2\pi}$, where $\displaystyle S_{N}(x)=\frac{a_{0}}{2}+\sum_{n=1}^{N}a_{n}\cos nx$.
Proof:
 First we see that if $ x \not\equiv 0\pmod {2\pi}$ then
       $\displaystyle \sum_{n=0}^{\infty}(n+1)\Delta ^{2}a_{n}\frac{1}{2} K_{n}(x) < +\infty $.
Indeed,
\begin{equation*}
\begin{split}
  \left|(n+1)\Delta ^{2}a_{n}K_{n}(x_{0})\right| &=\left|n+1\right|\left|\Delta ^{2}a_{n}\right|\left|K_{n}(x_{0})\right|\\ &\leq \left|n+1\right|\left| \Delta ^{2}a_{n}\right|\text{cosec}^{2}\frac {x_{0}}{2} \\
&<+\infty \left(\because \sum_{n=0}^{\infty}(n+1)\left|\Delta^{2}a_{n}\right|<+\infty \right)
\end{split}
\end{equation*}
$\therefore f(x)$ is well-defined everywhere except at $x\equiv 0\pmod {2\pi}.$
We now show that $f\in L^{1}$.
Let $\displaystyle t_{N}(x) =\sum_{n=0}^{N}(n+1)\Delta ^{2}a_{n}\frac{1}{2}K_{n}(x).$
Now, $t_{N}(x)\rightarrow f(x)$ a.e.
$\therefore \left|t_{N}(x)\right| \rightarrow \left|f(x)\right|$ a.e.
By Fatou's lemma,
\begin{equation*}
\begin{split}
\therefore \frac{1}{\pi}
\int_{-\pi}^{\pi}\left|f(x)\right|dx               &\leq \frac{1}{\pi}\lim_{N\to\infty} inf \int_{-\pi}^{\pi}\left|t_{N}(x)\right|dx\\
                                                   &\leq \frac{1}{\pi}\lim_{N\to\infty}inf\int_{-\pi}^{\pi}\frac{1}{2}\sum_{n=0}^{N}(n+1)\left|\Delta ^{2}a_{n}\right|\left|K_{N}(x)\right|dx\\
                                                   &=\frac{1}{2}
                                                   \lim_{N\to\infty}inf \left[\sum_{n=0}^{N}(n+1)\left|\Delta ^{2}a_{n}\right|\right]\\
                                                   &=\frac{1}{2}
                                                  \sum_{n=0}^{\infty}(n+1)\left|\Delta^{2}a_{n}\right| \\
                                                   &<+\infty .
\end{split}
\end{equation*}
$\therefore f\in L^{1}$.
We now show that $\|t_{N}-f \|_{1} \rightarrow0$ as $N \to \infty$.
\begin{equation*}
\begin{split}
\left|t_{N}(x)-f(x)
\right|         &=\left|\sum_{n=N+1}^{\infty}
(n+1)\Delta^{2}a_{n}\frac{1}{2}K_{n}(x)\right|\\
                &\leq \sum_{n=N+1}^{\infty}\left|(n+1)\Delta^{2}a_{n}\frac{1}{2}K_{n}(x)\right|\\
\therefore \left\|t_{N}-f\right\|_{1}
                &\leq  \left\|\sum_{n=N+1}^{\infty}\left|(n+1)\Delta^{2}a_{n}\frac{1}{2}K_{n}(x)\right| \right\|_{1}\\
                &\leq\sum_{n=N+1}^{\infty}(n+1)\left|\Delta^{2}a_{n}
                \right|\frac{1}{2}
                 \rightarrow 0\;{\text {as}}\; N\to\infty.\ (\because \|K_{n}\|_{1}=1.)
\end{split}
\end{equation*}
$\therefore \left\|t_{N}-f\right\|_{1} \rightarrow 0$ as $N\to\infty $.
Next we show that $S_{N}(x)\to f(x),$ for $x\not\equiv 0 \pmod{2\pi}.$
Now, $\displaystyle S_{N}(x)=\frac{a_{0}}{2}+\sum_{n=1}^{N}a_{n}\cos nx. $
$\displaystyle \therefore S_{N}(x) =\sum_{n=0}^{N}a_{n}b_{n}(x)$ where
$b_{n}(x)=
\begin{cases}
\cos nx     & ,n\neq0\\
\frac{1}{2} & ,n=0 .
\end{cases}$
Applying partial summation formula twice, we get,
\begin{equation*}
\begin{split}
S_{N}(x) &= a_{N}\frac{1}{2}D_{N}(x)+\sum_{n=0}^{N-1}\Delta a_{n}\frac{1}{2} D_{N}(x)\\
         &=a_{N}\frac{1}{2}D_{N}(x)+\frac{1}{2}\left[\Delta a_{N-1}N K_{N-1}(x)+\sum_{n=0}^{N-2}\Delta^{2}a_{n} (n+1)K_{n}(x)\right].
\end{split}
\end{equation*}
Now for fixed $x\not\equiv 0\pmod {2\pi},\ D_{n}(x)\; \text{and} \; K_{n}(x)$ are bounded sequence of numbers.
Since $(a_{n})$ is convex,
$ N\Delta a_{N}\to 0$ as $N\to \infty $. Also $a_{n}\to 0$.
$\displaystyle \therefore \lim_{N\to\infty} S_{N}(x)=f(x)$.
It remains to show that the series $\displaystyle \frac{a_{0}}{2}+\sum_{n=1}^{\infty}a_{n}\cos nx$ is a Fourier series of $f(x)$.
Here $\displaystyle S_{N}(x)=\frac{a_{0}}{2}+\sum_{n=1}^{N}a_{n}\cos nx.$
\begin{equation*}
\begin{split}
\therefore \frac{1}{\pi}\int_{-\pi}^{\pi}S_{N}(x)\cos kx dx
&= \frac{1}{\pi}\int_{-\pi}^{\pi}\left[\frac{a_{0}}{2}+\sum_{n=1}^{N}a_{n}\cos nx\right]\cos kx dx.\\
&=a_{k}.
\end{split}
\end{equation*}
But $S_{N}(x)\to f(x)$ as $N\to\infty$.
$\displaystyle \therefore a_{k}=\frac{1}{\pi}\int_{-\pi}^{\pi}f(x)\cos kx dx.$
Now, $\displaystyle f(x)=\sum_{n=0}^{\infty}(n+1) \Delta^{2}a_{n}\frac{1}{2}K_{n}(x),$ which is an even function. ($\because K_{n}(x)$ is an even function.)
$\therefore b_{k}=0.$
Am i right? If i am doing any mistake then please suggest me! Thanks in advance!


text:
Q: Setting background color of android actionbar I am operating with the compatibility library v7.
I am just trying to set the color of my actionbar (for Android 2.1 and above - though I run Android 4.4.2) to a solid color.
However the color does not change. It remains the same.
I have also tried creating a solid drawable with the color but that also does not change.
Finally I tested if I could change the backgroudn of my layout and I could - it must be something about the actionbar background which I'm not getting.
Here is the code:
    <?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="CustomActionBarTheme"
           parent="@style/Theme.AppCompat.Light.DarkActionBar">

        <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
    </style>

    <style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar">

         <item name="android:background">#0000ff</item>

    </style>
</resources>

A: This seems to work for me. Try to use a resource instead of a raw value.
<style name="app_theme" parent="@android:style/Theme.Holo">
    <item name="android:actionBarStyle">@style/app_action_bar</item>
</style>

<style name="app_action_bar" parent="@android:style/Widget.Holo.ActionBar">
    <item name="android:background">@color/google_lightest_gray</item>
    <item name="android:icon">@android:color/transparent</item>
    <item name="android:windowActionBarOverlay">false</item>
</style>

A: use getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#808080"))); in Activity   extends SherlockActivity or the color as your wish :)

A: You can use:
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.color.colorname));

A: use the following code getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_bg_color.xml));
actionbar_bg_color.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
      <solid android:color="@color/actionbar_bg"/>  <!-- set desired #0000ff color in color.xml
 you can use here solid color as well as gradient -->
 </shape>

hope this help you

A: I solved it by:

*

*Properly installing the support-v7-appcompat library.My mistake.

*Shifting the styling to the res/values/styles.xml files for each version, i.e. one for backwards compatibility and one for values-v11.

I don't know why I couldnt get the result I wanted within themes.xml.
If anyone has an answer I'd be grateful


text:
Q: Running Cboden Ratchet Websocket on the server I made a chat service on my local machine and successfully ran it.
This chat service uses cboden retchat library and the custom JS on frontend.
So I uploaded everything on the CENTOS server and tried to run the chat.
I'm getting connection refused error. But I checked server firewall, opened ports (I changed the port from 8080 to 60000).
I tried to run server on this target:
0.0.0.0:60000

and connect from client like this
SERVERIP:60000

or
DOMAIN:60000

Tried to run server also as ROOT, but I get the same error.
Is it client firewall problem? How I fix it? I found a JS package, which connects to the chat server via 80 port and there is no firewall problems. I cannot use this package, because on our server we have one hundred services ran. So I decided to use the 60000 port.
I checked the port- it's free and unblocked.
My .env file
CHAT_PROTOCOL=wss://
CHAT_ADDRESS=0.0.0.0
CHAT_PORT=60000

Client side JS
 var conn = new WebSocket(chat.protocol + SERVERIP +':'+ chat.port +'/chat');
//chat.protocol is wss://
//chat.port is 60000

Here is the problem

WebSocket connection to 'wss://SERVERIP:60000/chat' failed: Error in
  connection establishment: net::ERR_CONNECTION_REFUSED

Again, it was perfect on my local machine (ubuntu)

A: I found the solution after 5 month.
My domain uses SSL connection so I should to include the CRT and KEY files by declaring the server variable.
const server =
     require('https').createServer({
        key: fs.readFileSync('./ssl/keys/************************.key'),
        cert: fs.readFileSync('./ssl/certs/************************.crt'),
        ca: fs.readFileSync('./ssl/certs/************************.crt'),
        requestCert: false,
        rejectUnauthorized: false
    },express);


text:
Q: MVC: One model, multiple applications I am starting a project based on multiple webapplications (Website, ControlPanel, RestAPI) each based on the same Data[bases] and an MVC framework.
To avoid parallel code maintenance I thought of having the same model-files for each app. But when thinking deeper all possible approaches have some pro's and con's. I thought I'd ask some experts.
Possible ways to go (I know of) :

1. Plugin ~one4all
The very core of logic encapsuled as a plugin which is deployed in
each app.
++ Only one model per table for all apps
-- One bug can crash 4 apps
-- lots of unused code per app

2. Duplicated code ~all4one
Double maintenance of duplicated model files.
++ Bugs affect only one app
++ Models does not contain unused code
-- Inefficient development

3. Api between apps ~lonewolves
Apps get its data from an api.
++ one code serves all apps
-- uncommon approach
-- massive overhead

4. Models symlinked ~lazy1
One application holds the model files, the other apps will
symlink/include it.
++ almost no extra work to do
+- seems hilarious
-- one bug affects all apps
-- could restrict debugging

Are there more possible approaches? Which one is common/recommended?
I don't want to combine the functionality of all apps into one to avoid crashing the whole thing with one pull.
More approaches and ideas are very welcome. Thank you in advance.

A: Implement SOLID in proyect. Valid all framework.

A: One option you missed is to keep the projects as one. Instead of splitting the model, and thus maintaining it across three or more separate projects, you could make only one project, and just divide the portions with controllers. Although this method can create a monster of a project, it can also be kept in one place, and many controllers can divide the project down into easily managed pieces.
If it were me, and I wanted to keep the projects as separate cakephp projects, I would probably end up duplicating code. It's not that bad to copy and paste. That's what I do on a website that I work on, in order to separate testing and production.
Although, I would also probably try including separate files, which contain the same code. Even though you are using cakephp, you can also use php code. What if you require() files that contain cakephp logic. Not sure if this works, but I would at least give it a try.


text:
Q: phpredis Redis::subscribe() expects parameter 2 to be a valid callback I'm having trouble to use the subscribe method. Any help would be welcome in order to get it working. Following php unit test gives me the following error.
This is the example as phpredis provides it.
https://github.com/nicolasff/phpredis#subscribe
Redis::subscribe() expects parameter 2 to be a valid callback, function 'f' not found or invalid function name

/myproj/test/RedisEventBusTest.php:37

RedisEventBusTest.php
<?php

namespace bkcqrs\eventing;

use bkcqrs\DefaultDomainEvent;
use bkcqrs\serializing\JsonSerializer;

class RedisEventBusTest extends \PHPUnit_Framework_TestCase
{
    private $redisEventBus;
    private $redisSubscribeClient;

    public function setUp()
    {
        $serializer = new JsonSerializer();
        $this->redisEventBus = new RedisEventBus($serializer);
        $this->redisSubscribeClient = new \Redis();
    }

    public function it_publishes_the_event_on_redis()
    {
        $notificationCountChangedEvent = new NotificationCountChangedEvent(array('userId' => 6, 'count' => 21));
        function f($redis, $channel, $msg)
        {
            var_dump($msg);
            $notification = json_decode($msg);
            var_dump($notification);

            $this->assertEquals($notification["userId"], $notificationCountChangedEvent->userId);
            $this->assertEquals($notification["count"], $notificationCountChangedEvent->count);
        }

        $this->redisSubscribeClient->subscribe(array("NotificationCountChanged"), 'f');
        $this->redisEventBus->publish($notificationCountChangedEvent);
    }
}

class NotificationCountChangedEvent extends DefaultDomainEvent
{
    public $userId;
    public $count;
}

A: One of the following 2 approaches does work.
A) $client->subscribe($channels, function($r, $c, $m){});
B) $f = create_function($parms, $functionBody); $client->subscribe($channels, $f);


text:
Q: Continue to play audio even if the screen is locked I am just messing around with an app that streams audio and I wanted to give it a feature similar to Pandora/Google Music/etc where if you press home or lock the screen the audio continues to play in the background.
How exactly can I accomplish this? Is it through a broadcast receiver or a service? If I knew more closely what I was looking for Google would be more helpful.
Thanks!

A: It's a service.  Anytime you want to do something that takes a lot of time like playing music, downloading a lot of data from a server, etc. it should be a service.  The basic technique is to always have the service play the music and then have your activity connect to it to show the status and update the tracks, etc.