text:
Q: Echoing HTML with PHP causing syntax error due to quotes I'm using knockout.js with PHP and I'm trying to make a GET request which then returns an HTML/knockout form. The reason for doing this is because the form will be used by others, and rather than copying/pasting a rather large chunk of code, it's simply less code just to make a request to my server which returns the HTML/knockout.
//code on another server to request form from my server
$.ajax({
      //request here
    })
</script>

Now, this is the code on my server. Where the issue lies is that since I have to echo using php and I'm returning text, I need to use either a single or double quote around the text I'm echoing. However, I'm using knockout.js and a knockout.js validation addon which requires both single and double quotes, essentially canceling out the quotes wrapping the echo.
For example,
 <?
    if($_GET['something']){
       echo '

            Full Name

            <input type="text" data-bind="value: fullName, valueUpdate: 'afterkeydown'"/>

       ';
     }
 ?>

The line that is specifically causing the problem is
<input type="text" data-bind="value: fullName, valueUpdate: 'afterkeydown'"/>

Which the error returned is
Parse error: syntax error, unexpected 'afterkeydown' (T_STRING)

When I echo I use single quotes because I want to return it as text, however, within that I need to use single and double quotes for different elements. IS there a way around this?

A: try this -
<?
    if($_GET['something']){
       echo '

            Full Name

            <input type="text" data-bind="value: fullName, valueUpdate: \'afterkeydown\'"/>

       ';
     }
 ?>

A: you need to escape them
echo '

        Full Name

        <input type="text" data-bind="value: fullName, valueUpdate: \'afterkeydown\'"/>

   ';

A: PHP is an hypertext preprocessor, you can write raw HTML without using echo [and getting such quote nightmares]:
<?php if($_GET['something']): ?>

    Full Name

    <input type="text" data-bind="value: fullName, valueUpdate: 'afterkeydown'"/>

<?php endif; ?>

[see how SO syntax highlighting works fine now!]
BTW,  tag is deprecated since HTML 4.

A: whenever you have text like this:
TEXT 'LIKE' THIS
and you want to echo it, just prefix the ' with a \:
echo 'asdfadsf\'asdfasdf'
so in your case:
echo '

    Full Name

    <input type="text" data-bind="value: fullName, valueUpdate: \'afterkeydown\'"/>

';


text:
Q: Simple example of a ring which is normal but not CM I try to keep a list of standard ring examples in my head to test commutative algebra conjectures against. I would therefore like to have an example of a ring which is normal but not Cohen-Macaulay. I've found a few in the past, but they were too messy to easily remember and use as test cases. Suggestions?

A: Segre products of normal CM N-graded K-algebras A, B are always normal (since they're direct summands of the normal ring A\otimes_K B), but rarely CM.
A particular example is here:
http://www.math.purdue.edu/~walther/research/segre.ps
or also here:
http://www.mathstat.dal.ca/~faridi/research/enescu-faridi.pdf   (Corollary 35)
Take A=k[x,y,z]/x^3+y^3+z^3 to be the Fermat cubic, and B=k[a,b]. Then the Segre product A#B is not CM, since the a-invariant of A is non-negative.

A: Another family of examples is given by the homogeneous coordinate rings of
irregular surfaces (ie  2-dimensional $X$ such that $H^1({\mathcal O}_X) \neq 0$);
these surfaces cannot be embedded in any way so that their homogeneous coordinate rings
become Cohen-Macaulay. Elliptic scrolls (such as the one in the previous answer)
 and Abelian surfaces in P4, made from the sections of the Horrocks-Mumford bundle, are such examples.
The point is that sufficiently positive, complete embeddings of any smooth variety (or somewhat more generally) will have normal homogeneous coordinate rings, and they will be Cohen-Macaulay iff the intermediate cohomology of the variety vanishes. All the examples above fall into this category. It's an interesting general question to ask how positive is "sufficiently positive".

A: MJ Bertin en Anneaux d'invariantes d'Anneaux de polynômes, en caractéritique p . C.R.Acad.Sci.Paris Sér. A-B 264 1967 A653-A656
"... MJ Bertin has made use of Galois descent in order to construct an example of a factorial noetherian ring wich is not Cohen Macaulay..." Robert M. Fossum
The example is done completly in The Divisor Class Groups of a Krull Domain, Robert Fossum, Example 16.7 pages 87-88

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apache Camel split runs in parallell with ThreadPool, why? I have a camelRoute that should use a threadPool in a split to do parallell work. My problem is that i always end up with one thread too much because the split will run one thread and the threadpool the specified amount of threads. I would like the threadpool to cap the amount of threads.
Anyone can see why this happens? Route and camel-context below... (other values in code, like from and id etc, but cant show that here...)
from(FROM_ENDPOINT)
    .routeId(ID)
    .split(body(), new GroupedExchangeAggregationStrategy())
    .executorServiceRef("ThreadPool")
    .bean(bean, "beanMethod")
    .end()
    .bean(bean)
    .multicast()
    .to(TO_ENDPOINT);

The ThreadPool is configured like so in my camel-context.xml:
<camel:camelContext id="application-context" useMDCLogging="true" xmlns="http://camel.apache.org/schema/spring">
    <propertyPlaceholder id="properties" location="ref:props"/>
    <routeBuilder ref="refToRoute"/>
    <threadPoolProfile id="ThreadPool" maxPoolSize="2"
                       maxQueueSize="-1" poolSize="2"/>
</camel:camelContext>

A: The splitter needs one background thread to orchestrate the parallel work. So you have the threads from the thread pool + one extra thread with the name Splitter-AggregateTask.
So if you want a total max of 10, then set the thread pool size to be 9, so you have room for that 1 background thread also.


text:
Q: Trying to add y values to my bars using matplotlib Can someone help me add Y-values to my bars. I have tried but no luck.
And what would you recommend to make this code look cleaner? I feel like it can be improved but I'm still in the learning stage.
import matplotlib.pyplot as plt
import numpy as np

#style
plt.style.use("seaborn-colorblind")

# bar width
bar_width = 0.25

# data
months = ['April', 'May', 'June']
application = [18, 44, 7]
infrastructure = [27, 36, 20]

# convert months to array
months_array = np.arange(len(months))

# y labels
plt.ylabel('# of Errors\n', fontsize=14, fontweight='bold')

# add minor ticks on y axis
yticks = np.arange(0,45,5)
plt.yticks(yticks)

# graph title
plt.title("Fatal Errors from April 23rd - June 11th", fontsize=18,            fontweight='bold')

# bars names
plt.xticks(months_array + bar_width-0.125, months, fontweight='bold')

# bars
plt.bar(months_array, application, width=bar_width, color='#5cbae6',     edgecolor='white', label='Application')
plt.bar(months_array + bar_width, infrastructure, width=bar_width,     color='#b6d957', edgecolor='white', label='Infrastructure')

# legend
plt.legend()

# show graph
plt.show()

This is what I currently have:
Click here for picture
But I want something like this without percentage and values inside the bars:
Click here for picture - not my picture


text:
Q: How to pass a search model into angular $http.get how do I do this without manually specifying the url by building a string
var memberSearchModel = {
        SearchBy: "Name",
        SearchValue: "jaredites"

    };
    dataFactory.getMembers = function () {
        return $http.get(urlBase + '/' + memberSearchModel);
    };

A: First parameter is the url, second is the data:
var memberSearchModel = {
    SearchBy: "Name",
    SearchValue: "jaredites"

};
dataFactory.getMembers = function () {
    return $http.get(urlBase, memberSearchModel);
};

See $http.get docs


text:
Q: Can you index subqueries? I have a table and a query that looks like below. For a working example, see this SQL Fiddle.
SELECT o.property_B, SUM(o.score1), w.score
FROM o
INNER JOIN
(
    SELECT o.property_B, SUM(o.score2) AS score FROM o GROUP BY property_B
) w ON w.property_B = o.property_B
WHERE o.property_A = 'specific_A'
GROUP BY property_B;

With my real data, this query takes 27 seconds. However, if I first create w as a temporary Table and index property_B, it all together takes ~1 second.
CREATE TEMPORARY TABLE w AS
SELECT o.property_B, SUM(o.score2) AS score FROM o GROUP BY property_B;

ALTER TABLE w ADD INDEX `property_B_idx` (property_B);

SELECT o.property_B, SUM(o.score1), w.score
FROM o
INNER JOIN w ON w.property_B = o.property_B
WHERE o.property_A = 'specific_A'
GROUP BY property_B;

DROP TABLE IF EXISTS w;

Is there a way to combine the best of these two queries? I.e. a single query with the speed advantages of the indexing in the subquery?
EDIT
After Mehran's answer below, I read this piece of explanation in the MySQL documentation:
As of MySQL 5.6.3, the optimizer more efficiently handles subqueries in the FROM clause (that is, derived tables):
...
For cases when materialization is required for a subquery in the FROM clause, the optimizer may speed up access to the result by adding an index to the materialized table. If such an index would permit ref access to the table, it can greatly reduce amount of data that must be read during query execution. Consider the following query:
SELECT * FROM t1
  JOIN (SELECT * FROM t2) AS derived_t2 ON t1.f1=derived_t2.f1;

The optimizer constructs an index over column f1 from derived_t2 if doing so would permit the use of ref access for the lowest cost execution plan. After adding the index, the optimizer can treat the materialized derived table the same as a usual table with an index, and it benefits similarly from the generated index. The overhead of index creation is negligible compared to the cost of query execution without the index. If ref access would result in higher cost than some other access method, no index is created and the optimizer loses nothing.

A: First of all you need to know that creating a temporary table is absolutely a feasible solution. But in cases no other choice is applicable which is not true here!
In your case, you can easily boost your query as FrankPl pointed out because your sub-query and main-query are both grouping by the same field. So you don't need any sub-queries. I'm going to copy and paste FrankPl's solution for the sake of completeness:
SELECT o.property_B, SUM(o.score1), SUM(o.score2)
FROM o
GROUP BY property_B;

Yet it doesn't mean it's impossible to come across a scenario in which you wish you could index a sub-query. In which cases you've got two choices, first is using a temporary table as you pointed out yourself, holding the results of the sub-query. This solution is advantageous since it is supported by MySQL for a long time. It's just not feasible if there's a huge amount of data involved.
The second solution is using MySQL version 5.6 or above. In recent versions of MySQL new algorithms are incorporated so an index defined on a table used within a sub-query can also be used outside of the sub-query.
[UPDATE]
For the edited version of the question I would recommend the following solution:
SELECT o.property_B, SUM(IF(o.property_A = 'specific_A', o.score1, 0)), SUM(o.score2)
FROM o
GROUP BY property_B
HAVING SUM(IF(o.property_A = 'specific_A', o.score1, 0)) > 0;

But you need to work on the HAVING part. You might need to change it according to your actual problem.

A: I am not really that familiar with MySql, I mostly worked with Oracle.
If you want a where-clause in the SUM, you can use decode or case.
it would look something like that
SELECT o.property_B, , SUM(decode(property_A, 'specific_A', o.score1, 0), SUM(o.score2)
FROM o
GROUP BY property_B;

or with case
SELECT o.property_B, , SUM(CASE
                            WHEN property_A = 'specific_A' THEN o.score1
                            ELSE 0
                            END ),
SUM(o.score2)
FROM o
GROUP BY property_B;

A: I do not see why you would need the join at all. I would assume that
SELECT o.property_B, SUM(o.score1), SUM(o.score2)
FROM o
GROUP BY property_B;

should give what you want, but with a much simpler and hence better to optimize statement.

A: It should be the duty of MySQL to optimise your query, and I don't think there is a way to create an index on the fly. However, you can try to force the use of the index of property_o (if you have it). See http://dev.mysql.com/doc/refman/5.1/en/index-hints.html
Also, you can merge the create and alter statements, if you prefer.


text:
Q: Prove that $\lim_{n\to\infty} \frac{\log n}{n} = 0$ I want to show the above problem I already write in the title by using the following equality:
$\lim_{n\to\infty} \frac{a^n}{n} = \infty$ if $a>1$.
I tried to solve this problem by seeing the sequence as a function. But, I want to know by only seeing sequences. Please help!

A: Hint: Set $a=e$ and $n=\log(m)$.

A: Hint: You have ${{log(a^n)}\over {a^n}}= {n\over{a^n}}log(a)$.

A: It is much simpler than that:  prove that for all $x\ge 1$, $\ln x<2\sqrt x$.


text:
Q: Should I place class file *.cs in root folder of a project when I use Vs 2019 (Microsoft Visual Studio Community 2019)? When I use Vs 2012 Express edition to create a website , I remember I should place the class file *.cs  in the system folder \App_Code, and Vs 2012 can compile these files automatically. It's OK.
When I use Vs 2019 (Microsoft Visual Studio Community 2019), I find the  the class file *.cs  in the system folder \App_Code can't be compiled automatically, I have to set it by myself, you can see Image A.
But if I place  the class file *.cs in  in root folder of a project , they can be compiled automatically, it seems that Vs 2019 set Compile option as default,  you can see Image B.
Is is a bad way to place the class file *.cs  in the system folder \App_Code when I use Vs 2019 ?
Image A

Image B

A: It is not good or bad to place a class file *.cs in the system folder App_Code when you use VS2019 or some other VS, it depends on your goal for those files.
TLDR: put non user control sources in App_Code if you need server-side behavior (on the fly updates), but don't mark its build action as compile but rather content, and therefore forget about benefiting from IntelliSense.
For a website project, you have the special folders Bin and App_Code, for code shared between pages. Files inside App_Code do not have to be source code, it can be a content file. Files inside are handled by asp.net in special ways (1).
Source code inside App_code and subfolders are automatically compiled at runtime. When the website is running, you can update those source code, and they will be recompiled on the fly, just like Live unit testing in VS (1). This will happen when the website is running on the server too (2).

The App_Code folder and its special status in an ASP.NET Web
application makes it possible to create custom classes and other
source-code-only files and use them in your Web application without
having to compile them independently. (1)

But

User controls are not allowed in the App_Code folder. This includes
both single-file user controls and user controls that use the
code-behind model. Putting a user control .in the App_Code directory
causes the user control's code to be compiled out of its required
sequence and therefore is not allowed. Note that user controls do not
need to be in the App_Code folder; they are already available to pages
anywhere in the application. (1)

I add that you should not add source code in App_Code and leave it marked compile as build action, because then it will be both compiled by VS and asp.net, leading to duplicate references. Instead, leave it as content, but then IntelliSense won't see them as source code. (2)
Vishal R Joshi (2) gives the piece of advice:

You can add code files under any folder call it "CodeFolder",
"Controllers" or anything that makes sense in your project… Just avoid
putting them under "App_Code" unless you specifically want the server
side compilation behavior… (2)

References:

*

*Shared Code Folders in ASP.NET Web Sites

*App_Code folder doesn't work with Web Application Projects (WAPs)


text:
Q: mariasql how to get values from table and insert into another table hello first off sorry for bad explain but ill try my best
so im having 2 table
table 1 = sb_admins and
has COLUMNS =
 1. aid (AUTO_INCREMENT)
 2. user
 3. auth
 4. passoword
 5. gid
 6. email

table 2 = sb_admins_servers_groups and
has COLUMNS =
 1. admin_id
 2. group_id
 3. srv_group_id
 4. server_id

I need to get values from aid to admin_id with a INSERT INTO
what i have try but failed
INSERT INTO sb_admins_servers_groups (admin_id, group_id, srv_group_id, server_id)
SELECT aid FROM sb_admins

A: INSERT
INTO        sb_admins_servers_groups (
              admin_id,
              group_id,
              srv_group_id,
              server_id
            )
VALUES (
  (
    SELECT    aid
    FROM      sb_admins
    WHERE     authid = '{steamid}'
  ),
              '1',
              '1',
              '-1'
)


text:
Q: Select custom strings and values without fields SQL I wonder how I can select custom values in SQL. I understand this is easy with MS SQL, but is it doable with PHPMyAdmin?
SELECT field1, 0 as answers FROM table

// "answers" should contain 0

The problem is that 0 is interpreted as a field, which it isn´t; it´s just a value I want to store in "answers".
Thanks for your help!

A: If you want a constant, this should work:
SELECT field1, '0' as answers FROM table

A: In MsSql
SELECT 'my value' AS COL1

or in Oracle for example
SELECT 'my value'FROM DUAL


text:
Q: React Native Maps: why are directions going off-road when origin and destination are far apart? I'm using react-native-maps and react-native-maps-directions in my React Native app, and the route it's drawing isn't following the streets, as shown below:

This is my code:
<MapView
    provider={PROVIDER_GOOGLE}
    style={styles.map}
    region={{
        latitude: this.state.latitude,
        longitude: this.state.longitude,
        latitudeDelta: this.state.latitudeDelta,
        longitudeDelta: this.state.longitudeDelta,
    }}
>
    <MapViewDirections
        origin={origin}
        destination={destination}
        apikey={GOOGLE_MAPS_APIKEY_IOS}
        strokeWidth={3}
        strokeColor='hotpink'
    />
</MapView>

What I notice is that this occurs when origin and destination are far apart, but not when they're close together. In the example in the image, they're about 1300km apart.
Does anyone know how I can approach fixing this?

A: fetch(`https://maps.googleapis.com/maps/api/directions/json?origin=[ORIGIN]&destination=[DESTINATION]&mode=driving&key=[YOUR API]`)
.then(res => {return res.json()})
.then(result => {
   let path = []
   result..routes[0].legs[0].steps.map(step => {
      polyline.decode(step.polyline.points).map(step => {
         path.push({latitude:step[0],longitude:step[1]})
      })
   })
   console.log(path) //You should see all of the lat & lng at this point
})

<Polyline coordinates={path} />

//edit stroke styles and you should see polyline, the way you want to see.
//NOTE: You need to install @mapbox/polyline using npm

A: you need to add precision attribute like below.
    <MapViewDirections
      optimizeWaypoints={true}
      origin={origin}
      waypoints={waypoints}
      destination={dest}
      apikey={MAP_API_KEY}
      strokeColor={'hotpink'}
      strokeWidth={3}
      onReady={res => { console.log(res) }}
      precision="high"
    />

precision value is low by defaulte. just change it to high it will show the path on road.


text:
Q: Cache Issue on HttpWebRequest vb.net I need away to disable chaching for my VB.NET code.  I've found some hints in C#, but nothing that I can get to work.
Right now, when i send in a request, i'm getting the previous request results.
Here's my code:
        Dim responseData As String = ""
        Try
            Dim cookieJar As New Net.CookieContainer()
            Dim hwrequest As Net.HttpWebRequest = Net.WebRequest.Create(URL)
            hwrequest.CookieContainer = cookieJar
            hwrequest.Accept = "*/*"
            hwrequest.AllowAutoRedirect = True
            hwrequest.UserAgent = "http_requester/0.1"
            hwrequest.Timeout = 60000
            hwrequest.Method = method

            'hwrequest.CachePolicy = CachePolicy

            If hwrequest.Method = "POST" Then
                hwrequest.ContentType = "application/x-www-form-urlencoded"
                Dim encoding As New Text.ASCIIEncoding() 'Use UTF8Encoding for XML requests
                Dim postByteArray() As Byte = encoding.GetBytes(POSTdata)
                hwrequest.ContentLength = postByteArray.Length
                Dim postStream As IO.Stream = hwrequest.GetRequestStream()
                postStream.Write(postByteArray, 0, postByteArray.Length)
                postStream.Close()
            End If
            Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
            If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
                Dim responseStream As IO.StreamReader =
                  New IO.StreamReader(hwresponse.GetResponseStream())
                responseData = responseStream.ReadToEnd()
            End If
            hwresponse.Close()
            cookieJar = Nothing
        Catch e As Exception
            responseData = "An error occurred: " & e.Message
        End Try

        Return responseData
    End Function```

Any help would be appreciated!


text:
Q: python - Why does the += operator with lists is able to append a string but not list = list + "stri" l = list()

l = l + "string" #throws error
l += "string" #works

I was just wondering why this strange behaviour since we were taught l = l + "something" is the same as l += "something".

A: + requires a list when adding to a list.
+= only requires an iterable when updating a list. A str value is (for better or worse) an iterable of single-character strings, so that
l += "string"

causes 's', 't', 'r', etc to be appended to l. The += operator is more or less equivalent to
l.extend("string")


text:
Q: Hook into form handle from admin users table I'm adding a couple of buttons to the user table in a custom column, in which, on click will need to either approve or reject the user via update_user_meta.
I've tried hooking in with profile_update, but that didn't seem to work.
I also noticed that the form method is get, so would the best option here be some admin ajax?

TIA!


text:
Q: Need help on my Ubuntu server installation Needed help, I've tried commands but still not continuing to the desktop. badly needed help.

A: If you installed Ubuntu Server, the command prompt you show in the photo is perfectly normal. A graphical desktop environment is not installed by default.
Either you can reinstall Ubuntu (the normal desktop version) and setup your server applications from there, or you can install a graphical desktop on top of your existing installation as follows (I'll just give you an example for Gnome, if you want anything else the internet is full of help :) ).
Run the following commands from the command line:
sudo apt update
sudo apt upgrade
sudo apt install tasksel
sudo tasksel install ubuntu-desktop
sudo reboot

You should now be shown a graphical login screen!

A: You have installed the Ubuntu server version which does not include a desktop by default. So all operations you want to perform would be via a CLI (command-line interface) which is what the primary focus of a server type environment is.
Easiest thing you can do if you don't have CLI expertise
Download a Ubuntu Desktop version from Ubuntu website
https://ubuntu.com/download/desktop and reinstall it.
Alternate method through shell prompt
Start by updating the repositories and package lists:
sudo apt-get update && sudo apt-get upgrade

Next, install the tasksel manager utility:
sudo apt-get install tasksel

Choose a display manager. Many options are available from lightweight to high function desktop environment. Below is an example of Xubuntu - a moderately lightweight GUI for ubuntu
E.g. Install Xubuntu by entering the following:
sudo tasksel install xubuntu-core

Launch your desktop by
sudo service display_manager start

If you need to stop the desktop and return to the terminal shell
sudo service display_manager start


text:
Q: What is the limiting form of $\sum\limits_{k=1}^n \frac{1}{k}\cos(U_k)$ where $U_k$ are iid $U_n\in(0,2\pi)$? I am trying to find the limiting form:
$$
\lim\limits_{n \to \infty}\sum\limits_{k=1}^n \frac{1}{k}\cos(U_k)
$$
where $U_k$ are iid $U_n\in(0,2\pi)$. I really have no idea where to start. I know for a fact from $L_p$ martingale convergence it does indeed converge to some number, just not sure how to find the final form. Thanks!


text:
Q: tengo problemas de compatibilidad con PHPMailer La cuestión es la siguiente, debido a limitaciones ajenas a mi, debo de reconfigurar el envió de correos de un sistema que esta desarrollado en php 5.2. El problema es que el PHPMailer que es compatible con esa versión de php es la 5.0 y aun con con la configuración adecuada no funciona. pero utilizo la versión de PHPMailer actualizada junto con la versión actual de php todo funciona perfectamente, pero resalto que no puedo simplemente utilizar las versiones nuevas porque no seria compatible con el php usado en el servidor donde se aloja el sistema antes mencionado.
Adjunto el código de ambas versiones:
Versión Funcional:
<?php
require "PHPMailer/Exception.php";
require "PHPMailer/PHPMailer.php";
require "PHPMailer/SMTP.php";

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$oMail= new PHPMailer();
$oMail->isSMTP();
$oMail->Host="mail.servidordelaempresa.com";
$oMail->Port=587;
$oMail->SMTPSecure="tls";
$oMail->SMTPAuth=true;
$oMail->Username="sisad@servidordelaempresa.com";
$oMail->Password="pass1234";
$oMail->setFrom("sisad@servidordelaempresa.com","SISAD");
$oMail->addAddress("rodododo@hotmail.com","Correo de Destino");
$oMail->Subject="MSJ de Prueba";
$oMail->msgHTML("Hola soy un mensaje");

if(!$oMail->send())
  echo $oMail->ErrorInfo;

Version del sistema, la cual no funciona:
function enviarCorreoEntradaMat($correo, $body, $num_req){
        error_reporting(E_STRICT);
        date_default_timezone_set('America/Mexico_City');
        require_once('../../includes/phpmailer/class.phpmailer.php');

        $correos = explode(";", $correo);

        $mail = new PHPMailer();

        $mail->IsSMTP();
        $mail->Host       = "mail.servidordelaempresa.com";
        $mail->SMTPDebug  = 2;

        $mail->SMTPAuth   = true;
        $mail->Host       = "mail.servidordelaempresa.com";
        $mail->Port       = 587;
        $mail->Username   = "sisad@servidordelaempresa.com";
        $mail->Password   = "pass1234";

        $mail->SetFrom('sisad@servidordelaempresa.com', 'SISAD');
        $mail->Subject    = "MATERIAL ENTREGADO DE REQUISICION $num_req";

        $mail->Body       = $body;
        $mail->IsHTML(true);

        foreach ($correos as $email) {
            $email = trim($email);
            $mail->AddAddress($email, "USUARIO SISAD");
        }

        $mail->AddAddress($correo, "USUARIO SISAD");
        $mail->Send();
}

enviarCorreoEntradaMat($correo_requi, $contenido_mensaje, $num_requi);

A: Entiendo que necesitas que tu sistema funcione tanto en versiones antiguas de PHP como en recientes y sugiero que tengas dos códigos e incluyas el adecuado, de acuerdo a la versión detectada por phpversion():
if(phpversion() <= 5.2) {
    // Incluir librería PHPMailer 5.2, que puedes descargar desde:
    //     https://github.com/PHPMailer/PHPMailer/tree/5.2-stable
    // Incluir tu script de envío de correos para esta versión
    include 'ruta/correos-anterior.php';
} else {
    // Incluir librería PHPMailer actualizada
    // Incluir tu script de envío de correos para versiones recientes
    include 'ruta/correos-nuevo.php';
}

Si los nombres de espacio generan conflicto, entonces dentro de tus scripts incluyes la librería de PHPMailer que corresponda.


text:
Q: webapi won't deserialize string array using $.param I am trying to call a ASP.NET WebAPI method and pass it a serialized JavaScript object over a GET request similar to a $.ajax POST request. It is working fine except for when the JavaScript object has a null value for Networks, then it sends it in the URL like /api/airings/get-airings?networks= and the server is showing the string[] as having a single item with a value of null! If I remove the network= it shows up as null on the server as I would expect.
So, it appears that people requested tickets in jQuery regarding this behavior, but I want to know what I can do without using a plugin or rewriting the $.param logic or messing with WebAPI ModelBinder.
http://bugs.jquery.com/ticket/8653
http://bugs.jquery.com/ticket/1814
public class ApiGetAiringsRequest
{
    public DateTime? DateStart { get; set; }
    public DateTime? DateFinish { get; set; }
    public string[] Networks { get; set; }
}

public HttpResponseMessage GetAirings([FromUri] ApiGetAiringsRequest request )
    ...

document.location.href = "/api/airings/get-airings?" + $.param(request);

A: so to work around this issue I changed the string array to a simple string, and do a .split on it.
var serialize = function(obj)
{
    var str = [];

    for (var p in obj)
    {
        if (obj[p])
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }

    return str.join("&");
};

$.get('/api/airings/get-airings?' + serialize(request));

C#
var networks = (request.Networks??"").Split(',');


text:
Q: How to set focus in touchableopacity? I developing application for android-tv I need set focus in TouchableOpacity.
How can i do this?
My example of focus detection on Android TV
enableTVEventHandler() {
    this.evtHandler = new TVEventHandler();
    this.evtHandler.enable(this, this.handleTVRemoteEvent);
}

disableTVEventHandler() {
    if (this.evtHandler) {
        this.evtHandler.disable();
        delete this.evtHandler;
    }
}

handleTVRemoteEvent = (cmp, event) => {
    const { eventType, tag } = event;

    if (tag !== this.nodeHandle) {
        return;
    }

    if (eventType === "focus") {
        this.setState({ isFocus: true });

        if (this.props.focus !== undefined) {
            this.props.focus();
        }
    }

    if (eventType === "blur") {
        this.setState({ isFocus: false });
    }
}

A: After working for a while i found this solution:
<TouchableHighlight
  onPress={this.props.onPress}
  onFocus={() => {
    this.setState({
      currentStyle: 'blue',
    })
  }}
  onBlur={() => {
    this.setState({
      currentStyle: 'white',
    })
  }}
>
{this.props.children}
</TouchableHighlight>


text:
Q: Event Handling in Sabre App I am new to the Sabre Red App plugin development. I am exploring the event handling support in the Red App. Below are my questions:
1) What are the events available. Do we have the event like 'flight booking completed' ?
2) How to register the event handlers for the events ?

A: There are a combinations of Events that a Red App can subscribe to, mainly tied to Sabre commands in a workflow from a consultant, or specific functions being triggered in the platform (i.e. a Profile being copied to a Trip/PNR being created). When it comes to commands that are utilized to construct the Trip/PNR, these can be any type of command being entered.
One you install the Developer Tools from the Red App SDK on the Eclipse IDE, documentation is added to the default Eclipse Help System for Red Apps.


text:
Q: Why does C style cast work but reinterpret_cast doesn't? So I have a two char array
unsigned char v[2];

I want to show the value of v[0] as a number from 0 to 255 but
cout << v[0] << endl; //prints some garbage

cout << (void*)v[0] << endl; //prints the right thing but in hex

So I tried
cout << (int)v[0] << endl;

or
printf("%d\n", v[0]);

This shows exactly what I wanted but I don't like it at all. Also what I don't understand at all is why this doesn't work:
cout << reinterpret_cast<int>(v[0]) << endl; //compiler error

A: *

*reinterpret_cast : "...allows any integral type to be converted
into any pointer type and vice versa."  Use this only to convert
things that could be pointers into the right pointer type (an
unsigned char clearly cannot be a pointer in anything other than an
8-bit system).

*static_cast : Use this when you want to cast a type into another
type (like a float to int, or unsigned char to int).
cout tries to print an unsigned char as an ASCII character code, so converting to int via static_cast<int>(v[0]) is the right thing to do.

A: The way you are using reinterpret_cast, you are trying to read a char as an int, and they are not the same size.

A: reinterpret_cast converts values of pointer types to other pointer type values or integer values and vice versa, in order to allow a dereference of the destination pointer value. You however try to convert one integer type value to another integer type value. That's not going to work. reinterpret_cast supports the casting of reference types, which is equivalent to the respective pointer value cast with a follow-up dereference. So it appears you wanted to do
// NOTE: THIS IS UNDEFINED BEHAVIOR
cout << reinterpret_cast<int&>(v[0]) << endl;

This is well-formed, but reinterprets the unsigned char as an integer object, which isn't guaranteed to work (possible issues range from invalid alignment of the storage to incompatible sizes - 1 byte vs 4 bytes). You can solve these cases by doing the (int)v[0] cast, I think that's perfectly fine. You can also say +v[0], which promotes the value to (signed or unsigned) int automatically.

A: (In layman's terms) reinterpret_cast is used to interpret the bits of an object as another type in an implementation-defined manner. You don't want that: you want a conversion (from char to int). Use static_cast instead.
(All possible uses of reinterpret_cast are listed in 5.2.10; this is not one of them.)

A: cout << v[0] << endl; // prints some garbage

Not garbage, but the character that the value in v[0] represents.
cout << (void*)v[0] << endl;

This "converts" the value in v[0] to a pointer (undefined behavior, since it wasn't a pointer to begin with), and prints the value of that pointer as a hex value.
cout << (int)v[0] << endl;

This converts the value in v[0] to an int (well defined; just promote to int) and displays the value.
reinterpret_cast, as others have mentioned, has some constraints on what it can do. The right answer is to use static_cast<int>:
cout << static_cast<int>(v[0]) << endl;

A: static_cast will, as others have noted, do the right thing.  It is weaker than a C-style cast, so it is less likely to be damaging and cause undefined behavior.
reinterpret_cast is also weaker than a C-style cast, but it is not strictly stronger than static_cast; there are things static_cast can do that reinterpret_cast cannot.  You have run into one of them.
reinterpret_cast is intended to permit you to take values of one type, store them as values of another, then get back the original type.  You can do this to convert beteen integer and pointer types that are compatible.  You can use this to convert from one pointer type to another and back again.
In general, a reinterpret_cast converts your to a "holding" value, and that holding value is implementation defined at best, and often using it is undefined behavior.
So you want to avoid using it unless you really really mean it.
Converting a char to an int is not a matter of reinterpreting usually.
static_cast<int>(some_char) will upgrade the char to an int and get you the appropriate value.

However, in certain circumstances I find static_cast too powerful.  It can do unsafe pointer conversions, and counts as an explicit conversion.
Both of these can disguise bugs.
You can write a strictly weaker cast as follows:
template<class T, class U>
T implicit_cast( U&& u ) { return std::forward<U>(u); }

now you can
std::cout << implicit_cast<int>(v[0]) << std::endl;

and you get behavior very much like calling a function taking an int with a char argument, which I believe is what you want.

What is going wrong here?  Well, std::cout is a stream, and streams pay attention to the type passed.  char types are printed as if they are `'a`` style characters, not as if they are small integers.
In order to treat a char as a small integer, you have to convert it to another integer type.
The same is true of char*; they are treated as pointers to null-terminated buffers of char, like "hello world", and not like other pointers.


text:
Q: process and export text file into csv file I'm using this code to get a text file as an input, and turn it to csv file as an output. The csv file has two columns, one for the words, and the other for the count of the words.
from collections import Counter
file = open(r"/Users/abdullahtammour/Documents/txt/1984/1984.txt", "r", encoding="utf-8-sig")
wordcount={}
wordcount = Counter((file.read().split()))
for item in wordcount.items():
    print("{}\t{}".format(*item), file=open("/Users/abdullahtammour/Documents/txt/1984/1984.csv", "a"))
file.close()

I want to enhance the code and add two feature:
1st (and the most important) I want only the words in the output file, no numbers, no characters like (*&-//.,!?) and so on.
2nd to turn all the words in the output file to be lower case.
Any help will be appreciated.

A: You can use the string method isalpha() to check if there are only alphabetic characters in a word, and you can use lower() to convert it to lower case. I'm assuming you don't want apostrophes or other punctuation in your words either, but if that is OK then you could strip such characters out with replace, like this:
word.replace("'",'').isalpha()

It's also better to just open a file once than to open & close it a thousand times, which is what you do by opening it in the body of the loop. It is not only inefficient but could conceivably have weird results if buffering is involved.
I rewrote it with a 'with' clause which is roughly equal to opening the file at the beginning of the clause and closing it at the end.
Not as important, but you can use the 'sep' keyword in print() instead of manually inserting a tab, like this:
print(arg1, arg2, sep='\t')

Revising your code:
from collections import Counter
file = open(r"/Users/abdullahtammour/Documents/txt/1984/1984.txt", "r", encoding="utf-8-sig")
wordcount={}
wordcount = Counter((file.read().split()))
file.close()

with open("/Users/abdullahtammour/Documents/txt/1984/1984.csv", "w") as file:
    for word, count in wordcount.items():
        if word.isalpha():
            print(word.lower(), count, sep='\t', file=file)


text:
Q: Adobe LiveCycle Designer: Hide/Show Multiple Subforms via Drop Down List Good afternoon,
Quick question here. Could someone show me the code needed to hide / show subforms in Adobe LiveCycle Desier ES 8.2? I have 3+ subforms that I need to be able to switch between based on a specific country. I'd really appreciate the help.  Thank you.
Also, I've been able to get it to work between two selections but now everytime I try to build a form I can't even select an item from the drop down list.
Xeverus

A: you can achieve this by java-script.
on change - (JavaScript, client) event of drop-down you add script.
subform1.presence = "hidden";
subform2.presence = "hidden";

var order= xfa.resolveNode("form1.#subform[0].typeOfIncidentDdl").rawValue;
if (order == 1) {
          subform1.presence = "visible";
}
if(order ==2){
          subform2.presence = "visible";
}


text:
Q: How to delete elements by ID? I have a list of ids
IEnumerable<long> ids

How can I delete from a table where the ID matches?

A: The "standard" way according to the MSDN docs is to use those IDs to pull up each of the objects, then delete them with the DeleteObject command:
context.Where(x=>ids.Contains(x.Id)).ToList().ForEach(context.DeleteObject);

This will produce N+1 roundtrips to the DB. This is a common downside of ORMs; they're excellent at 99% of everyday use of SQL by an app (querying for results, creating/updating/deleting single objects) but are not really designed for these bulk operations.
You could also construct a query using ExecuteStoreCommand, where you "DELETE FROM table WHERE id IN @p1" and specify the list of IDs as a parameter.

A: Assuming you have Id as primary key in your entities and you have an entity called SampleEntity you could do something like this:
foreach(long id in ids)
{
  var sampleEntity = context.SampleEntities.SingleOrDefault( e => e.Id == id);
  if(sampleEntity!=null)
     context.SampleEntities.DeleteObject(sampleEntity);
}
context.SaveChanges();

EF does not support batch operation, so you will have to delete entities one by one, or alternatively do a direct store query (SQL) to make the deletion.

A: Generically
var db = GetYourDBContext();
var ItemsToDelete = (from id in ids
                     from item in db.TableWithItems
                     where item.id == id
                     select item).ToList();

foreach (Item item in ItemsToDelete)
    db.DeleteObject(item);

db.SaveChanges();

A: How about something like,
context.Entities.Where(e => ids.Contains(e.id))
                .ToList()
                .ForEach(e => context.SampleEntities.DeleteObject(e) );

context.saveChanges();


text:
Q: Problem fetching contact container Xamarin.iOS I got a problem with a little application I'm developing using Xamarin.iOS
My goal is simply to get every contacts present on an iPhone.
I have this code, it worked until now on my phone and at least 3 others.
Yesterday I added someone in my provisioning profile, since, I can't get any other value than 'null' on my phone when I try to fetch a container.
My phone is an iPhone 7 iOS 13.1.2 - I can't test it on any other phone until a little moment.
It still works on a simulator (iPhone 8 iOS 13.1).
I have the contact authorization request in my info.plist.
I just don't understand what getting 'null' means when fetching a default container ...
try
        {
            var keysTOFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.Nickname, CNContactKey.JobTitle, CNContactKey.DepartmentName, CNContactKey.OrganizationName, CNContactKey.PostalAddresses, CNContactKey.UrlAddresses, CNContactKey.EmailAddresses, CNContactKey.PhoneNumbers };
            NSError error;
            CNContact[] contactList;
            var ContainerId = new CNContactStore().DefaultContainerIdentifier;  <---- //This where I get a null I never got before ...
            if (ContainerId != null)
            {
                using (var predicate = CNContact.GetPredicateForContactsInContainer(ContainerId))
                using (var store = new CNContactStore())
                    contactList = store.GetUnifiedContacts(predicate, keysTOFetch, out error);
                var contacts = new List<UserContact>();
                status = writeCSV(contactList, user);
            }
            else
                Console.WriteLine("Didn't get any container identifier ..");
        }

Apple documentation says it can return 'null' but without further explanation ..
Thanks a lot for your help

A: You are facing this issue on some phones and not other because the phone that work have only one container that it is trying load contacts from, while the phones that don't work have more than one container (i.e. Gmail, Exchange, iCloud accounts used to store contacts). So you are only loading the contacts from the account that is configured as the default, which has 0 contacts. Therefore, it would not load all contacts as requested.
Solution: Get all the containers and iterate over them to extract all contacts from each of them. You might be able to find some samples of it on Github.


text:
Q: AWS Service Limit I have created case for increasing service rate limit of aws lambda for handling heavy load in our application. I want to get information about whether aws take any charges monthly/one time for increasing limit?

A: There is no charge to process your request to increase the limit. See: AWS Lambda Pricing for the actual cost over free tier.

*

*Free Tier - 1M REQUESTS per month / 400 GB-SECONDS of compute time per month.

*Requests - 1M REQUESTS FREE First 1M requests per month are free. / $0.20 PER 1M REQUESTS THEREAFTER $0.0000002 per request.

*Duration - 400,000 GB-SECONDS PER MONTH FREE / First 400,000 GB-seconds per month, up to 3.2M seconds of compute time, are free. $0.00001667 FOR EVERY GB-SECOND USED THEREAFTER

A: Adding to what @hellov have written.
You can control code execution performance and costs for your Lambda function by adjusting Memory and Timeout.
These are present in Basic Setting of your Lambda function console. However these will affect your pricing. Please visit this page for more detailed information regarding the pricing.
Below is a complex example how the pricing will work:

Let's assume you have three functions, each with different memory
  sizes as described below:
Function 1
128MB of memory, executed 25M times in one month, runs for 200ms each
  time
Total compute (seconds) = 25M * (0.2sec) = 5M seconds
Function 2
448MB of memory, executed 5M times in one month, runs for 500ms each
  time
Total compute (seconds) = 5M * (0.5sec) = 2M seconds
Function 3
1024MB of memory, executed 2.5M times in one month, runs for 1 second
  each time
Total compute (seconds) = 2.5M * (1sec) = 2.5M seconds
If you ran these functions, your charges would be calculated as
  follows:
Monthly compute charges
AWS Lambda normalizes the total compute time to GB-s and then sums the
  total across all functions
Function 1 (GB-S) = 5M seconds * (128MB/1024) = 625,000 GB-s
Function 2 (GB-S) = 2.5M seconds * (448MB/1024) = 1,093,750 GB-s
Function 3 (GB-S) = 2.5M seconds * (1024MB/1024) = 2,500,000 GB-s
Total monthly compute usage (GB-S) = 4,218,750 GB-s
The monthly compute price is $0.00001667 per GB-s and the free tier
  provides 400,000 GB-s. Monthly charged compute usage = Total monthly
  compute usage – Free tier usage
Monthly charged compute usage = 4,218,750 – 400,000 = 3,818,750 GB-s
Monthly compute charges = 3,818,750 * 0.00001667 = $63.66
Monthly request charges
The monthly request price is $0.20 per 1 million requests and the free
  tier provides 1M requests per month.
Total requests – Free tier requests = Monthly billable requests
(25M+5M+2.5M) requests – 1M free tier requests = 31.5M Monthly
  billable requests
Monthly request charges = 31.5M * $0.2/M = $6.30
Total Monthly Charges
Total charges = Compute charges + Request charges = $63.66 + $6.30 =
  $69.96 per month


text:
Q: Python Pandas read_csv reads only single line from CSV file I am writing a code to read and extract parameters from each row of a CSV file.
From each row, I get a list of parameter values arranged by datestamps and values. An example csv file is as below:
Row1: 'Fanspeed','Value=32','Datetime=05-01-2015','Fanspeed','Value=32','Datetime=05-02-2015'

Row2: 'Fanspeed','Value=32','Datetime=05-03-2015','Fanspeed','Value=32','Datetime=05-04-2015'

If I use the Pandas read_csv to read in the file and then print the output, it only prints the first row. However, when I use the csv.reader function, I get the correct output. My program looks like this:
csv_f = pd.read_csv('test.csv')
for row in csv_f:
    csv_f = pd.read_csv('test.csv')
    print csv_f

I get only the following output:
'Fanspeed','Value=32','Datetime=05-01-2015','Fanspeed','Value=32','Datetime=05-02-2015'

However, on running the same program with the csv.reader function as below:
f = open('test.csv')
csv_f = csv.reader(f)
for row in csv_f:
    csv_f = pd.read_csv('test.csv')
    print csv_f

I get the correct output. Could someone help me?

A: First of all , you can try to pass 'header=None' to indicate the first row will be data instead of the headers.
csv_f = pd.read_csv('test.csv', header=None)
print csv_f

Secondly, what the read_csc returns is already a DataFrame, so you should directly working on it.
More information pandas.read_csv

A: Try this:
    csv_f = pd.read_csv('test.csv')
    print csv_f.head()
    #for row in csv_f:
        #csv_f = pd.read_csv('test.csv')
        #print csv_f


text:
Q: Converting to predicate logic I having a lot of trouble converting two english statements to predicate logic:

*

*For every positive real number x, there is some real number y that is the square
root of x (extend this statement to show that there are two distinct
square roots of x)

*For any two distinct real numbers there is a third real number with a value between the first two.
I figured out the first part of the first statement : ∀x (x > 0 → ∃y (y=$\sqrt{x}$)) but I am unable to solve the second part (extend this statement to show that there are two distinct square roots of x)
and I am clueless how to go about the second question (For any two distinct real numbers...)
Any help will be greatly appreciated!!

A: I give you a hint:
You can reformulate the parenthesized sentence into: For any positive real $x$ there exist numbers $y_1$ and $y_2$ such that they are not equal and such that each of them is a square root of $x$.
I would write "$y$ being a square root of $x$" as $y^2=x$, since $\sqrt{x}$ is not unique in your statement.
For the second part: For any two $x_1$ and $x_2$ which are not equal there exists $y$ such that ($x_1$ is smaller than $y$ and $y$ is smaller than $x_2$) or ($x_2$ is smaller than $y$ and $y$ is smaller than $x_1$).
Is it clear to you why these are the same?


text:
Q: Umbraco 5 keeps showing Login Expired on Administrator Panel On administration panel, Jupiter regularly takes off a "Login Expired" box asking to login again.

*

*I am using a IIS7 hosting service

*I am using SQL Server 2008 R2

*I checked the full trust capability on web.config adding trust level="full" (this is need on mi hosting)

*I manually add ASP.NET WebPages assemblies to /bin  directory (except System.Web.WebPages.Administration.dll because it conflicts with Nuget assembly in Umbraco)

I checked the same site on IIS 7.5 through publishing on other hosting provider and this was solved but still I need solve this.
The admin panel is operating but It constatly needs relogin.
The log seems to show all working fine.
Anybody had the same problem?

A: Check the dates on your server, versus your workstation. They need to match, its a common problem, that catches a lot of people.

A: I think this can also be caused when your app pool recycles. I've noticed that the popup seems to appear after the app pool has been recyled or restarted on the server.


text:
Q: How to get menu items from one menu and append them to different menu I have a mini menu with few links which on tablet and mobile screen sizes have to be hidden which  is fine am doing this with css and media queries, but I have one more main menu with different links and on normal screen sizes appear as expanded but on tablet and mobile appear as a hidden clickable hamburger menu. I want on tablet and mobile size when the links from the mini menu are hidden to become part of the main menu. I know I have to create in my .js file some kind of for loop which on tablet and mobile sizes will grab the menu items from the minu menu and append them to the main menu but not really sure how to do that if someone please can help me with a code wireframes how to do that will be great.
Thank you!

A: I would recommend to just put inside your main menu the links which you want to be seen on mobile and add a class to those links which will only show them on mobile. If it's just a simple link it should do the job.

always visible

always visible

only visible on mobile

always visible

Then in your css:
.main-menu .visible-mobile { display: none }

@media (max-width: ...) {
   .main-menu .visible-mobile { display: block }
}

If you still prefer to do it with javascript, here's one way to do it
const mainMenu = document.querySelector('.main-menu');
const minuMenu = document.querySelector('.mini-menu');
const mobileBreakpoint = 767; // put your mobile breakpoint here
const isMobile = window.innerWidth < mobileBreakpoint;

if ( isMobile ) {
    const listItems = miniMenu.querySelectorAll('li');
    mainMenu.appendChild(listItems);
}


text:
Q: Cannot edit question? Your post appears to contain code that is not properly formatted as code I was trying to edit this Experiences on free and low-cost hosting for play framework applications?
I wanted to fix the formatting, so that it looks like this:
(Actually it would contain more links, but I'm not allowed to post more than two links here).

I'd like to know your experience finding a host for play applications on free or low-cost servers.
So far now I found the following options:

*

*Playapps
A cloud hosting solution by zenexity, the company behind play framework
Module
  [Princing][3]

*[Google Application Engine][4]
[Module][5]
  Cons: You can't use mysql, you should not use JPA. Instead of JPA it is  advised to use [siena][6].
  [Nice example][7]

*[Cloudbees][8]
[Module][9]
  [Pricing][10]
  [Floss][11]
  [Tutorial][12]

*[dotCloud][13]
[Module][14]
  [Princing][15] (there's a free plan with 10MB db)
  [Floss][16]
(updated)

*[AWS - Amazon Web Services][17]
[Pricing][18]
  [More pricing][19]
  [Sample][20]
  [Another sample][21]

*[Heroku for play!][22]
[Princing][23] (Seems like you get 1 web dyno and 5mb postresql dabate for free)
  [Sample][24]
Do you have any experience with one of these?
Any other option you know?

But I got an error message

Oops! Your edit couldn't be submitted because:
Your post appears to contain code that is not properly formatted as code. Please indent all code by 4 spaces using the code toolbar button or the CTRL+K keyboard shortcut. For more editing help, click the [?] toolbar icon.

Why is that? The question does not contain any code.

A: I didn't get a warning with the edit I just did. The formatting is as follows:
- Title
<blank line>
______Stuff__
______MoreStuff__
______OtherStuff
Four spaces before the stuff in the list, two spaces at end of line for all but the last stuff (in order not to have too much vertical space between the items like you'd get with an empty line between each - I'm guessing that is what triggered the "code-look-alike" filter if you had empty lines alternating with code-indented lines).
Renders as:

*

*Title
Stuff
MoreStuff
OtherStuff
And if you want code in there (as you should on SO, posts without code are sad):

*

*Title
Stuff
<just indent="four more">to get code in the list</just>

OtherStuff


text:
Q: How to skip transaction in ActiveRecord for INSERT ONLY statement? Look at this example:
2.1.3 :001 > Stat.create!
   (0.1ms)  BEGIN
  SQL (0.3ms)  INSERT INTO `stats` (`created_at`, `updated_at`) VALUES ('2015-03-16 11:20:08', '2015-03-16 11:20:08')
   (0.4ms)  COMMIT
 => #<Stat id: 1, uid: nil, country: nil, city: nil, created_at: "2015-03-16 11:20:08", updated_at: "2015-03-16 11:20:08">

As you can see the create! method execute insert statement inside useless transaction. How to disable transation in this case only (without disabling them in whole application)?

A: The problem here is that you want to modify behavior for a class-level method.  This is inherently not thread-safe, at the very least for concurrent transactions for other Stat objects.  A simple workaround would be to flag the instance as not requiring a transaction:
class Stat < ActiveRecord::Base
  attr_accessor :skip_transaction

  def with_transaction_returning_status
    if skip_transaction
      yield
    else
      super
    end
  end
end

Stat.create! skip_transaction: true

If you are running on a single threaded framework, and therefore aren't concerned with suspending transactions for Stat objects during this time, you can use class level methods and wrap the call like so:
class Stat < ActiveRecord::Base
  def self.transaction(*args)
    if @skip_transaction
      yield
    else
      super
    end
  end

  def self.skip_transaction
    begin
      @skip_transaction = true
      yield
    ensure
      @skip_transaction = nil
    end
  end
end

Stat.skip_transaction { Stat.create! }

A: How it works:
The persistence module define create: https://github.com/rails/rails/blob/4-2-stable/activerecord/lib/active_record/persistence.rb#L46
def create!(attributes = nil, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| create!(attr, &block) }
  else
    object = new(attributes, &block)
    object.save!
    object
  end
end

It create an object and call #save!
It is not documented in the public api, but calls https://github.com/rails/rails/blob/4-2-stable/activerecord/lib/active_record/transactions.rb#L290
def save!(*) #:nodoc:
  with_transaction_returning_status { super }
end

At this point the transaction wrap the save (super), which is at Persistence module again: https://github.com/rails/rails/blob/4-2-stable/activerecord/lib/active_record/persistence.rb#L141
def save!(*)
  create_or_update || raise(RecordNotSaved.new(nil, self))
end

Let's hack this with some new methods:
module ActiveRecord
  module Persistence
    module ClassMethods

      def atomic_create!(attributes = nil, &block)
        if attributes.is_a?(Array)
          raise "An array of records can't be atomic"
        else
          object = new(attributes, &block)
          object.atomic_save!
          object
        end
      end

    end

    alias_method :atomic_save!, :save!
  end
end

module ActiveRecord
  module Transactions

    def atomic_save!(*)
      super
    end

  end
end

Perhaps you want to use the standard create! method, then you need to redefine it. I define a first optional parameter :atomic, and when it's present means you want to use the atomic_save! method.
module ActiveRecord
  module Persistence
    module ClassMethods

      def create_with_atomic!(first = nil, second = nil, &block)
        attributes, atomic = second == nil ? [first, second] : [second, first]
        if attributes.is_a?(Array)
          create_without_atomic!(attributes, &block)
        else
          object = new(attributes, &block)
          atomic == :atomic ? object.atomic_save! : object.save!
          object
        end
      end
      alias_method_chain :create!, :atomic

    end
  end
end

With this in config/initializers/<any_name>.rb it can work.
How it runs at console:
~/rails/r41example (development) > Product.atomic_create!(name: 'atomic_create')
  SQL (99.4ms)  INSERT INTO "products" ("created_at", "name", "updated_at") VALUES (?, ?, ?)  [["created_at", "2015-03-22 03:50:07.558473"], ["name", "atomic_create"], ["updated_at", "2015-03-22 03:50:07.558473"]]
=> #<Product:0x000000083b1340> {
            :id => 1,
          :name => "atomic_create",
    :created_at => Sun, 22 Mar 2015 03:50:07 UTC +00:00,
    :updated_at => Sun, 22 Mar 2015 03:50:07 UTC +00:00
}
~/rails/r41example (development) > Product.create!(name: 'create with commit')
  (0.1ms)  begin transaction
  SQL (0.1ms)  INSERT INTO "products" ("created_at", "name", "updated_at") VALUES (?, ?, ?)  [["created_at", "2015-03-22 03:50:20.790566"], ["name", "create with commit"], ["updated_at", "2015-03-22 03:50:20.790566"]]
  (109.3ms)  commit transaction
=> #<Product:0x000000082f3138> {
            :id => 2,
          :name => "create with commit",
    :created_at => Sun, 22 Mar 2015 03:50:20 UTC +00:00,
    :updated_at => Sun, 22 Mar 2015 03:50:20 UTC +00:00
}
~/rails/r41example (development) > Product.create!(:atomic, name: 'create! atomic')
  SQL (137.3ms)  INSERT INTO "products" ("created_at", "name", "updated_at") VALUES (?, ?, ?)  [["created_at", "2015-03-22 03:51:03.001423"], ["name", "create! atomic"], ["updated_at", "2015-03-22 03:51:03.001423"]]
=> #<Product:0x000000082a0bb8> {
            :id => 3,
          :name => "create! atomic",
    :created_at => Sun, 22 Mar 2015 03:51:03 UTC +00:00,
    :updated_at => Sun, 22 Mar 2015 03:51:03 UTC +00:00
}

Caveat: You will lose after_rollback and after_commit callbacks!
Note: on 4.1 the methods create! and save! are in module Validations. On Rails 4.2 are in Persistence.
Edit: Perhaps you think you can earn the transaction elapsed time. In my examples the commit time goes to the inserts (I have a standard HD and I think you have an SSD).

A: The simplest way is to manually write your INSERT statement, still using ActiveRecord to execute it. This won't disable transactions for any other code you write.
sql = "INSERT INTO stats (created_at, updated_at) VALUES ('2015-03-16 11:20:08', '2015-03-16 11:20:08')"
ActiveRecord::Base.connection.execute(sql)

Not as nice as using Alejandro's solution above, but does the trick - especially if it's a once off and the table is unlikely to change.

A: I don't know of any nice way of doing this
On ruby 2.2 you can do
stat = Stat.new
stat.method(:save).super_method.call

This won't work pre ruby 2.2 (that's when super_method was added) and only works because in the list of ancestors, transactions is the first (or last depending on which way you order) to override save. If it wasn't then this code would skip over the 'wrong' save method. As such, I could hardly recommend this
You could do something like
stat = Stat.new
m = stat.method(:save)
until m.owner == ActiveRecord::Transactions
  m = m.super_method
end
m = m.super_method

To automatically walk up the chain until you have found the transactions bit, but there's no telling what code you might have skipped over.

A: Answer of Alejandro Babio is extensive but wanted to explain why transaction is done in the first place.
This answer explains what role does the transaction have in the call. Here is it in short:
begin transaction
insert record
after_save called
commit transaction
after_commit called

But provided no after_save hook is registered by developer, I wonder why transaction is not skipped. For high latency connections, the transaction may increase overall operation time 3 times :/ IMO Rails needs to be optimized.
Rails rejected such optimization, see why: https://github.com/rails/rails/issues/26272


text:
Q: JQuery DataTables serverside processing with additional variables I've been trying to implement a solution using JQuery datatables with serverside processing to display logs. This has largely been successfull. The datatable declaration is as follows:
$('#IndexTable').dataTable({
    "bServerSide": true,
    "oLanguage": {
    "sSearch": "
" +
        "Search : " +
            "
" +
            "
" +
                "_INPUT_" +
            "
" +
            "
" +
                "
" +
            "
",
        "sLengthMenu": "
" +
                      "Display : " +
            "
" +
            "
" +
                "_MENU_" +
            "
" +
            "
" +
                "
" +
            "
",
        "sInfo": "
Showing _START_ to _END_ of _TOTAL_ records",
},
"bDestroy": true,
"sAjaxSource": '@Url.Action("List")',
"fnServerData": function (sSource, aoData, fnCallback) {
    $.ajax({
        dataType: 'json',
        type: "POST",
        url: sSource,
        data: aoData,
        success: fnCallback,
        error: function (jqXHR, textStatus, errorThrown) { alert('Error getting logs:' + errorThrown) }
    })
},
"bPaginate": true,
"sPaginationType": "full_numbers",
"iDisplayLength": 25,
"aLengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
"aoColumnDefs": [
    { "sName": "Level", "aTargets": [0], "mDataProp": "LogLevel" },
    { "sName": "Source", "aTargets": [1], "mDataProp": "LogSource" },
    { "sName": "Date", "aTargets": [2], "mDataProp": "LogDate" },
    { "sName": "Text", "aTargets": [3], "mDataProp": "LogText" }
    ]
});

Then, the contrller action:
public JsonResult List(jQueryDataTableParamModel param)
{ ... }

Where jQueryDataTableParamModel is structured as demonstrated here.
This works perfectly for displaying, paging, searching and sorting. Problem is, I have 2 drop-downs that I used when I still did the processing client-side that that filters everything based on 2 of the columns (level and source):

For this, I need the selected values in the List action method. I attempted to do this by simply adding the parameters in the method and passing them through.
data: {
    param: aoData,
    levelId: $("#LevelList").val(),
    sourceId: $("#SourceList").val()
},

Doing this works, but all the fields in the jQueryDataTableParamModel are null:

I can only assume the problem lies with the differences between:
data: aoData

and
data: {
    param: aoData
},

in the ajax call.

A: I've since figured this out by doing the following:
"ajax": {
    "url": "@Url.Action("List")",
    "type": "POST",
    'contentType': 'application/json; charset=utf-8',
    'data': function (data) {
        var tempData = {};
        tempData.pageRequest = data;

        // To addd custom parameters:
        // tempData.customParameter1 = $("#CustomParam").val()

        tempData.levelId = $("#LevelId").val();
        tempData.sourceId = $("#SourceId").val();

        return JSON.stringify(tempData);
    }
},

Then these are recieved in the controller action:
public JsonResult List(DataTablesPageRequest pageRequest, int levelId, int sourceId)
{ ... }

Note: I had to update my version of DataTables from 1.9.2 to 1.10.5


text:
Q: Hibernate validator for ComboBox How to validate a jComboBox for user to select any item other than the default item?
I need to check whether the user didn't select any item. So the jComboBox value will be "Please select a scurity question"

In my model class,
@NotEmpty(message="Please fill the username field!")
public String getUsername() {
    return this.username;
}

public void setUsername(String username) {
    this.username = username;
}

@NotEmpty(message="Please fill the password field!")
public String getPassword() {
    return this.password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getSeqQue() {
    return this.seqQue;
}

public void setSeqQue(String seqQue) {
    this.seqQue = seqQue;
}

What will be the hibernate validator annotation to add in getSeqQue() to validate my jComboBox?

A:
To validate your JComboBox with custom message simply you can make custom constraint validator.

See following example:
MyModel.java
public class MyModel {

    @ValidComboBox //this is the annotation which validates your combo box
    private String question;

    //getter and setter
}

ValidComboBox.java //annotation
import java.lang.annotation.*;
import javax.validation.*;

@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ComboBoxValidator.class)
@Documented
public @interface ValidComboBox {
String value = "Please select a security question";

String message() default "Please select a security question.";

Class<?>[]groups() default {};

Class<? extends Payload>[]payload() default {};
}

ComboBoxValidator.java
import javax.validation.*;
public class ComboBoxValidator implements ConstraintValidator<ValidComboBox, String> {

private String value;

@Override
public void initialize(ValidComboBox arg0) {
    this.value = arg0.value;

}

@Override
public boolean isValid(String question, ConstraintValidatorContext arg1) {
    if(question.equalsIgnoreCase(value)){
        return false;
    }
    return true;
}
}

Add items to your jComboBox like this:
JComboBox<String> jComboBox = new JComboBox<>();
jComboBox.addItem("Please select a scurity question");
jComboBox.addItem("Question 1");
jComboBox.addItem("Question 2");

And following lines you need to add when you perform action to validate:
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();

String question = jComboBox.getSelectedItem().toString();
MyModel model = new MyModel();
model.setQuestion(model);

Set<ConstraintViolation<MyModel>> constraintViolations = validator.validate(model);

if (!constraintViolations.isEmpty()) {
        String error = "";
        for (ConstraintViolation<MyModel> constraintViolation : constraintViolations) {
                error += constraintViolation.getMessage();
                JOptionPane.showMessageDialog(null, error);
        }
}

It will display Please select a security question message if you try to send request without choosing question.


text:
Q: ZF last inserted id does this code gives me the last inserted id of the record, even on a heavy load page?
  db = Zend_Db_Table::getDefaultAdapter();
  $db->insert($this->_name, $fields_values);
  $idAddress = $db->lastInsertId($this->_name);

Regards
Andrea

A: i am using  this...
db = Zend_Db_Table::getDefaultAdapter();
$lastInsertId = $db->insert($this->_name, $fields_values);

A: The Zend_Db_Adapter_Abstract::lastInsertId() method is a proxy to PDO::lastInsertId(). According to the documentation:

PDO::lastInsertId — Returns the ID of the last inserted row or sequence value
Note:
This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.

Now you know. Use it as your own risk!

A: public function saveData(array $data) {
    $this->_setName('user');

    // this will return all field name for user table in $field variable
    $fields = $this->info($this->getConstCol());

    // By this foreach loop we will set data in $data array
    foreach ($data as $field => $value)
    {
        if (!in_array($field, $fields))
        {
            unset($data[$field]);
        }
    }
    // It will call insert function of (Zend_Db_Table_Abstract Parent of Zend_Db_Table)
    // It will return $pkData which is primary key for user table

    return $this->insert($data); // It will return last insert ID
 }


text:
Q: how can i change focus of kendo datePicker on another button? i i use change property and close property but apparently Kendo date picker have problem with them
i use onselect too,  but nothing is working
$("#txtFromDate").kendoDatePicker({
            format: "MM/dd/yyyy",
});

//$('#txtFromDate').trigger('change', function (e) {
//    $('#btnNewRanges').focus();
//});`enter code here`

A: You can define a change event when you initialize the date picker :
$("#txtFromDate").kendoDatePicker({
        format: "MM/dd/yyyy",
        change: function(){
             // Your date picker changed, handle accordingly
             $('#btnNewRanges').focus();
        }
});

Likewise, if you need to subscribe to the event later (i.e. post-initialization), you can use the bind() function to wire up the event :
$("#txtFromDate").data("kendoDatePicker").bind("change", function() {
      // Your date picker changed, handle accordingly
      $('#btnNewRanges').focus();
});


text:
Q: Fourier transform over a finite abelian group Let $G$ be a finite abelian group. Let $f:G\mapsto \mathbb{C}$ be a function. Now, we can view each such functions as a vector in $\mathbb{C}^{|G|}$ by taking all evaluations over $G$. We define characters on abelian group as $\chi:G\mapsto\mathbb{C}$, as a homomorphism from $G$ to $\mathbb{C}$. As, this characters, when seen as a vector in $\mathbb{C}^{|G|}$ by taking evaluations, are orthogonal, it forms a basis. A Fourier transform on $G$ is just a vector space isomorphism mapping standard basis to these character basis. Also the group of characters is isomorphic to $G$.
Now, while reading this https://www.cs.umd.edu/~amchilds/teaching/w13/l02.pdf, I came across a definition that states, $F(|x\rangle)=\sum_{y\in \hat{G}}\chi_y(x)|y\rangle$, where $x$ is a group element $F$ is the fourier transform, $|x\rangle$ is the standard basis indexed by $x$ and as per my understanding $|y\rangle$ is the character basis indexed by $y$. Here, $\hat{G}$ is the group of characters.
Can anyone help me to clarify how this definition and the one I stated in the last paragraph are the same? It appears to me that, the standard basis are getting mapped to a linear combination of character basis, instead of just mapping to a character basis.


text:
Q: Elasticsearch term query issue

As the pictures show the record field of dispatchvoucher value is "True".
But when I searched with the term it couldn´t found any record.
when I changed the value to "true", the result matched. What's the reason for this?

A: As mentioned in the documentation :

Avoid using the term query for text fields.
By default, Elasticsearch changes the values of text fields as part of
analysis. This can make finding exact matches for text field values
difficult.
To search text field values, use the match query instead.

The standard analyzer is the default analyzer which is used if none is specified. It provides grammar-based tokenization.
GET /_analyze
    {
      "analyzer" : "standard",
      "text" : "True"
    }

The token generated is -
{
  "tokens": [
    {
      "token": "true",
      "start_offset": 0,
      "end_offset": 4,
      "type": "<ALPHANUM>",
      "position": 0
    }
  ]
}

Term query returns documents that contain an exact term in a provided field. Since True gets tokenized to true, so when you are using the term query for "dispatchvoucher": "True", it will not show any results.
You can either change your index mapping to
{
  "mappings": {
    "properties": {
      "dispatchvoucher": {
        "type": "keyword"
      }
    }
  }
}

OR You need to add .keyword to the dispatchvoucher field. This uses the keyword analyzer instead of the standard analyzer (notice the ".keyword" after dispatchvoucher field).
Adding a working example with index data, search query, and search result
Index Data:
{
  "dispatchvoucher": "True"
}

Search Query:
{
  "query": {
    "bool": {
      "filter": {
        "term": {
          "dispatchvoucher.keyword": "True"
        }
      }
    }
  }
}

Search Result:
"hits": [
      {
        "_index": "65605120",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.0,
        "_source": {
          "dispatchvoucher": "True"
        }
      }
    ]


text:
Q: Jquery Add .css to label based on wildcard ID I have the following generated code that needs to be modified with jquery

     <input id="priority1" type="radio" name="priority" value="Low" disabled="">
     Low
     <input id="priority2" type="radio" name="priority" value="Normal" disabled="">
     Normal<input id="priority3" type="radio" name="priority" value="High" disabled="">
     High
     <input id="priority4" type="radio" name="priority" value="CRITICAL" disabled="">
     CRITICAL

I need to add padding to each label (padding-right: 30px;)
I have tested with this:
$j("label[for='priority1']").css("padding-right", "30px");
It works and it could be argued that I can just repeat it four times for each label; however, I want to use a wildcard like so $j("label[for='[id^=priority]']").css("padding-right", "30px");. Unfortunately that did not work, any help would be appreciated.

A: $("label[for^='priority']").css("padding-right", "30px");

Seems to work fine here, no need to add id stuff.


text:
Q: Google sign-in prompt is not shown again after user closes the prompt only once I am trying to gapi to Google Identity Services in js client-side Google-SignIn.
SignIn Prompt is working with google.accounts.id.prompt() after
   google.accounts.id.initialize({
      client_id: 'YOUR_GOOGLE_CLIENT_ID',
      callback: handleCredentialResponse
    });

But if user closes prompt manually even if it is only once, prompt doesn't pop up again even the page is refreshed. Probably it is (suppressed_by_user). Is there a way to increase this cancel_limit number ?


text:
Q: Read auto_arima summary from pmdarima package correctly I run auto_arima model with seasonality from pmdarima python package.
The output summary is the following:

Shortly, it says that the best model is $ARIMA(3,1,2)(0,1,1)_{12}$ with intercept.
Now, I want to write the equation for my model, but I'm not sure that I did it correctly.
Please check it out:
$$ \Delta y_t = 0.618 y_{t-1} - 0.2979 y_{t-2}  - 0.4196 y_{t-3}  -0.3204 \epsilon_{t-1} -0.5838 \epsilon_{t-2} + \epsilon_{t} -0.4687 \epsilon_{t-12} + 0.0098$$
Edit
Please write it not in terms of $Y_t , e_t, θ$ and $Θ$


text:
Q: Javascript Text Slideshow Start from Beginning on Hover I have added a text slideshow to a div that is called by JQuery on hover.  How do I get the slideshow to start from the beginning each time the user hovers on the div?  Right now it just continues to loop after the first time it is activated.
Thanks in advance!
<script>

$(document).ready(function(){

$('#mercury .infos').hover(

  function () {
            if($("a.active").is('.mercury')){
                $("#descriptionls").fadeIn("2000");
            };

        var quotes = [
        "Who's the one who's always there when that keeps happening?",
        "Learn to dismantle self-defeating behaviors",
        "JOIN THE FLOW TODAY",
        ];

        var i = 0;

        setInterval(function() {
            $("#lstextslide").html(quotes[i]);
            if (i == quotes.length)
                i=0;
            else
                i++;
        }, 1 * 4000);

        });

});

</script>

A: You have to cancel the previous interval and call the function that updates the HTML immediately. See http://jsfiddle.net/xozL96fj/
$(document).ready(function(){

    var intervalTimer = null;

    $('#mercury .infos').hover(

        function () {
            if($("a.active").is('.mercury')){
                $("#descriptionls").fadeIn("2000");
            }

            if (intervalTimer !== null) {
                clearInterval(intervalTimer);
            }

            var quotes = [
                "Who's the one who's always there when that keeps happening?",
                "Learn to dismantle self-defeating behaviors",
                "JOIN THE FLOW TODAY",
            ];

            var i = 0;

            function update() {
                 $("#lstextslide").html(quotes[i]);
                 i = (i + 1) % quotes.length;
            }
            // Call it immediately, don't wait until the interval
            update();
            intervalTimer = setInterval(update, 4000);
        });
});

A: You need to make a check if your slider has already been activated. If you hover over your slider when the slider is already active, you will have to reset $i, and call setInterval() again.


text:
Q: SQLite Cascade Delete actually i'm developping windows metro app using SQLite DataBase. i use sqlite manager (mozilla) for administration. i tried delete cascade but it work only in sqlite manager not in C# code :
My function

public async Task<string> DeleteSurvey(int SurveyID)
{
    string result = string.Empty;
    var db = new SQLite.SQLiteAsyncConnection(App.DBPath);
    var survey = await GetSurvey(SurveyID);
    var res = await db.DeleteAsync(survey);

    if (res > 0)
        result = "Success";
    else
        result = "Echec";

    return result;
}

db.CreateTable<Survey>();

SQLiteCommand command1 = new SQLiteCommand(db);
command1.CommandText = "create table if not exists SurveyItemGroup";
command1.CommandText += "(ID integer primary key autoincrement not null, IDSurvey integer,";
command1.CommandText += "Number integer, Name varchar(50), FOREIGN KEY(IDSurvey) REFERENCES Survey(ID) ON DELETE CASCADE ON UPDATE CASCADE)";
command1.ExecuteNonQuery();

In C# code it only delete survey table not both (Survey and SurveyItemGroup)
PS: I have the same problem with pragma (pragma foreign_keys=ON;) it works only if i do it sqlite manager.

A: (I'm adding this answer because the OP noted this as his solution, but only in a comment.)
Currently, for ON DELETE CASCADE to work, pragma foreign_keys=on; must be issued in each new connection. It's not currently a persistent setting.


text:
Q: What is the exact usage of exists()? I am using it as
if ModelName.objects.get(fieldname=value).exists():
I either get the error 'ModelName' object has no attribute 'exists' or it throws a DoesNotExist exception.
Related doc: https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.exists

A: You should apply it to queryset, not a single object, try:
if ModelName.objects.filter(fieldname=value).exists():

If queryset is not empty, this will return True.


text:
Q: How can I add a custom HTML map marker to a Nokia HERE map? From what I'm reading of the documentation on Nokia maps I can add custom marker using a vector based drawing API:
http://developer.nokia.com/Community/Wiki/HERE_Maps_API_-_How_to_create_custom_graphics_marker
You can create custom graphic markers but only based on a sprite:
http://heremaps.github.io/examples/examples.html#sprite-markers
Or you can add their own markers:
http://developer.nokia.com/Community/Wiki/HERE_Maps_API_-_How_to_add_map_markers
But is there any way to provide an HTML snippet to position on the map like a map marker? That is how other map libraries work so I can completely control the map marker in HTML/CSS. I already have map markers I would like to use that are styled in HTML/CSS and would not like to duplicate that styling in custom JS.

A: If you are intent on using styled, injected HTML, it would be possible to create a series of custom components (one for each marker) and attach them to the map. This would inject a block level element for each component which you could style as you see fit.
This is not entirely dissimilar to the simple GroundOverlay component I used to use before the ImgTileProvider class was exposed in the API - it injects a <IMG> element and resizes  on zoomLevel (which you will probably need to remove) , but still effectively attaches a piece of HTML to a specific anchor point on the map.
For most simple applications I would usually use Markers (with or without my own iconography) or Infobubbles though. These lead to a more  responsive and standard UI and don't clutter the map.
function extend(B, A) {
  function I() {}
  I.prototype = A.prototype;
  B.prototype = new I();
  B.prototype.constructor = B;
}

function GroundOverlay(url, boundingBox) {
  nokia.maps.map.component.Component.call(this);
  this.init(url, boundingBox);
}

extend(GroundOverlay,
    nokia.maps.map.component.Component);

GroundOverlay.prototype.init = function (url, boundingBox) {
  var that = this;
  that.overlayDiv  = document.createElement('div');
  that.overlayDiv.style.position = 'absolute';
  that.overlayDiv.style.cursor = 'default';
  that.overlayImage = document.createElement('img');
  that.overlayImage.id = 'groundoverlay';
  that.overlayDiv.appendChild(that.overlayImage);

  that.set('url', url);
  that.set('boundingBox', boundingBox);
  that.set('visible', true);
  that.set('opacity', 1);

  that.addOverlay = function () {
    var isVisible = that.get('visible'),
      bbox,
      topLeft,
      bottomRight;

    if (isVisible === false) {
      that.overlayDiv.style.display = 'none';
    } else {
      bbox = that.get('boundingBox');
      topLeft = that.map.geoToPixel(bbox.topLeft);
      bottomRight = that.map.geoToPixel(bbox.bottomRight);
      that.overlayDiv.style.display = 'block';
      that.overlayDiv.style.left = topLeft.x + 'px';
      that.overlayDiv.style.top = topLeft.y + 'px';
      that.overlayDiv.style.width = (bottomRight.x - topLeft.x) + 'px';
      that.overlayDiv.style.height = (bottomRight.y - topLeft.y) + 'px';
      that.overlayImage.src = that.get('url');
      that.overlayImage.style.width = (bottomRight.x - topLeft.x) + 'px';
      that.overlayImage.style.height = (bottomRight.y - topLeft.y) + 'px';
      that.overlayImage.style.opacity = that.get('opacity');
    }
  };

  that.addObserver('opacity', that.addOverlay);
  that.addObserver('visible', that.addOverlay);
  that.addObserver('url', that.addOverlay);
  that.addObserver('boundingBox', that.addOverlay);

  that.eventHandlers = {
    dragListener : function (evt) {
      var newGeo = that.map.pixelToGeo(
        that.map.width / 2 - evt.deltaX,
        that.map.height / 2 - evt.deltaY
      );
      that.map.set('center', newGeo);
      evt.stopPropagation();
    },
    dblClickListener :  function (evt) {
      evt.target = this.parentNode.parentNode;
      that.map.dispatch(evt);
    },
    mouseWheelListener :  function (evt) {
      evt.target = this.parentNode.parentNode;
      that.map.dispatch(evt);
    }
  };
};

GroundOverlay.prototype.attach = function (map) {
  this.map = map;
  var controls = map.getUIContainer().firstChild,
    child = controls.firstChild;
  controls.insertBefore(this.overlayDiv, child);

  map.addObserver('center', this.addOverlay);
  map.addObserver('zoomLevel', this.addOverlay);

  if (!this.evtTarget) {
    this.evtTarget =  nokia.maps.dom.EventTarget(
      document.getElementById('groundoverlay')
    ).enableDrag();
    this.evtTarget.addListener('drag', this.eventHandlers.dragListener);
    this.evtTarget.addListener('dblclick', this.eventHandlers.dblClickListener);
    this.evtTarget.addListener('mousewheel', this.eventHandlers.mouseWheelListener);
    this.addOverlay();
  }
};

GroundOverlay.prototype.detach = function (map) {
  this.map = null;
  map.removeObserver('center', this.addOverlay);
  map.removeObserver('zoomLevel', this.addOverlay);
  this.overlayDiv.parentNode.removeChild(this.overlayDiv);
};

GroundOverlay.prototype.getId = function () {
  return 'GroundOverlay';
};

GroundOverlay.prototype.getVersion = function () {
  return '1.0.0';
};


text:
Q: Does NightwatchJS support running tests by tags I see that there exists a "tags" support with NightwatchJS , as in
https://github.com/beatfactor/nightwatch/blob/master/examples/tests/github.js#L2
But could not see much documentation about how the "tags" could be used.
Neither in nightwatch --help
Is there a facility to run the tests based on these tags ?
For example,  run all tests with tag "sms" but exclude all with tag "mms" ?

A: Yes. See documentation: http://nightwatchjs.org/guide#test-tags

To select which tags to run, use the --tag command line flag:
$ nightwatch --tag login
Specify multiple tags as:
$ nightwatch --tag login --tag something_else


text:
Q: Error explode() expects parameter 2 to be string When using where function i want to remove some post that have specific restrict value
the posts are 2 type (artists and songs) , songs belong artists
i get the songs of artist by below code but when i use where function to remove some songs its not working ang got error
Error :

explode() expects parameter 2 to be string, object given

My Code
$rel = collect([]);
foreach ($post->artists as $artist) {
   $artist_posts = $artist->getPosts->where(function ($query) {
     $query->whereNotIn('restrict', ['res1'])->orWhereNull('restrict');
   })->sortbydesc('id');
   $rel = $rel->concat($artist_posts->where('type', $type));
}
$col = $rel->unique('id');

Post.php (model)
...
public function getPosts()
    {
        return $this->belongsToMany(Post::class, 'artists_posts', 'artist_id', 'post_id')->with('artists');
    }
 ...

A: You can't pass a Closure to the where method of Illuminate\Support\Collection. That is not a Query Builder you are calling where on, it is a Collection.
/**
 * Filter items by the given key value pair.
 *
 * @param  string  $key
 * @param  mixed  $operator
 * @param  mixed  $value
 * @return static
 */
public function where($key, $operator = null, $value = null)

If you wanted to call where on a Query Builder to do a database query you would have to use the actual relationship method not the dynamic property:
 $artist_posts = $artist->getPosts()->where(function ($query) {
                                  ^^

Then you would have to adjust sortbydesc to orderByDesc(...) and you would have to call get on the Builder to get the Collection of results.


text:
Q: Remainder addition Here is the problem.
We are given two numbers, a and m. We have to print if at some point 'a' will be divisible by 'm' or it will get stuck in a loop.
If a % m is not divisible then new value of a will be a = a + a % m.
My approach to solve the problem was to first check if remainder (a % m) is present in a set. If the remainder is present, we will get stuck in a loop otherwise store remainder (a % m) in a set. Continue until (a % m) is present in the set or until a is divisible by m.
My method got accepted but I don't know how it works. The solution is given as
for some K check if (a*2^k) is divisible by m. If yes, it will stop else it wont.
I tried a little by myself to derive the equation (a*2^k)
a = qm + r; where q is the quotient and r the remainder when divided by m
a = a + a % m
= qm + r + r;  since a % m = remainder = r
= qm + 2r
After some point, if loop stops then,
a = q'm + r, where r = 0
So equating, we get
qm + 2r = q'm + 0
(q' - q)m = 2r
(q' - q) = 2r / m
So if 2 * r is divisible by m, we will find that loop will stop(if my derivation is correct). If (a % m) is zero, we will stop. else remainder(r) > 0 then put all values of 1..m - 1 in the above equation and check if (2*r) is divisible by m
But we can't simply put all the values of remainder 1...m - 1 in the equation because we can't be sure if all the remainders appear in the sequence. So, how do I derive the above equation(a*2^k)?
Example:
a = 1, m = 5
Ans: It will get stuck in loop
Iter1. a = 1 + 1 % 5 = 2
Iter2. a = 2 + 2 % 5 = 4
Iter3. a = 4 + 4 % 5 = 8
Iter4. a = 8 + 8 % 5 = 11
If we go on, we will find that we will get stuck in a loop. So the answer is no.
a = 3, m = 6
Ans: It will stop.(yes)
a = 3 + 3 mod 6 = 6
a % m = 6 % 6 = 0; hence this will stop.(yes)
Recent problem on codeforces. Only solution was posted without any explanation.

A: (a + (a % m)) % m = (a + a) % m = (2 * a) % m, so a + (a % m) is divisible by m if and only if a + a is divisible by m and extending this means that you will stop if $2^k a$ is divisible by $m$ for some non-negative integer $k$.
So find the largest odd divisor of $m$ and call it $o$ (easily done by taking the prime factorisation of $m$ and ignoring the powers of $2$).  You will stop if and only $o$ divides $a$.
You can find which step you will stop at by comparing the largest power of $2$ which divides $m$ with the largest power of $2$ which divides $a$.


text:
Q: NSFetchedResultsController challenge for tags and content Is it a way to show in a tableView tags and the relating content?
TAG1
  (TAG1 > )C1
  (TAG1 > )C2
TAG2
TAG3
  (TAG3 > )C3
  (TAG3 > )C1

What predicate and sortDescriptors need for NSFetchRequest? Is it even possible?
let fr = NSFetchRequest(entityName: "TagOrContent")
fr.sortDescriptors = [/* .. */]
fr.predicate = NSPredicate(format: " ... ", /* .. */)
frc = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: mainMOC, sectionNameKeyPath: nil, cacheName: nil)
frc!.delegate = self
frc!.performFetch(nil)

A: I would probably use 2 FRCs - 1 for Tags and another for Content.
The Tag FRC controls the sections in the table view, but not rows. Tag information is shown in section headers. The sectionNameKeyPath needs to be set so that each Tag is returned in a separate section. You can add a button to each section header to detect taps to manage collapse of the section.
The Content FRC exists only to monitor the context for changes and cause reloads of the section to which they belong (based on the Tag they are connected to).
If you want to hide a full tag section then you should remove the rows and set the section header height to zero, so the section still exists but isn't visible. Otherwise you will have indexing issues.


text:
Q: JBoss WAR Deployment problem (caching problems?) I'm trying to deploy my war file on JBoss 4.2.3. This application was working fine and still is working fine (sans the bugfix that I've put into my code). I have made a new war file with a bug fix in it (which involves passing some extra http request params while requesting another app's servlet). However, when I tried to deploy this seemingly innocuous war file, I see the console logs from Jboss that say the new war file has been deployed etc. However, I don't see my changes reflecting in the browser (i.e, the extra params are not being sent in the request). I've verified that the war file that has gone into /server/default/deploy is exactly the same (cksum's are the same). I tried these few usual tricks to no avail: deleted the old war file from server before deploying the new one, restarted the server to free any cached stuff. Even put a return in my servlet at entry point. But still no difference! The servlet works just like before without the fix. Any suggestions?
I request you to kindly help me. I kinda screwed if this doesn't work.

A: A couple of thoughts

*

*maybe your browser is 'offline' or using the cache, try clearing the cache / refresh

*delete the contents under the server/default/tmp and server/default/work folders also

A: You could try adding some logging statements to your application, and see if they're output when you redeploy the war...
If it is definitely being redeployed then perhaps, as skaffman says, the fix didn't work.


text:
Q: What do I do when a question can't be answered? The FAQ mentions bounty, but sometimes a question just doesn't really have a right answer:

*

*No solution exists

*The question as written is unanswerable and unsalvageable

*There may be a technically correct answer, but the asker is unable to utilize it for some reason.

In these cases, a bounty, and more answers, won't really help. What is the appropriate etiquette in these cases? Should the question be closed? Left hanging?

A:

*

*No solution exists

If this is known, then it's fine to add and accept an answer stating there is no answer, and why, under what conditions, etc.
If this is not known, there's really no choice but to leave the question open and use one of the aformentioned methods to draw attention to the question in the hope that someone will be able to offer a bit of help.

*

*The question as written is unanswerable and unsalvageable

These types of questions are normally closed off quickly, so anything that's totally unanswerable won't remain in the system. Those few that get through will just end up abandoned... there's really nothing else that can be done with them unless they get cleaned up by the original author.

*

*There may be a technically correct answer, but the asker is unable to utilize it for some reason.

Since there's a correct solution that would work for others, it's fine to accept the answer even if it didn't solve the original specific problem.
Most of the time in this case, the technically correct answer will lead to another solution, or another approach to the problem entirely. At that point, if the author needs help, it would be better to start a new question with a reference to the first one stating why that solution doesn't work in this situation, and repeat this whole process.

A: I see no reason not to leave it hanging. Several reasons:

*

*A user may have the same question and see the progress in your question

*A user may find your question and answer it

*It can be the base question for duplicates to be pointed to/merged to

A: If there's no solution, saying so is a valid answer.
If the question is too vague, if the system is working correctly it will be closed as "not a real question" before it's eligible for a bounty.  (If it isn't, well, there's flaws in all systems.)
If there are answers that don't apply, it still may be worthwhile suggesting them.  This may be useful for other readers, or may suggest a reason, or the OP's restrictions may not be as inflexible as he or she thinks they are at first.


text:
Q: MercurialEclipse automatically adds tag named tip I use the MercurialEclipse Plugin for Eclipse, with a - you guessed it - Mercurial repository (on bitbucket).
But unfortunately somehow my Eclipse tags all my commits with the word 'tip'
and I have no idea where and how and why.
Where can i remove it?
It's particularly annoying when I work with other people who dont tag their commits, because I always have to merge before each push.
Here are some pictures of the tag-screens,
so yuo can see that there are no tags. So it shouldn't tag anything - but it still does.

and interestingly it always says 'tip' next to my Project-Name

but why?
i dont understand - how do I remove it??

A: That's just the tip of your repository, it's not an actual tag created by hg tag.
Here's the explanation on Mercurial's wiki.


text:
Q: Using selenium I want to scrape this text Hello guys I am trying to scrape from this url the following text using selenium:

But I get the error that it couldnot find any element by that class name.. This is my code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

driver = webdriver.Chrome(r'C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\chromedriver_py\chromedriver_win32.exe')
driver.get('https://xangle.io/project/XTZ/full-disclosure')
driver.find_element_by_class_name('fv1').text

A: Induce WebDriverWait() and visibility_of_element_located() and following xpath.
driver.get("https://xangle.io/project/XTZ/full-disclosure")
print(WebDriverWait(driver,15).until(EC.visibility_of_element_located((By.XPATH,"//div[text()='Token Name']/following-sibling::div[1]"))).text)

OR
print(WebDriverWait(driver,15).until(EC.visibility_of_element_located((By.XPATH,"(//div[@class='token-profile-cont']//div[@class='fv1'])[1]"))).text)

Import following libraries.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

A: The error is because there are multiple elements with the same class name.
Use XPATH to better traverse the page identify the element required.
WebDriverWait(driver,15).until(EC.visibility_of_element_located((By.XPATH,"//div[contains(@class, 'token-name')]/div[2]")))

driver.find_element_by_xpath("//div[contains(@class, 'token-name')]/div[2]").text

This will give you the Token name text content.


text:
Q: What's the big deal about manifolds with boundary? I am revisiting some self-study I have done of manifolds. I often see statements such as "this holds for manifolds with or without boundary" or, "this only holds for manifolds without boundary", etc. This leads me to a general question:
What is the main issue/issues that arise when dealing with manifolds with boundary?
Is it simply the fact that in order to do arguments for points on the boundary, you have to consider smooth extensions of functions, while you do not have to do this for interior points?
Thanks!

A: One particular example:
"Cobordisms are studied both for the equivalence relation that they generate, and as objects in their own right. Cobordism is a much coarser equivalence relation than diffeomorphism or homeomorphism of manifolds, and is significantly easier to study and compute. It is not possible to classify manifolds up to diffeomorphism or homeomorphism in dimensions ≥ 4 – because the word problem for groups cannot be solved – but it is possible to classify manifolds up to cobordism. Cobordisms are central objects of study in geometric topology and algebraic topology."
https://en.wikipedia.org/wiki/Cobordism