text:
Q: Porqué se usa [0] Javascript

<!DOCTYPE html>
<title>Ejemplo aprenderaprogramar.com</title><meta charset="utf-8">

Cursos aprenderaprogramar.com

Ejemplos JavaScript

 Probar

Porqué se usa
var nodoBody = document.getElementsByTagName('body')[0];

en [0] ?

A: Entre los conceptos básicos de programación está el de colección.
En JavaScript, a partir de ECMAScript 6,

*

*Las colecciones pueden ser ordenadas mediantes claves/llaves (en inglés keys) o mediante índices.

*A una colección ordenada mediante índices se le conoce como matriz o arreglo (en inglés array).

*La numeración de índices comienza en 0.

*El colocar los corchetes inmediatamente después de un objeto y entre estos una clave o número sirve para llamar al miembro correspondiente de la colección.

El método getElementsByTagName(tagname) devuelve una colección, la cual puede ser una colección vacía, de uno o más miembros.
Considerando lo anterior,
document.getElementsByTagName('body') devuelve una colección formada por todos los elementos con la etiqueta body, si sólo hay uno, como es el caso del HTML incluído en la pregunta, la colección tendrá un sólo miembro, para llamar a ese miembro se usa el índice 0, que corresponde al primer miembro de la colección, lo cual se realiza de la siguiente forma:
document.getElementsByTagName('body')[0]
Si no quieres usar un método que devuelve una colección, usa getElementById('id'),pero para ello deberá agregar un el atributo id al elemento, que en este caso es body.

A: getElementsByTagName() retorna una coleccion de elementos, sin importar de tag se trate.Si no hay elementos retorna una coleccion vacia. Si hay un solo elemento, este esta en la posicion 0 (cero), y asi sigue.
El [0] es para obtener el unico elemento body que hay en la pagina.


text:
Q: Solr payloads: count terms with highest payload value Imagine we have these documents in solr
{id: 1, values: [foo|0.7, bar|0.3] }
{id: 2, values: [foo|0.6, bar|0.3] }
{id: 3, values: [foo|0.2, bar|0.4] }

What I want to get as a result is counts of terms but only account one term per document, the one with the highest payload value, so result is:
foo: 2
bar: 1

Because for doc with id = 1 foo has highest payload value, for id = 2 again foo has highest payload value and for id = 3 bar has the highest payload value.
How would I get this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Importing data from Excel into SQL Server that has a different design in the template in Excel I am developing a system that will import and export a data from Excel into a SQL Server database. I already done in exporting, my problem is in importing the template that I will import is different template that I exported. I know the code about importing because I learned it in google, but in my problem is, I can't get what I need. So allow me to show a screenshot about the template in my Excel.

That's the template, and my database design is like this:

So the PODATE and PORECEIVEDDATE there in database is equal to the PO DATE below in Excel and DELIVERYDATE is equal to ETD in Excel.
As of now I have a code here that will get only the above template and it will not get the whole data in Excel.
Here is my code:
public void ImportDataFromExcel(string excelFilePath)
{
        string ssqltable = "tmp_100_POEntry_SF_sample";
        //string myexceldataquery = "select PONO,PODATE,PORECEIVEDDATE,DELIVERYDATE,PARTCODE,QUANTITY,UNITCOST,TOTALAMOUNT,STOCKS,INCHARGE,CLIENT from [Sheet1$]";
        string myexceldataquery = "select [PO NO],[PART CODE],QUANTITY,[UNIT COST],[TOTAL AMOUNT],STOCKS,[IN CHARGE],CLIENT from [Sheet1$]";

        try
        {
            string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + excelFilePath +
            ";extended properties=" + "\"excel 8.0;hdr=yes;\"";

            string sclearsql = "delete from " + ssqltable;
            SqlConnection sqlconn = new SqlConnection(Common.connectionstring);

            SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);

            sqlconn.Open();
            sqlcmd.ExecuteNonQuery();
            sqlconn.Close();

            OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
            OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
            oledbconn.Open();
            OleDbDataReader dr = oledbcmd.ExecuteReader();
            SqlBulkCopy bulkcopy = new SqlBulkCopy(Common.connectionstring);
            bulkcopy.DestinationTableName = ssqltable;

            while (dr.Read())
            {
                bulkcopy.WriteToServer(dr);
            }

            dr.Close();
            oledbconn.Close();
        }
        catch (Exception ex)
        { throw ex; }
}

That code is really have an error if I add the PODATE, PORECEIVEDDATE and DELIVERDATE. All I just want is to get the 3 remaining parameters value from Excel into the database.
I don't want to change the template in Excel because of some reason.
Please I badly need your help guys. I really appreciate it.


text:
Q: ESX Root User Cannot Reboot Server I have a machine running ESX v3.5 and the root user is unable to perform tasks like shut down the esx server, create new VM's, manage roles, pretty much everything except for starting and stopping VM's.
How do I (re)set these permissions?
UPDATE: I found this forum post. Am thinking of trying out the process described in the last post in that thread.

A: Seems like someone removed root's access on the VIC, you're going to need to go into the VIC with a user with Administrator permissions. The click on your host, go to the Permissions tab and change root back to administrator.
I half remember that there is a way to do this on the console, but I'm having trouble finding it right now.

EDIT: Found the console stuff
Ok, yep you can fix this on the console.

You'll need to edit the file /etc/vmware/hostd/authorization.xml from the console.
You should seen something like this:
<ConfigRoot>
  <ACEData id="10">
    <ACEDataEntity>ha-folder-root</ACEDataEntity>
    <ACEDataId>10</ACEDataId>
    <ACEDataIsGroup>false</ACEDataIsGroup>
    <ACEDataPropagate>true</ACEDataPropagate>
    <ACEDataRoleId>-1</ACEDataRoleId>
    <ACEDataUser>root</ACEDataUser>
  </ACEData>
<... SNIP Other USERS ... >
<... SNIP Possible custom roles ...>
</ConfigRoot>

The piece you are going to want to change is the "ACEDataRoleId" (-1 is Administrators)
you might have to restart the hostd service with service mgmt-vmware restart after your changes.


text:
Q: send parameter using submit, PHP
*

*<input type = "submit" name = "ok" value = "<? php echo $ _POST ['no'];?>">

*<input type = "submit" name = "ok" value = "ok">
what if I want to send parameters using submit. if i use the number 2 then value on submit = "ok", but the parameters that will be sent is "ok". but when using the number 1, then the value on submit depending on the value of $ _POST ['no'], but managed to send parameters.
I want to ask how can I make permanent value "ok" but sends the parameters depend on $ _POST ['no']?

A: from what I understand you are looking for a hidden field:
<input type = "hidden" name = "someField" value = "<? php echo $ _POST ['no'];?>">
<input type = "submit" name = "ok" value = "ok">

A: Add a second <input> element to maintain the value of $_POST['no']. HTML provides the <input type="hidden"> input for this explicit purpose:
<input type="hidden" name="ok" value="<?= $_POST['no'] ?>" />
<input type="submit" value="ok">


text:
Q: How to build the latest Version of WSO2 Identity Server I would like to test if the newest head/trunk/master version of WSO2 Identity Server.
I found a version on gitlab (https://github.com/wso2/platform) an a version SVN (https://svn.wso2.org/repos/wso2/carbon/platform/trunk/)
What is the preferred way to build the latest version of WSO2 Identity Server.
kindly regards Philipp

A: Latest version of Identity Server is 5.0.0. Using this release matrix, you can find the branch, chunk and patch that identity server 5.0.0 has been released.  It is Turing branch , chunk 11 and kernal patch 0008.  You can find chuck 11 from here and kernel patch from here
However if you need to build the current version.  Then i am not sure the exact chunk and patch as it is not release. However it must be the highest chunk value and patch value that are available in same location that i have shared for 11 and 0008
Still Identity Server is not used the github to release it.


text:
Q: Keep annotated clutter away from Domain Model I'm in the situation where I have a Domain Model that is clean. By clean I mean it's just a collection of private properties and getter and setters. I guess that's what's ment by the Anemic Data Model.
This model is interchangeable with other applications (can be shared with other application code) without pulling in extra dependencies.
This model needs to be serialized to different data formats. For this I can use a wide range of annotations that greatly simplify my life.
Only they pull in an extra set of dependencies in all the projects that will share the domain model.
I've read it's not advised to clutter the domain model for such reasons and I could possibly land in a Jar Hell.
I could write a wrapper that is annotated and pass in the domain model in the constructor and copy all the properties over to the annotated model. This way I can happily use annotations while keeping a clean Domain Model that will not enforce any extra dependencies.
This is not specifically about serializing your data model but about adding extra functionality (for example through annotations) in your Domain Model that enforces new dependencies.
How do you handle such use cases what's a safe way to handle this without having to fear Jar Hell ?

A: You only have to use the annotations at compile time.
If the annotation classes are not available at runtime they will simply not exist.
E.g. if the client code calls AnnotatedElement.getAnnotations() on a
domain model class and the annotations it was compiled with are not available in the class path they will not be returned.
If you use maven you should declare the annotation dependencies with scope optional.
Optional dependencies will not be included in the client.
Thus they are only available if the client declares them.
For example:
If Proj-A has a optional dependency ( ?-> ) on Proj-B
 Proj-A ?-> Proj-B

and a Proj-X references Proj-A as a compile dependency it will not get the optional dependency Proj-B.
 Proj-X -> Proj-A

because transitive dependency resolution ends on an optional dependency.
Expect that you have the following annotation in a jar file called annotations.jar
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ARuntimeAnnotation {

}

and you have the following model class contained in a model.jar
@ARuntimeAnnotation
public class Model {

}

and the model.jar has a dependency to the annotations.jar because it needs it to compile.
<depdendency>
       <groupId>someGroup</groupId>
       <artifactId>annotations</artifactId>
       <scope>optional</scope>
 </dependency>

If this dependency is optional it will not be automatically become a transitive dependency of someone how only has a dependency on the model.jar.
Now a client wants to use the Model class. Thus it has a dependency to model.jar.
 <depdendency>
       <groupId>someGroup</groupId>
       <artifactId>model</artifactId>
 </dependency>

If the client also wants to see the annotation ARuntimeAnnotation it must also include the
annotations.jar as a dependency, because it is optional.
If the client does not include dependency on the annotations.jar the following call will return an empty array:
 Model.class.getAnnotations(); // will be empty if the annotations.jar is not available at runtime


text:
Q: c++ what are the header files to include for using CP_UTF8 and WideChartoMultiByte Which header files do I have to include to use CP_UTF8 and WideChartoMultiByte
I am getting errors that they are not in scope.
I am working on Codeblocks in Linux (Debian)

A: That's just <windows.h>.

A: WideChartoMultiByte is a windows API. Maybe you should use std::codecvt.
Note that there is a know issue about partial on both gcc and VC. I just stuck on them few days ago.


text:
Q: base query method in CodeIgniter Im trying to create a base query that I can then use later to add grouping or filters
simplified example:
function baseQuery()
{
    $query = $this->db->select('*')
    return $query;
}

function queryWhere($value)
{
    $query = $this->baseQuery();
    $query->where($value)
    $result = $query->get();

    return $result
}

What is the correct way to do this in CodeIgniter?

A: Your code needs some dynamic values like table and field names for extending single purpose of query
Take a look on example
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Testing extends CI_Controller {

    public function baseQuery($fields,$tableName)
    {
        $query = $this->db;
        $query->select($fields);
        $query->from($tableName);
        return $query;
    }

    public function queryWhere($whereCondition)
    {
        $query = $this->baseQuery('*','tablename');
        $query->where($whereCondition);
        $result = $query->get();
        return $result;
    }
    public function index() {

        $query = $this->queryWhere("id > 0");
        $data = $query->result_array();
        print_r($data);
    }

}


text:
Q: Facebook LogginButton integration on Android

I am trying to integrate Facebook login button into my android application.  I am following the code specified in facebook sdk docs.  The application shows the facebook login button and when I click on it, it brings on the facebook login activity.
The problem is that after I have logged in, NO events are fired.  I would expect onSuccess method to execute if my credentials were accepted by facebook, or onCancel if I cancel the login.
What am I missing?  Also can someone recommend a good facebook-android integration tutorial in addition to what is already on the facebook developer site?
Thank you.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_main);
    callbackManager = CallbackManager.Factory.create();
    loginButton = (LoginButton) findViewById(R.id.login_button);

    loginButton.setReadPermissions("user_friends");

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            String test = "";
        }

        @Override
        public void onCancel() {
            String test = "";
        }

        @Override
        public void onError(FacebookException exception) {
            String test = "";
        }
    });
}

A: Have you write onActivityResult()
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

A: Add this to your Activity for registering callback:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
}


text:
Q: How can I change the bit rate of MP3s in iTunes 11? TL;DR I have a number of MP3 albums in iTunes that I would like to convert from 196kbps to 128kbps.

I ripped a number of CDs into iTunes at 196kbps, but have decided that I want them to be at 128kbps to conserve space - as a compilation of them will be downloaded from the internet, by others, later.
I opened iTunes preferences and changed the import settings to 128kbps, then selected File -> Create New Version -> Create MP3 Version, after selecting the files from one of the albums. This worked great and it created a lower bit rate copy of the files. In Finder it appends a "1" to the end of each track name - so I see:

Track 01
Track 01 1
Track 02
Track 02 1
     etc.

However, in iTunes it is just:

Track 01
Track 01
Track 02
Track 02
     etc.

Thus it is difficult to tell - without opening "Get Info" on every file - which one is the 128kbps.
I consulted this KB article, but the information in it didn't seem to exactly match my setup (even though I am running iTunes 11 on OSX 10.8). For example, in step #3 it says to go to File -> "Create New Version" -> "Create Format Version". The closest thing I could find is what I mentioned above, and I wasn't able to find "Create New Version". Even then it looked like it would evoke the same situation as what I have.
Also, when I open Finder and delete the original files, iTunes recognizing them even though they are in Trash. Perhaps there would be a re-index that?
How can I convert the files I have, or have iTunes display the "1" addendum in the track listing? Should I just re-rip the files, or is there another software I should turn to?

A: Although quality will be lost when converting the bit rate to 128kbps, one option is to use a combination of a smart playlist in iTunes and Max.
1) Either back up music library or specify a different output directory in Max, and then re-import files to iTunes.
2) In iTunes, create a smart playlist where the bit rate is greater than 128 kbps for example.
3) Select the files from the playlist and drag them to the conversion window in Max. Preferences in Max should be setup so that the output files will be stored in the same location as input files if you want the originals replaced. There is also an option checkbox to "Overwrite existing files" and "Delete source files after encoding". This will take care of the re-naming issue. There is also an option to add output files to the iTunes library under the iTunes 'tab'.
Depending on the size of your library, it may be necessary to convert the mp3 files in chunks.

A: I have realised that importing files I have downloaded, the bitrate of the file will remain, no matter what it is. Unlike importing a CD which will import it at the settings you choose.
So, to decrease file size, I set the import bitrate to the desired rate (e.g. 128 kbps) and select all of the files I want to convert. Once highlighted, right click the lot and choose Create MP3 Version. Do not click on anything until it is completely finished encoding. Only then, right click one of the highlighted tracks, and choose Delete and Move to trash.
As a bonus you can add columns for Bit Rate and Date Added to the track list by right-clicking in the header line.


text:
Q: I want dynamic image change with some animation. I want image change randomly on a single img tag src and also with animation effect when it changes. I have done with image change but i want some special effect on random image.
Using css and jquery.


text:
Q: How are question title slugs generated so magically? (ß) I was just looking through some old posts and I noticed that a "ß" in a question title magically turns into an "ss" in the URL slug.
What function is being used to format the slugs? Clearly it has some advanced behavior in terms of determining character equivalents, rather than just ignoring special characters.
(Note: I just tried this with "fi" and "fl" and they're not converted to "fi" and "fl"...)

A: Assuming the current implementation is still similar (although Jeff mentions looking into another approach)...
Taking 80 characters from the raw title, , ,, ., /, \, and _ are replaced with -, collapsing consecutive such characters into a single dash. Latin alphabetic characters are converted to lowercase, and the following substitutions are made:
àåáâäãåą => a
èéêëę    => e
ìíîïı    => i
òóôõöø   => o
ùúûü     => u
çćč      => c
żźž      => z
śşš      => s
ñń       => n
ýŸ       => y
ł        => l
đ        => d
ß        => ss
ğ        => g
Þ        => th
ĥ        => h
ĵ        => j

Finally, if the above process resulted in the trailing dash, it is removed.


text:
Q: FluentSecurity makes Azure WebRole to fail I have a ASP.NET MVC website using FluentSecurity. As a Azure Website it works just fine. I need to make it a WebRole. I added a WebRole project but the WebRole fails at startup with a generic "The page cannot be displayed because an internal server error has occurred."
I have a DenyAnonymousAccessPolicyViolationHandler and RequireRolePolicyViolationHandler implementing IPolicyViolationHandler and the whole FluentSecurity setup according to http://blog.mariusschulz.com/setting-up-fluentsecurity-to-use-ninject-for-dependency-resolution.
I discovered that when I delete both classes implementing IPolicyViolationHandler then then WebRole starts just fine. I created a sample project demonstating this issue, you can find it at https://dl.dropboxusercontent.com/u/73642/MvcApplication1.zip.
So how can I get the FluentSecurity work with Azure WebRole including my policy classes?

A: We had the same problem; working on a Website, but not in a Web Role.
It was because Fluent Security references MVC3, not MVC4. The comments to this bug on Github go into further detail https://github.com/kristofferahl/FluentSecurity/pull/39.
You can either:
1) Take a local copy of the FluentSecurity.csproj and upgrade it's System.Web.MVC reference to MVC 4, then include it in your solution (this is what we did).
2) Or, as per the Github bug link above "...fix this using assembly redirect in your web.config" like this
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
  </dependentAssembly>
</runtime>


text:
Q: Understanding the function of Boost capacitor I'm going through this MOSFET Driver IC - MIC5021.
Since this is a high side switch, the gate voltage should be higher than the source voltage, which would be the Source voltage, Vdd.
According to the datasheet,

If the vdd voltage is 12V, then the gate voltage typ would be 18V, which seems logical. We might need to select the MOSFET's gate-source threshold voltage according to this.
One small question is what would be the gate voltage if the Vdd is 24V? What can be assumed so as to select the MOSFET gate - source threshold voltage?
But my actual question is how does the Boost capacitor help? Does the boost capacitor help to boost the Vdd voltage and provide the boost voltage to the GATE pin?
Also, different configurations are mentioned in Figures 6-1, 6-2 & 6-3. Do small capacitors imply small time constant, hence charging happens faster? But in that case, for high voltage configurations, the capacitor value should be less right?
But for the highest voltage config of figure 6-3, 20V to 36V, the cap recommended is 10nF. But for 12V-36V configuration, the cap is lesser 2.7nF?
Unable to understand this clearly. Request some help on this.


text:
Q: Compile chokes on floating table. "Missing number, treated as zero. " error I'm compiling a doc and I get the following error no matter what I try.
LaTeX Warning: Reference `LastPage' on page 4 undefined on input line 256.

<use logo.jpg> [4 <./picture4.png> <./picture4.png>]
! Missing number, treated as zero.
<to be read again>
                   |
l.285 ...5cm} | p{1.25cm} | p{3.0cm} | p{4.5cm} |}

?
! Illegal unit of measure (pt inserted).
<to be read again>
                   |
l.285 ...5cm} | p{1.25cm} | p{3.0cm} | p{4.5cm} |}

?
)
Runaway argument?

! File ended while scanning use of \TX@get@body.
<inserted text>
                \par
<*> Input_API.tex

Yes, I have googled and searched this (and other) sites for an answer to this. Snarky comments not required.
Here are my packages
%% Doc Class Declaration %%
\documentclass[a4paper]{article}
\usepackage[margin=4.5cm]{geometry}

%% Additional packages to use %%
\usepackage{amscd,amsmath,amssymb,verbatim}
\usepackage[TS1,OT1,T1]{fontenc}
\usepackage{graphics}
\usepackage{float}
\usepackage{times}

%% These packages are symbols %%
\usepackage{fourier}
\usepackage{bbding}
\usepackage{dingbat}

%% Word wrap in tables %%
\usepackage[english]{babel}

%% Other Stuff
\usepackage{fancyhdr}
\usepackage{lastpage}
\usepackage[xindy,nonumberlist,acronym,toc]{glossaries}
\usepackage[colorlinks]{hyperref}
\hypersetup{linkcolor=black,urlcolor=blue2,citecolor=black,filecolor=black}
\usepackage[usenames,dvipsnames,table]{xcolor}
\usepackage[pdftex]{graphicx}
\newcommand{\HRule}{\rule{\linewidth}{0.5mm}}
\usepackage{pifont}
\usepackage{enumitem}
\usepackage{tabularx}

I have other tex docs that are highly similar to this one that compile fine. For the life of me I cannot pinpoint the diff.
Here is the block of code just before line 256.
\begin{figure}[H]
\centering
\framebox{\fboxrule=0.1cm{\includegraphics[width=0.9\linewidth]{picture4.png}}}
\caption{blah blah blah text.}
\label{fig:Picture number Four}
\end{figure}

Any help or guidance is much appreciated.
UPDATE 1:
Full tabularx env for Xavier

\subsection{API Actions}
\smallskip
\begin{center}
\rowcolors{1}{blue1}{grey2}
\begin{tabularx}{ | p{2.5cm} | p{1.25cm} | p{3.0cm} | p{4.5cm} |}
\hline
\textbf{Action} & \textbf{(C)reate (U)pdate} & \textbf{Params} & \textbf{Comments}\\ \hline
\hiderowcolors
place\_order & CU & order\_id & Orders can be placed as though
 specific customers were driving the form.\\ \hline
submit\_order & U & order\_id & Submits the specified order. Order submit
constraints must be met (e.g. if you have "charge code" as a
 required field and the order has no "charge code",
then the API request will fail. \\ \hline
order\_purchasing\_information & U & order\_id & Updates am order's purchasing information.
The billing address, shipping address, purchase contact,
and charge code information may be set via this action. \\ \hline
user\_address &  CU & address\_id, type, user\_id & Creates or updates a user address.
If creating a new address you must supply the type and user\_id parameters,
where type is S (shipping), B (billing) or P (purchase contact).
If updating an existing address only the address\_id parameter is required. \\ \hline
primer & CU & primer\_id & \\ \hline
instrument & C & instrument\_id & \\ \hline
user & CU & user\_id & \\ \hline
lab\_group  & CU & lab\_group\_id & \\ \hline
charge\_code & CU & charge\_code\_id & \\ \hline
template & CU & tempalte\_id & \\ \hline
container\_map & U & container\_id & This action updates the location map (a two-column text string that maps container locations to template barcode) for an existing container. Useful for automatically updating the contents of a plate that was just scanned by a bed scanner. \\ \hline
inventory\_item & CU & & inventory\_item\_id \\ \hline
update\_template\_step & U & template\_id (\textit{n}-many) & Updates the step of a supplied list of tempaltes to
the next step in their workflow. \\ \hline
update\_container\_step & U & container\_id (\textit{n}-many) & Updates the step of a list of provided containers.\\
\hline
\end{tabularx}
\end{center}

A: You forgot to specify the width of the tabularx environment - a requirement:
\begin{tabularx}{<width>}{<col spec>}
%...
\end{tabularx}

However, you're not using any X-columns - the special stretchable columns within tabularx. So, I suggest just removing the use of tabularx altogether, and use a traditional tabular.


text:
Q: Дата и время. Угол солнца над горизинтом Определить угол солнца над горизонтом, зная время суток. Исходные данные: солнце встает на востоке в 6:00, что соответствует углу 0 градусов. В 12:00 солнце в зените, а значит угол = 90 градусов. В 18:00 солнце садится за горизонт и угол равен 180 градусов. В случае, если указано ночное время (раньше 6:00 или позже 18:00), функция должна вернуть фразу "I don't see the sun!".
from datetime import datetime
def sun_angle(time):
    #replace this for solution
    list_fortime=[]   #пустой список для значений
    dt = datetime.strptime(time, '%H:%M')   #перевод из строки
    tt=datetime.timetuple(dt)   # struct_time
    for it in tt:
        list_fortime.append(it) # заполняем новый список
    if list_fortime[3]>=6 and list_fortime[3]<=18:
        time_1=(list_fortime[3]-6)*15 #1 час= 15 градусов
        time_2= (str(list_fortime[4])+str(list_fortime[5]) #1 минута 0.25 градуса
        time_3 = int(time_2) #тут ошибка , возможно с преобразованием типов ,подскажите что не так
        return time_1+time_3
    else:
        return 'I don\'t see the sun!'

    #return tt
    #if tim[]>=6
    #return time

if __name__ == '__main__':
    print("Example:")
    print(sun_angle("07:00"))

    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert sun_angle("07:00") == 15
    assert sun_angle("01:23") == "I don't see the sun!"

подскажите где ошибаюсь и альтернативный способ.

A: Попробуйте так:
from datetime import datetime as DT

def sun_angle(tm):
    dt = DT.strptime(tm, "%H:%M")
    if not (6 <= dt.hour <= 18):
        return "I don't see the sun!"
    # возвращаем число минут начиная с [06:00] умноженное на 0.25
    return ((dt.hour - 6) * 60 + dt.minute) * 0.25

A: Вы используете что-то уж очень сложное. Несколько структур данных, и прочее. Нужно провести анализ задачи: время должно быть в диапазоне от XXX Минут до YYY минут.
Первое решение
def sun_angle(time):
    #replace this for solution
    list_fortime=[]   #пустой список для значений
    dt = datetime.strptime(time, '%H:%M')   #перевод из строки
    #Восход и закат в минутах
    startOfSun=6*60
    endOfSun=18*60
    #переводим время в минуты
    tt=dt.time().hour*60+dt.time().minute
    #Если время в диапазоне, то считаем угол как долю от дуги окружности.
    if tt in range (startOfSun,endOfSun+1):
        return 180*(tt-startOfSun)/(endOfSun-startOfSun)
    else:
        return 'I don\'t see the sun!'

И решение с использованием только datetime
from datetime import datetime
def sun_angle(startSun,endSun,time):
    dt = datetime.strptime(time, '%H:%M')   #перевод из строки
    startOfSun=datetime.strptime(startSun, '%H:%M')   #перевод из строки
    endOfSun=datetime.strptime(endSun, '%H:%M')   #перевод из строки

    #Если время в диапазоне, то считаем угол как долю от дуги окружности.
    if dt>=startOfSun and dt<=endOfSun:
        # переводим время в минуты
        tt = dt.time().hour * 60 + dt.time().minute
        tStart=startOfSun.time().hour * 60 + startOfSun.time().minute
        tEnd = endOfSun.time().hour * 60 + endOfSun.time().minute
        return 180*(tt-tStart)/(tEnd-tStart)
    else:
        return 'I don\'t see the sun!'

if __name__ == '__main__':
    print("Example:")
    print(sun_angle("6:00","18:00","12:00"))


text:
Q: Aerospike connect using JavaScript I want to connect to Aerospike server (using IP address:3000) using JavaScript only, without any between layer (like node.js). Does anyone have a clue, how to do it?

A: It impossible because JS cant create direct connect to RAW Socket.


text:
Q: How to write text in jupyter / ipython notebook? Here is an example of IPython notebook in which besides the input and output cells we have a plain text. How can I do the same in my IPython notebook? At the moment I have inly In and Out cells.

A: Simply Enter Esc and type m it will convert to text cell.

A: Adding to Matt's answer above (as I don't have comment privileges yet), one mouse-free workflow would be:
Esc then m then Enter so that you gain focus again and can start typing.
Without the last Enter you would still be in Escape mode and would otherwise have to use your mouse to activate text input in the cell.
Another way would be to add a new cell, type out your markdown in "Code" mode and then change to markdown once you're done typing everything you need, thus obviating the need to refocus.
You can then move on to your next cells. :)

A: As it is written in the documentation you have to change the cell type to a markdown.

A: Change the cell type to Markdown in the menu bar, from Code to Markdown. Currently in Notebook 4.x, the keyboard shortcut for such an action is: Esc (for command mode), then m (for markdown).

A: Step 1: Click on the '+' to create a new cell, type some text in, and select 'Markdown' in the dropdown

Step 2: It should now look like this:

Step 3: Click anywhere in the cell and click on 'Run'. Now it looks how you expect it to.


text:
Q: Finding $b-a$ for positive integer $a$, $b$ satisfying $\sum_{x=1}^\infty\frac{3x^2+12x+16}{(x(x+1)(x+2)(x+3)( x+4))^3}=\frac1{4(a!)^b}$
$$
\sum_{x = 1}^{\infty}\frac{3x^{2} + 12x + 16}
{\left[\vphantom{A^{A}}x\left(x + 1\right)\left(x + 2\right)
\left(x + 3\right)\left(x + 4\right)\right]^{\, 3}} =
\frac{1}{4\left(a!\right)^{b}}
$$
Compute $b-a$ if $b$ and $a$ are positive integers.

I asked my teacher to help me in solving this sum. But, unfortunately, he said I can't. it is a very hard question, So, I hope you can help me in solving this problem.

A: The answer is $\color{green}{-1}$.
Indeed, the sum converges very quickly (the terms are $\Theta(x^{-13})$) and the inverses of the partial sums are
$$55741.9354839\\
55312.3888560\\
55297.2897327\\
55296.1612133\\
55296.0276428\\
55296.0059708\\
55296.0015387\\
55296.0004559\\
55296.0001513\\
55296.0000551\\
\cdots$$
Obviously, this tends to $4\cdot4!^3$.


text:
Q: How to print and connect to printer using flutter desktop via usb? I want to connect to the printer via usb but I cant find any solutions to do this.

A: *

*Download PDFtoPrinter.exe http://www.columbia.edu/~em36/pdftoprinter.html

*Use it by running spwan procceses
https://api.dart.dev/stable/2.17.6/dart-io/Process-class.html

A: You can try this package, it too easy to use:
https://pub.dev/packages/flutter_pos_printer_platform

A: you can use  printing package  https://pub.dev/packages/printing i think it would help you


text:
Q: Pyspark : How to create union table for some selected columns from df I have below pyspark dataframe -

I want to convert this to. Basically all 3 id columns stacked to each other

I can do this by creating 3 separate dataframe for each of 3 id columns and then do the union of all. But I am looking for a solution which can achieve this in fewer lines because I have at least 25+ id columns in main file.

A: Try by casting source_* columns to array then explode.
Example:
df.show()
#+---------+-----------------+-----------------+-----------------+--------+
#|movieName|Source_1_movie_id|Source_2_movie_id|Source_3_movie_id|   genre|
#+---------+-----------------+-----------------+-----------------+--------+
#| example1|          movie_1|          movie_4|          movie_7|  action|
#| example2|          movie_2|          movie_5|          movie_8|thriller|
#| example3|          movie_3|          movie_6|          movie_9| romance|
#+---------+-----------------+-----------------+-----------------+--------+

from pyspark.sql.functions import *

df.selectExpr("moviename","explode(array(Source_1_movie_id,Source_2_movie_id,Source_3_movie_id))","genre").\
withColumnRenamed("col","id").\
orderBy("id").\
show()
#+---------+-------+--------+
#|moviename|     id|   genre|
#+---------+-------+--------+
#| example1|movie_1|  action|
#| example2|movie_2|thriller|
#| example3|movie_3| romance|
#| example1|movie_4|  action|
#| example2|movie_5|thriller|
#| example3|movie_6| romance|
#| example1|movie_7|  action|
#| example2|movie_8|thriller|
#| example3|movie_9| romance|
#+---------+-------+--------+


text:
Q: UIToolbar on top and interfaceOrientation out of sync in rotations using iPad..bug? Looking for confirmation or a correction on the following behaviour...
When problematically changing width of a fixed space uibarbuttonitem in UItoolbar via willAnimateRotationToInterfaceOrientation method, the display lags behind showing landscape when in portrait and vice versa after a few rotations. Like it goes one step out of sync.
As isolated test I:

*

*Created new view based project in iPad

*In IB designer added a uitoolbar to top of view

*and the following uibarbutton items to it:
left button|--Fixed space--|middle button<--flexible space-->right button

*Assign UIBarButtonItemFixedSpace as IBOutlet to "|--Fixed space--|" button

*Add following method to *.m
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation duration:(NSTimeInterval)duration {
    if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){
        UIBarButtonItemFixedSpace.width = 100;
    }else{
        UIBarButtonItemFixedSpace.width = 500;
    }
}

Even thought the if statement does fire correctly in respective orientation after a few 90 degree rotations, the display lags one 90 degree rotation behind. Seen in both simulator and iPad iOS 4.3 & Xcode 4
Am I missing something?

A: Although this does look like a bug, I have moved away from bar buttons and gone with popovers instead...in other words a re-think and re-design in the UI.


text:
Q: Why won't changes reflect in my Xamarin.Forms project or SQLite database UPDATE - Issue #1 is Solved, Issue#2 is still unsolved
You can view a very crude demonstration video of my issue at https://www.youtube.com/watch?v=5_6KJ0QJouM
I am building have a Xamarin.Forms app with an SQLite database using the MVVM design pattern and C#
When try to Save a record to the database from a View the update/save does not appear to be saving to the SQLite database or reflect in other Views.
I know the database Save method does work as I have created some dummy data when the application first loads (in App.xaml.cs) using the DeveloperData.cs file.
I have two issues.
(SOLVED) Issue 1 - Data not Saving to Database
when I call the Save command from the MerchandiserEditPage.xaml, which uses the  MerchandiserEditPageViewModel.cs ViewModel, the record does not appear to save.
Issue 2 - Changes Reflecting in other Views
Once the updated data is saved to the database, how can I reflect that change in other views?  After I Save a record from the MerchandiserEditPage that View is "Popped" off the stack and the user is returned to the MerchandiserProfileView.  I want the updated data to be reflected in all other views on the stack.  But this doesn't appear to be happening? (I tested this using hardcoded data and the same issue occurred, so problem is not directly related to issue 1)
There are many files in my project, that can be viewed/downloaded from my GitHub repository but I will concentrate on the following in this question.

*

*MerchandiserEditPage.xaml (View)

*MerchandiserProfilePage.xaml (View)

*MerchandiserDatabase.cs (Database Functions)x

*MerchandiserEditPageViewModel.cs x

View my GitHub repository for the full project.
MerchandiserDatabase.cs (Database Functions)
using SQLite;

namespace MobileApp.Database
{
    public class MerchandiserDatabase
    {
        private static SQLiteConnection database = DependencyService.Get<IDatabaseConnection>().DbConnection();
        private readonly static object collisionLock = new object();

        public MerchandiserDatabase()
        {
            database.CreateTable<Models.Merchandiser>();
        }

        public static void SaveMerchandiser(Models.Merchandiser merchandiser)
        {
            lock (collisionLock)
            {
                if (merchandiser.Id != 0)
                {
                    database.Update(merchandiser);
                }
                else
                {
                    database.Insert(merchandiser);
                }
            }
        }

    }
}

MerchandiserEditPageViewModel.cs (ViewModel) UPDATED
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace MobileApp.ViewModels
{
    public class MerchandiserEditPageViewModel : BaseViewModel
    {
        public string PageTitle { get; } = "Edit Merchandiser Profile";

        public Command SaveCommand { get; set; }

        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged();
            }
        }

        private string phone;
        public string Phone
        {
            get { return phone; }
            set
            {
                phone = value;
                OnPropertyChanged();
            }
        }

        private string email;
        public string Email
        {
            get { return email; }
            set
            {
                email = value;
                OnPropertyChanged();
            }
        }

        public MerchandiserEditPageViewModel(Models.Merchandiser selectedMerchandiser)
        {
            Name = selectedMerchandiser.Name;
            Phone = selectedMerchandiser.Phone;
            Email = selectedMerchandiser.Email;

            SaveCommand = new Command( async ()=> {

                selectedMerchandiser.Name = this.Name;
                selectedMerchandiser.Phone = this.Phone;
                selectedMerchandiser.Email = this.Email;

                Database.MerchandiserDatabase.SaveMerchandiser(selectedMerchandiser);
                await Application.Current.MainPage.Navigation.PopModalAsync();
            });
        }
    }
}

MerchandiserEditPage.xaml (View)
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MobileApp.Views.MerchandiserEditPage">
    <ContentPage.Content>
        <StackLayout>

            <!--Page Heading-->
            <StackLayout Spacing="0">
                <Label Text="{Binding PageTitle}"
                       Style="{StaticResource PageTitle}"/>
                <BoxView HeightRequest="1" Color="LightGray" />
            </StackLayout>

            <!-- Merchandiser Profile -->
            <StackLayout Margin="10">

                <Label Text="Name"/>
                <Entry Text="{Binding Name}"/>

                <Label Text="Phone"/>
                <Entry Text="{Binding Phone}"/>

                <Label Text="Email"/>
                <Entry Text="{Binding Email}"/>

                <StackLayout Orientation="Horizontal"
                             HorizontalOptions="Center">
                    <Button Text="Cancel"
                            Clicked="CancelButton_Clicked"/>
                    <Button Text="Save"
                            Command="{Binding SaveCommand}"/>
                </StackLayout>

            </StackLayout>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>

MerchandiserEditPage.xaml.cs (View - Code Behind)
public partial class MerchandiserEditPage : ContentPage
    {
        Models.Merchandiser SelectedMerchandiser { get; set; }

        public MerchandiserEditPage (Models.Merchandiser selectedMerchandiser)
        {
            InitializeComponent ();
            SelectedMerchandiser = selectedMerchandiser;
            this.BindingContext = new ViewModels.MerchandiserEditPageViewModel(selectedMerchandiser);
        }

        async private void CancelButton_Clicked(object sender, EventArgs e)
        {
            await Navigation.PopModalAsync();
        }

    }

MerchandiserProfilePage.xaml (View - XAML)
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MobileApp.Views.MerchandiserProfilePage"
             NavigationPage.HasNavigationBar="False">
    <ContentPage.Content>
        <StackLayout>

            <!--Page Heading-->
            <StackLayout Spacing="0">
                <Label Text="{Binding PageTitle}"
                       Style="{StaticResource PageTitle}"/>
                <BoxView HeightRequest="1" Color="LightGray" />
            </StackLayout>

            <!-- Merchandiser Profile -->
            <StackLayout Margin="10">

                <Label Text="Name"/>
                <Entry Text="{Binding Name}"
                       IsEnabled="False"/>

                <Label Text="Phone"/>
                <Entry Text="{Binding Phone}"
                   IsEnabled="False"/>

                <Label Text="Email"/>
                <Entry Text="{Binding Email}"
                   IsEnabled="False"/>

                <StackLayout Orientation="Horizontal"
                             HorizontalOptions="Center">
                    <Button Text="Back"
                            Clicked="BackButton_Clicked"/>
                    <Button Text="Edit"
                            Clicked="EditButton_Clicked"/>
                </StackLayout>

                <Button Text="Delete"
                        Command="{Binding DeleteCommand}"/>

            </StackLayout>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>

MerchandiserProfilePage.xaml.cs - (View - Code Behind)
    public partial class MerchandiserProfilePage : ContentPage
    {
        private Models.Merchandiser SelectedMerchandister { get; set; }

        public MerchandiserProfilePage (Models.Merchandiser selectedMerchandiser)
        {
            InitializeComponent ();
            SelectedMerchandister = selectedMerchandiser;
            this.BindingContext = new ViewModels.MerchandiserProfilePageViewModel(selectedMerchandiser);
        }

        async private void BackButton_Clicked(object sender, EventArgs e)
        {
            await Navigation.PopModalAsync();
        }

        async private void EditButton_Clicked(object sender, EventArgs e)
        {
            await Navigation.PushModalAsync(new Views.MerchandiserEditPage(SelectedMerchandister));
        }
    }

MerchandiserProfilePageViewModel.cs (ViewModel)
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace MobileApp.ViewModels
{
    public class MerchandiserProfilePageViewModel : BaseViewModel
    {
        public string PageTitle { get; } = "Merchandiser Profile";

        public Command DeleteCommand { get; }

        private string name;
        public string Name
        {
            get { return name;  }
            set
            {
                name = value;
                OnPropertyChanged();
            }
        }

        private string phone;
        public string Phone
        {
            get { return phone; }
            set
            {
                phone = value;
                OnPropertyChanged();
            }
        }

        private string email;
        public string Email
        {
            get { return email; }
            set
            {
                email = value;
                OnPropertyChanged();
            }
        }

        public MerchandiserProfilePageViewModel(Models.Merchandiser selectedMerchandiser)
        {
            Name = selectedMerchandiser.Name;
            Phone = selectedMerchandiser.Phone;
            Email = selectedMerchandiser.Email;
            DeleteCommand = new Command( async()=> {

                bool deleteConfirmed = await Application.Current.MainPage.DisplayAlert("Confirm Delete",$"Are you sure you want to delete {selectedMerchandiser.Name} as a Merchandiser?","Yes","No");

                if (deleteConfirmed)
                {
                    // TODO: Delete Merchandiser
                    await Application.Current.MainPage.Navigation.PopModalAsync();
                }
            });

        }
    }
}

A: you have a hardcoded set of data in your VM instead of loading it from the db
public MerchandisersPageViewModel()
{
    //Merchandisers = new ObservableCollection<Models.Merchandiser>(Database.MerchandiserDatabase.GetMerchandisers());
    Merchandisers = new ObservableCollection<Models.Merchandiser>()
    {
       new Models.Merchandiser { Id=1, Name="Barney Rubble", Phone="021 321 654", Email="barney@rubble.com"},
       new Models.Merchandiser { Id=2, Name="Frank Grimes", Phone="022 456 789", Email="grimey@homersfriend.com"},
       new Models.Merchandiser { Id=3, Name="Perry Platypus", Phone="023 789 456", Email="perry@agentp.com"},
    };
}

Update:
in MerchandiserProfilePageViewModel, get rid of the properties for Name, Phone and EMail
then in MerchandiserProfilePage.xaml change the bindings
<Entry Text="{Binding SelectedMerchandiser.Name}" IsEnabled="False"/>


text:
Q: CNOT quantum gate on python with numpy First of all i apologyse for any error i have, english is not my native lenguage.
Ok so i must implement quantum teleportation in python without using any quantum library, just with linear algebra, i already implement a way to get Hadamard and PauliX, im struggling to get the CNOT gate between q1 and q2 and the CNOT gate between q0 and q1, also i need a way to measure the final result as in the image, i already know the CNOT gate is a 8*8 matrix, and in another post i could see what that matrix is, but i dont know the steps to get that matrix, also as a plus, i need to implement cz gate too.

A: I don't know if you are using Qiskit or not. I have never used Numpy to draw a Qauntum Circuit. Qiskit is a framework to do quantum programming in python. I use Qiskit for creating this type of circuits. Here is an example:
from qiskit import *
from qiskit.circuit import Gate

n = 3
qr = QuantumRegister(n, 'q')
an = QuantumRegister(1, 'ancilla')
cr = ClassicalRegister(1, 'c')

circuit = QuantumCircuit(an, qr, cr)

circuit.h(qr[2])
circuit.cx(qr[2], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cz(qr[1], qr[2])
circuit.cy(qr[1], qr[2])
circuit.x(qr[1])
circuit.swap(qr[0], qr[1])
circuit.barrier(qr)
circuit.cu1("Pi", an[0], qr[1])
circuit.cu1("Pi/3", an[0], qr[0])
circuit.swap(qr[0], qr[1])
circuit.x(qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[2], qr[1])
circuit.measure(qr[0], cr[0])

circuit.draw(output='mpl')

This code will generate the following circuit:

Here, I tried to cover all the most important gates and functionalities in Qiskit. I hope you will find this useful. If it is useful don't forget to hit the upvote button. Happy Quantum Computing. :)


text:
Q: Ignoring Non-Lower Case Characters in C I am required to write a code which reads in a string, and places letters in the string that are less than 'm' into an array called first and the letters that are 'm' or greater are placed into an array called last. When it encounters a non-lower case letter it should simply skip it and move to the next one.
My code here works only when non-lower case letters are in the string but doesn't work when it involves numbers and symbols.
#include<stdio.h>

// main function
int main(void){
  // declare strings
  char letters[20], first[20], last[20];

  // read in a lower-case string
  printf("enter letters: ");
  scanf("%19s",letters);  //the number %19s limits the string to being
                          //19 characters long (plus the null character)

  // setup indexes to track current index of  arrays.
  int letters_index, first_index, last_index;
  letters_index=0;
  first_index=0;
  last_index=0;
char curr_letter ;

  // loop and split
while(letters[letters_index] != 0) { // not null
    switch (letters[letters_index]){
        case 97 ... 122:
    curr_letter = letters[letters_index];
    // less than 'm'?
    if(curr_letter < 'm'){
      // add to first
      first[first_index]=curr_letter;
      first_index++;
    } else {
      // otherwise, add to last
      last[last_index]=curr_letter;
      last_index++;
    }
    letters_index++;
            break;
    }
}

  // now add nulls
  first[first_index]='\0';
  last[last_index]='\0';

  // print arrays
  printf("first: %s\n",first);
  printf("last: %s\n",last);
}

If the input is hell2o, the output should be first: hell; last :o

A: Your code increments letters_index only if the input matches case 97 ... 122:. It is an endless loop if a non-matching character is found.
Move the incrementing letters_index++; out of the switch{} to the end of the while loop.
Unrelated to the error: Instead of the numbers 97 and 122 you should use the corresponding character constants 'a' and 'z' or maybe the library function islower().
Modified code:
#include <stdio.h>

// main function
int main(void){
    // declare strings
    char letters[20], first[20], last[20];

    // read in a lower-case string
    printf("enter letters: ");
    scanf("%19s",letters);  //the number %19s limits the string to being
    //19 characters long (plus the null character)

    // setup indexes to track current index of  arrays.
    int letters_index, first_index, last_index;
    letters_index=0;
    first_index=0;
    last_index=0;
    char curr_letter ;

    // loop and split
    while(letters[letters_index] != 0) { // not null
        switch (letters[letters_index]){
        case 'a' ... 'z':
        curr_letter = letters[letters_index];
        // less than 'm'?
        if(curr_letter < 'm'){
            // add to first
            first[first_index]=curr_letter;
            first_index++;
        } else {
            // otherwise, add to last
            last[last_index]=curr_letter;
            last_index++;
        }
        break;
        }
        letters_index++;
    }

    // now add nulls
    first[first_index]='\0';
    last[last_index]='\0';

    // print arrays
    printf("first: %s\n",first);
    printf("last: %s\n",last);
}

A: You only increase the counter when the character is between 'a'  and 'z', in consequence you are running into an infinite loop, move the counter outside the switch:
while(letters[letters_index] != 0) { // not null
    switch (letters[letters_index]){
        case 97 ... 122:
            curr_letter = letters[letters_index];
            // less than 'm'?
            if(curr_letter < 'm'){
              // add to first
              first[first_index]=curr_letter;
              first_index++;
            } else {
              // otherwise, add to last
              last[last_index]=curr_letter;
              last_index++;
            }
            // letters_index++; --> Not here
            break;
    }
    letters_index++; // --> Here
}

On the other hand, do not use magic numbers like 97 and 122, instead:
case 'a' ... 'z':


text:
Q: Map outgoing TCP connection to Docker container I have a collection of IPv4 traffic recorded by tcpdump, and I am interested in mapping a given outgoing connection to its origin Docker container on the same machine. I can view the TCP source port, but it is unclear to me how to ask Docker which container is using this port. How can this be done?
Thanks

A: You can filter containers which publish or expose a given port:
docker ps --filter=expose=3306

or use the format switch to get a list of container IDs with the used ports:
docker ps --format "{{.ID}}: {{.Ports}}"

A: I had this exact problem where I wanted to know which container was the client for a particular Postgresql database query. These are the steps I took to find the container that was the source of the TCP connection I was interested in.
In postgres query pg_stat_activity to determine the client_addr and client_port of the query you care about:
SELECT * FROM pg_stat_activity;

Now you know the source ip (client_addr) you can ssh to this box and determine the network interface used by docker:
ip addr

In my case it was docker0. Now we can use the source port of the database connection (client_port) to find the container ip address:
tcpdump -i docker0 src port 52282
 02:41:16.257106 IP 172.17.0.15.52282 > 192.168.2.119.postgres: Flags [P.] ...

Now we need to work out which container this source ip (172.17.0.15) belongs to, to do this we can use the docker inspect command with a filter:
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container

We run this command in a loop for each of the running containers and grep for the ip we are looking for:
for name in $( docker ps --format '{{.Names}}' ); do echo -n "$name => " && docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $name; done | grep 172.17.0.15
my-container => 172.17.0.15

Now we know that the container my-container is the source of the traffic we are interested in.


text:
Q: PHP Mail Formatting I'll start by saying that I'm not a PHP coder at all (I usually use Coldfusion), however I've been tasked to fix this for an old project.
The form that triggers this works fine, and the email does send, however the formatting is off.  This is the PHP we have right now (contact.php);
<?php

if ($_POST) {
$to_Email = "me@domain.com"; //Replace with recipient email address
$subject = 'Contact via Domain'; //Subject line for emails
//check if its an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

    //exit script outputting json data
    $output = json_encode(
            array(
                'type' => 'error',
                'text' => 'Request must come from Ajax'
    ));

    die($output);
}

//check $_POST vars are set, exit if any missing
if (!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userTelephone"]) ||!isset($_POST["userMessage"])) {
    $output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
    die($output);
}

//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
$user_Telephone = filter_var($_POST["userTelephone"], FILTER_SANITIZE_STRING);

//additional php validation
if (strlen($user_Name) < 4) { // If length is less than 4 it will throw an HTTP error.
    $output = json_encode(array('type' => 'error', 'text' => 'Name is too short or empty!'));
    die($output);
}
if (!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) { //email validation
    $output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
    die($output);
}
if (strlen($user_Message) < 5) { //check emtpy message
    $output = json_encode(array('type' => 'error', 'text' => 'Too short message! Please enter something.'));
    die($output);
}

//proceed with PHP email.
$headers = 'From: ' . $user_Email . '' . "\r\n" .
        'Reply-To: ' . $user_Email . '' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

$sentMail = @mail($to_Email, $subject, $user_Message . '  - ' . $user_Name. '  - ' . $user_Telephone, $headers);

if (!$sentMail) {
    $output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
    die($output);
} else {
    $output = json_encode(array('type' => 'message', 'text' => 'Hi ' .     $user_Name . ' Thank you for your email'));
    die($output);
}
}
?>

The mail that is sent comes through like this;
tst 4 - Test - 123456
What I need to do is change it so it looks like this;
Name: tst 4
Email: sender@domain.com
Phone: 123456

Message: Test

The email address line isn't critical as the mails already come through with that in the 'from'.
The way this PHP file is setup and mail is sent doesn't match up with any samples I can find online, hence me being stuck!

A: PHP mail() function:
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

The last parameter, the headers, are optional for the function but required for sending HTML email, as this is where we are able to pass along the Content-Type declaration telling email clients to parse the email as HTML.

Content-Type: text/html; charset=UTF-8

In fact, the headers area gives us the opportunity to do lots of important email functions. This is where we can set the From: and Reply To: settings if need be, as well as CC and BCC other recipients
<?php

if ($_POST) {
    $to_Email = "me@domain.com"; //Replace with recipient email address
    $subject = 'Contact via Domain'; //Subject line for emails
//check if its an ajax request, exit if not
    if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

        //exit script outputting json data
        $output = json_encode(
            array(
                'type' => 'error',
                'text' => 'Request must come from Ajax'
            ));

        die($output);
    }

//check $_POST vars are set, exit if any missing
    if (!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userTelephone"]) ||!isset($_POST["userMessage"])) {
        $output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
        die($output);
    }

//Sanitize input data using PHP filter_var().
    $user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
    $user_Telephone = filter_var($_POST["userTelephone"], FILTER_SANITIZE_STRING);

//additional php validation
    if (strlen($user_Name) < 4) { // If length is less than 4 it will throw an HTTP error.
        $output = json_encode(array('type' => 'error', 'text' => 'Name is too short or empty!'));
        die($output);
    }
    if (!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) { //email validation
        $output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
        die($output);
    }
    if (strlen($user_Message) < 5) { //check emtpy message
        $output = json_encode(array('type' => 'error', 'text' => 'Too short message! Please enter something.'));
        die($output);
    }

//proceed with PHP email.
    $headers = 'From: ' . $user_Email . '' . "\r\n" .
        'Reply-To: ' . $user_Email . '' . "\r\n" .
        'X-Mailer: PHP/' . phpversion() . "\r\n" .
        'Content-Type: text/html; charset=UTF-8\r\n';
    $msg    =   <<<MSG
Name: {$user_name}

Email: {$user_Email}

Phone: {$user_Telephone}

Message: {$user_Message}

MSG;

    $sentMail = @mail($to_Email, $subject, $msg, $headers);

    if (!$sentMail) {
        $output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
        die($output);
    } else {
        $output = json_encode(array('type' => 'message', 'text' => 'Hi ' .     $user_Name . ' Thank you for your email'));
        die($output);
    }
}
?>

A: The problem is the third parameter you are passing to the mail() function which is the content for your email. Currently, you are just providing a hyphen seperated list so you need to create a new variable that looks something like the below:
$email_content = "
Name: $user_Name
Email: $user_Email
Phone: $user_Telephone

Message: $user_Message";

Then update your mail() call to this:
$sentMail = @mail($to_Email, $subject, $email_content, $headers);


text:
Q: Complex number containing vectors in R I am trying to make a Mandelbrot set code in R from scratch without using any predefined functions. But I am getting an error message saying-

In complex(real = rl, imaginary = hig) :
imaginary parts discarded in coercion

I think that means complex numbers can't be stored in vectors.
Please tell me whether I am right or wrong and also please help me to solve this error.
Below is my code.
listx=c()
z=0
inmbs=F
imgdispl=matrix(c(),441 ,441 )
for (hig in seq(-220,220,1)){
  for (wid in seq(-220,220,1)){
    listx=c()
    z=0
    for (k in 0:5){
      inmbs=F
      xx=z^2
      rl=xx+wid
      l = complex(real = rl, imaginary = hig)
      if (l %in% listx){
        inmbs=T
        break
      }
      else{
        append(listx,l)
        z=l
      }
    }
    if (inmbs==T){
      imgdispl[hig+221,wid+221]=1
    }
    else{
      imgdispl[hig+221,wid+221]=0
    }
  }
}
image(imgdispl)

updated code:
listx=c()
z=0
inmbs=F
imgdispl=matrix(c(0),441 ,441 )
for (hig in seq(-220,220,1)){
  for (wid in seq(-220,220,1)){
    listx=c()
    z=0
    for (k in 0:5){
      inmbs=F
      xx=z^2
      coor = complex(real = wid/15, imaginary = hig/15)
      l=xx+coor
      if (l %in% listx){
        inmbs=T
        break
      }
      else{
        append(listx,l)
        z=l
      }
    }
    if (inmbs==T){
      imgdispl[hig+221,wid+221]=1
    }
    else{
      imgdispl[hig+221,wid+221]=0
    }
  }
}
image(imgdispl)

A: If you debug your code you'll see that rl becomes complex.
The message tells you that only the real part is used in the call to:
l = complex(real = rl, imaginary = hig)

If you follow these instructions, you get:
z=0
N=10
inmbs=F
imgdispl=matrix(c(0),441 ,441 )
for (hig in seq(-220,220,1)){
  for (wid in seq(-220,220,1)){
    coor = complex(real = wid/220, imaginary = hig/220)
    z=0

    for (k in 0:N){
      inmbs=F
      if ((Re(z)^2+Im(z)^2)>4){
        inmbs=T
        break
      }
    z = z^2 + coor
    }
    if (inmbs==T){
      imgdispl[hig+221,wid+221]=1
    }
    else{
      imgdispl[hig+221,wid+221]=0
    }
  }
}
image(imgdispl)


text:
Q: Any Graphical interface for installing packages like php , mysql for UBUNTU In Cpanel/whm there is option to install various linux packages like php , mysql postgre sql etc.
Is there any option available in Ubuntu where i can tick the packages and those gets installed rather than writing on command line.

A: Synaptic Package Manager is what you're looking for.  Should be under System -> Administration.

A: Aptitude runs in a menuing system on a character terminal, but I agree that you should become accustomed to the CLI. Ubuntu uses apt-get and its relatives.

A: There is also a utility that can be invoked from the command like called tasksel.  This will help you configure your server's role.  It sounds like the "LAMP Server" configuration might be what you're aiming toward.
From the Ubuntu Wiki:

Tasksel groups software packages by tasks and offers an easy way to install all the packages needed for that task. It provides the same functionality as using conventional meta-packages.

Run it with the following command:
sudo tasksel


text:
Q: Is there any power of $4$ with natural exponent that can be represented as sum of several different powers of $5$ with whole non-negative exponent? There is a power of $2$ with a natural exponent, which can be represented as several different powers of $3$ with whole non-negative exponent. For example, $2^{2}=3^{1}+3^{0}$ or $2^{8}=3^{5}+3^{2}+3^{1}+3^{0}$.
There is also a power of $3$ with a natural exponent, which can be represented as several different powers of $4$ with whole non-negative exponent. For example, $3^{4}=4^{3}+4^{2}+4^{0}$.
However, is there any power of $4$ with natural exponent that can be represented as sum of several different powers of $5$ with whole non-negative exponent?


text:
Q: From a varchar column extract the last numerical digit seperated by '-' I have a dataframe which looks like this.
COURSE_ID
EX-AAB-5S-102345
EX-A45-5F-143567
INC-AAB-WW-104514
INC-AAB-DE-567431

What i am trying is to create a new column COURSE where i will only have the 6digit numerical filed
COURSE_ID.            COURSE
EX-AAB-5S-102345.     102345
EX-A45-5F-143567.     143567
INC-AAB-WW-104514.    104514
INC-AAB-DE-567431.    567431

A: Using str.extract:
df["COURSE"] = df["COURSE_ID"].str.extract(r'(\d+)$')


text:
Q: linq lambda convert object with list of objects of the same type to another object I currently have a List<OriginalItem> that i need to convert to a List<NewItem>.
Here are the classes
public class OriginalItem
{
   public int ItemIndex {get;set;}

   public string Name {get;set;}

   private OriginalItem[] itemsList;

   public OriginalItem[] ItemsList
   {
        get
        {
            return itemsList;
        }
        set
        {
            itemsList= value;
        }
   }

}

public class NewItem
{
  public int NewItemIndex {get;set;}
  public string NewName {get;set;}

  private NewItem[] itemsList;

  public NewItem[] ItemsList
  {
      get
      {
          return itemsList;
      }
      set
      {
         itemsList= value;
      }
   }
}

I know using a select statement i can create a new object from a list i.e.
List<NewItem> newItems = originalItems.Select(x=> new NewItem(){
                                                            NewItemIndex = x.ItemIndex,
                                                            NewItemName = x.Name
                                                           }).ToList();

but how do i create the list within the list? It doesnt have to use recursion, if there is another way to do it.

A: Thanks,
from the above i managed to get what i need with minor changes:
public class OriginalItem
{
.
.
.
   //add new method to convert the originalItem to newItem
   public NewItem createNewItem()
   {
      NewItem item = new NewItem();
      item.NewName = this.Name;
      item.NewItemIndex = this.ItemIndex;
      item.ItemsList = this.ItemsList.Select(x =>x.createNewItem()).ToList();
   }
}

and then in the main class where i had the List<OriginalItem> originalItems I did the following:
List<NewItem> newItems = originalItems.Select(x=>x.createNewItem()).ToList();

A: You can't get by without a recursion with recursive properties. This operation is essentially recursive.
One possible implementation:
NewItem ToNew(OriginalItem item)
{
    return new NewItem() { NewItemIndex = item.ItemIndex, NewName = item.Name, ItemsList = item.ItemsList == null ? null : item.ItemsList.Select(ToNew).ToArray()};
}

And here is how to use it:
var newItems = originalItems.Select(ToNew).ToList();

It also could be implemented as a copy constructor, but no reason to cople the two classes.
Also it's more convenient to use as a method group (just ToNew, not i => ToNew(i)).

A: Here's how I would do it:
Func<OriginalItem, NewItem> convert = null;
convert = oi =>
    new NewItem()
    {
        NewName = oi.Name,
        NewItemIndex = oi.ItemIndex,
        ItemsList = oi.ItemsList == null
            ? null
            : oi.ItemsList.Select(x => convert(x)).ToArray(),
    };

var newItems = originalItems.Select(oi => convert(oi)).ToList();

So, given this input:
var originalItems = new List<OriginalItem>()
{
    new OriginalItem()
    {
        Name = "0", ItemIndex = 0,
        ItemsList = new []
        {
            new OriginalItem()
            {
                Name = "1", ItemIndex = 1, ItemsList = null,
            },
            new OriginalItem()
            {
                Name = "2", ItemIndex = 2, ItemsList = null,
            },
        },
    },
    new OriginalItem()
    {
        Name = "3", ItemIndex = 3, ItemsList = null,
    },
};

I get this output:


text:
Q: Loading Text file to HTML textarea from mobile phone storage I am writing an app for mobile phones using HTML5, Javascript and CSS. One part of the app should allow the user to load a text file present the phone's local storage on to a text area provided on that page. My questions are:

*

*How do I create a file dialog box to ask user to select the txt file. (Is it possible?)

*I read something about PHP etc to load files but I have no experience in it. Is there like a code snippet that I could use to load text file? Can Javascript, jquery mobile has something to do this?

*Once I load it into the textarea, I want to edit it and save it again.

It would be helpful if someone can throw some light on this or direct me towards some resource where I can learn about it.

A: Local I/O is never allowed directly, for what should be fairly obvious security reasons. You need to set up an <input type="file"> form to do this, but I'm not sure how those behave on a mobile platform. I'm sure that that would very between platforms. Assuming a successful file upload and transmission to your editing area, saving back to storage would require a file download you would have to initiate, and which the user could choose to accept or ignore.
You use the words "local storage" and your tags include HTML 5, so there are additional options. You can look in to the LocalStorage API, which allows you to store larger amounts of data which you can then retrieve, allow editing on, and save. This is controlled by the browser to eliminate security issues. There is also the File API, which allows reading files. I believe this is read-only, however, (again for security) and may not be what you are looking for.


text:
Q: Timeout does not work in AngularJS Karma - Jasmine test My code:
describe('Popup', function(){

it("Should close on second click", function(){
        compileDirective(400,'click','true');
            element.triggerHandler('click');
            timeout(function() {
                 element.triggerHandler('click');
                 scope.$digest();
                 timeout.flush();
                 element.remove();
                 $(".sidepopright").remove();
             }, 1000);

        });

});

I want to make a delay for the second click of the popup, so I put a timeout after the first click. However, it does not work. Anyone have idea?

A: You should use the injectable service $timeout, not timeout.
$timeout(function () {
// Do something
}, 1000);

A: You have to use $timeout.flush(); to simulate the timeout completion in your unit test.


text:
Q: Functions not working as expected I am doing a Javascript project for a class and cannot seem to get two of the functions to work.  They are swapFE and swapEF.  Essentially what I am trying to do is that when the user clicks down on the mouse button the French phrase swaps to English.  When the mouse button is released it is supposed to swap back to French.  Below is what I have for the entire project, including HTML code.  If anyone could point out what I am doing wrong, I would appreciate it.
    <?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

   <title>French Phrases Week 5</title>
   <link href="styles.css" rel="stylesheet" type="text/css" />

            Prof. Eve Granger

            Office: 810 Linton Hall

            Hours: TR: 3:00-4:30

            French 101

            MWF: 9:00-9:50

            Rm. 402 Linton Hall

Home

Phrases

Week 1 Phrases

Week 2 Phrases

Week 3 Phrases

Week 4 Phrases

Week 5 Phrases

Quizzes

Chapter 1 Quiz

Chapter 2 Quiz

Chapter 3 Quiz

Dept. of French

French 101

French 135

French 155

French 201

French 301

Staff

Denise Abbot

Viola Devreaux

Eve Granger

Cynthia Trudeau

Gary Vironque

Week 5 Phrases

Press down your mouse button on each phrase to translate

      <address>
         French-English Translation Page
      </address>

This is the JavaScript code that has the Arrays for both English and French...
  /*
   New Perspectives on JavaScript, 2nd Edition
   Tutorial 7
   Case Problem 1

   Filename: french5.js

   Variable List:
   french
      Contains an array of 10 english phrases

   english
      Contains an array of 10 French translations
    */

    var english=new Array();
    english[0]="This hotel isn't far from the Eiffel Tower.";
    english[1]="What time does the train arrive?";
    english[2]="We have been waiting for the bus for one half-hour.";
    english[3]="This meal is delicious";
    english[4]="What day is she going to arrive?";
    english[5]="We have eleven minutes before the train leaves!";
    english[6]="Living in a foreign country is a good experience.";
    english[7]="Excuse me! I'm late!";
    english[8]="Is this taxi free?";
    english[9]="Be careful when you go down the steps.";

    var french=new Array();
    french[0]="Cet hôtel n'est pas loin de la Tour Eiffel.";
    french[1]="A quelle heure arrive le train?";
    french[2]="Nous attendons l'autobus depuis une demi-heure.";
    french[3]="Ce repas est délicieux";
    french[4]="Quel jour va-t-elle arriver?";
    french[5]="Nous avons onze minutes avant le départ du train!";
    french[6]="Habiter dans un pays étranger est une bonne expérience.";
    french[7]="Excusez-moi! Je suis en retard!";
    french[8]="Est-ce que ce taxi est libre?";
    french[9]="Faites attention quand vous descendez l'escalier.";

And this is the code that I am currently working on...
/*
   New Perspectives on JavaScript, 2nd Edition
   Tutorial 7
   Case Problem 1

   Author: Chris Carter
   Date:   10/21/2013

   Filename: engfr.js

   Function List:

   addEvent(object, evName, fnName, cap)
      Adds an event hander to object where evName is the name of the event,
      fnName is the function assigned to the event, and cap indicates whether
      event handler occurs during the capture phase (true) or bubbling
      phase (false)

   setUp()
      Insert the current week's french phrases into document and set up
      event handlers for the phrases.

   swapFE(phrase, pnum)
      Changes a French phrase to the English version of that phrase.

   swapEF(phrase, pnum)
      Changes an English phrase ot the Frech version of that phrase.

*/

function addEvent(object, evName, fnName, cap) {
   if (object.attachEvent)
       object.attachEvent("on" + evName, fnName);
   else if (object.addEventListener)
       object.addEventListener(evName, fnName, cap);
}

addEvent (window, "load", setUp, false);

function setUp() {
    var transDoc = document.getElementById("doc");
    var olElem = document.createElement("ol");
    for (var i = 0; i < french.length; i++) {
        var newLI = document.createElement("li");
        newLI.innerHTML = french[i];
        newLI.id = i + "phrase";
        newLI.style.cursor = "pointer";
        addEvent(newLI, "onmousedown", swapFE, false);
        addEvent(newLI, "onmouseup", swapEF, false);
        olElem.appendChild(newLI);
    }
    transDoc.appendChild(olElem);
}

function swapFE(phrase, pNum) {
    var phrase = e.target || event.srcElement;
    var pNum = 0;
    if (phrase.nodeType == "#text") {
        phrase = phrase.parent.Node
    }
        pNum = parseInt(phrase.id);
        phrase.innerHTML = english[pNum];
        phrase.style.fontStyle = "italic";
        phrase.style.color = "rgb(155, 102, 102)";
    }
}

function swapEF(phrase, pNum) {
    var phrase = e.target || event.srcElement;
    var = 0;
    if (phrase.nodeType == "#text") {
        phrase = phrase.parentNode
    }
        pNum = parseInt(phrase.id);
        phrase.innerHTML = french[pNum];
        phrase.style.fontStyle = "normal";
        phrase.style.color = "black";
    }
}

A: function addEvent already adds the "on" to "onMouseDown" and "onMouseUp" removing the on would fix your problem and allow you to continue debugging.


text:
Q: How can I streamline Email body using utl_smtp.write_data I am trying to send output of an query through mail. I am using following command.
FOR i IN emp_cur LOOP
   e_fullname := i.full_name;
   UTL_SMTP.WRITE_DATA(v_connection_handle,
                        e_fullname || ' - ' || i.ID ||' - ' || i.location_city ||' - ' || i.job ||' - ' || i.supervisor_name || UTL_TCP.CRLF|| UTL_TCP.CRLF);

  END LOOP;

Output looks like this:
Pandyan - 12312 - Williamsburg - Developer - Pieterson

Bowaris - 98615 - Ohio - Spec - Pieterson

Perry, Steven W (Steve) - 11111 - Ohio - Analyst - Pieterson

Praveerarajan - 44444 - Williamsburg - Engineer - Pieterson

Now, how can I make my output look good(streamlined). So that all emp names have right spacing and IDs are displayed one below the other in a straight line, and the same for the other columns.
Thanks
venkat

A: Use the RPAD and LPAD functions to make the columns take up the same amount of space, regardless of the length of the content.  Use RPAD to align strings on the left-hand side, and LPAD to align numbers on the right.
Eg.
rpad(e_fullname, 15) || ' - ' || lpad( i.ID, 10) ||' - ' || rpad(i.location_city, 30) ||' - ' || rpad(i.job,10) ||' - ' || rpad(i.supervisor_name,15) || UTL_TCP.CRLF|| UTL_TCP.CRLF);

The default padding character is space, which is probably what you want in this case.
Of course, this is only going to make things line up nicely in a fixed size font (like Courier New).  If your email is going to use some easy reading font like Arial you've got problems.


text:
Q: Wordpress script with integrity and crossorigin I'm trying to use the wp_register_script and wp_enqueue_script FUNCTION on WordPress to enqueue a script, which has two attributes: "integrity" and "crossorigin".
Normally I use PHP and my code looks like:
wp_register_script('jquery', 'http' . ($_SERVER['SERVER_PORT'] == 443 ? 's' : '') . '://code.jquery.com/jquery-3.1.1.slim.min.js', false, null);
wp_enqueue_script('jquery');

With any other script. The wp_register_script takes five parameters (in this case four) $handle, $src, $deps, $ver ($media). I'm wondering where I can add the two attributes. I've already tried:
wp_register_script('jquery', 'http' . ($_SERVER['SERVER_PORT'] == 443 ? 's' : '') . '://code.jquery.com/jquery-3.1.1.slim.min.js'.'integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n"', false, null);
    wp_enqueue_script('jquery');

But it didn't work.
Anyone who had the same problem?
This is the original script from bootstrap 4, which also has bootstrap and tether with the same attributes (integrity and crossorigin) so, since it is pretty new, any kind of help will be very appreciated.

A: I just cracked this by accident. I've had to use conditionals on some CSS files for ancient Internet Explorer versions and figured I may as well try putting an array in the same wp_script_add_data function that I used. It works!
    wp_register_script('jquery3', 'https://code.jquery.com/jquery-3.3.1.min.js', array(), '3.3.1', true); // jQuery v3
    wp_enqueue_script('jquery3');
    wp_script_add_data( 'jquery3', array( 'integrity', 'crossorigin' ) , array( 'sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=', 'anonymous' ) );

Reference: https://developer.wordpress.org/reference/functions/wp_script_add_data/#parameters
For completeness: If adding jQuery v3, you also need Migrate v3: http://jquery.com/download/

A: This is the correct syntax:
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>

"integrity" and "crossorgin" are not part of the URL. They are part of the script tag.
Unfortunately Wordpress can not handle attributes on enqueued scripts at the moment.
But they working on it... Status: needs-testing  :-)
 => Ticket 22249 / Wordpress Core

A: You can use the script_loader_tag hook (the main part is actually not my code, but I honestly don't remember where I got it, probably somewhere here on SO or WP Stack Exchange):
add_filter( 'script_loader_tag', 'add_attribs_to_scripts', 10, 3 );
function add_attribs_to_scripts( $tag, $handle, $src ) {

// The handles of the enqueued scripts we want to defer
$async_scripts = array(
    'jquery-migrate',
    'sharethis',
);

$defer_scripts = array(
    'contact-form-7',
    'jquery-form',
    'wpdm-bootstrap',
    'frontjs',
    'jquery-choosen',
    'fancybox',
    'jquery-colorbox',
    'search'
);

$jquery = array(
    'jquery'
);

if ( in_array( $handle, $defer_scripts ) ) {
    return '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n";
}
if ( in_array( $handle, $async_scripts ) ) {
    return '<script src="' . $src . '" async="async" type="text/javascript"></script>' . "\n";
}
if ( in_array( $handle, $jquery ) ) {
    return '<script src="' . $src . '" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous" type="text/javascript"></script>' . "\n";
}
return $tag;
}

A: Thanks for all the postings, they really helped. I did roll my own version to give it some structure and make it easier to read and update. Use enqueue as normal, use script for CSS files with a false tag at the end so that it loads at the top. Though it can probably be simplified somewhat.
add_filter('script_loader_tag', 'add_attributes_to_script', 10, 3);

function add_attributes_to_script( $tag, $handle, $src ) {

        $scripts_to_load = array (

            (0) => Array
              (
                ('name') => 'popper_min_js',
                ('type') => '<script type="text/javascript" src="',
                ('integrity') => 'sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49',
                ('close') => '></script>'
              ),

             (1) => Array
               (
                ('name') => 'bootstrap_min_js',
                ('type') => '<script type="text/javascript" src="',
                ('integrity') => 'sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T',
                ('close') => '></script>'
               )
        );

        $key = array_search($handle, array_column($scripts_to_load, 'name'));

        if ( FALSE !== $key){

            $tag = $scripts_to_load[$key]['type'] . esc_url($src) . '" integrity="' . $scripts_to_load[$key]['integrity'] .'" crossorigin="anonymous"' . $scripts_to_load[$key]['close'] . "\n";

        }
        return $tag;
    }

A: This is well explained here:

*

*https://snippets.webaware.com.au/howto/subresource-integrity-wordpress-scripts-stylesheets/

*https://developer.wordpress.org/reference/functions/wp_enqueue_script/#comment-4246
For each enqueued script you need to add a filter which adds proper attributes;
/**
* load custom JS
*/
add_action('wp_enqueue_scripts', function() {
    wp_enqueue_style('jquery', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js', [], null);

    add_filter('style_loader_tag', __NAMESPACE__ . '\\add_jquery_sri', 10, 2);
});

/**
* add SRI attributes to jQuery style loader element

* @param string $html
* @param string $handle
* @return string
*/
function add_jquery_sri($html, $handle) {
    if ($handle === 'jQuery') {
        $html = str_replace(' />', ' integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous" />', $html);
    }

    return $html;
}

URL & hash taken from https://cdnjs.com/libraries/jquery
All praise to the authors!

A: I've created a function that works just like I imagined wp_script_add_data would work if it was used to add attributes. ( it's not, read below)
Hope you find it useful! ☺
function add_script_attributes($handle, $keys, $values) {
  $GLOBALS['targeted_script_handle'] = $handle;
  $GLOBALS['targeted_script_keys'] = $keys;
  $GLOBALS['targeted_script_values'] = $values;

  add_filter( 'script_loader_tag', function ( $tag, $handle, $src ) {
    if ($GLOBALS['targeted_script_handle'] !== $handle) {
      return $tag;
    }

    $attrs = array();

    if (is_array($GLOBALS['targeted_script_keys'])) {
      foreach ($GLOBALS['targeted_script_keys'] as $key => $value) {
        $target_value = '';

        if (!empty($GLOBALS['targeted_script_values'])) {
          if (is_array($GLOBALS['targeted_script_values'])) {
            $target_value = array_key_exists($key, $GLOBALS['targeted_script_values']) ? $GLOBALS['targeted_script_values'][$key] : '';
          } else {
            if ($key === 0) {
              $target_value = $GLOBALS['targeted_script_values'];
            }
          }
        }

        array_push($attrs, sprintf('%s="%s"', $value, esc_attr($target_value)));
      }
    } else {
      $target_value = '';

      if (!empty($GLOBALS['targeted_script_values'])) {
        if (is_array($GLOBALS['targeted_script_values'])) {
          $target_value = $GLOBALS['targeted_script_values'][0];
        } else {
          $target_value = $GLOBALS['targeted_script_values'];
        }
      }

      array_push($attrs, sprintf('%s="%s"', $GLOBALS['targeted_script_keys'], esc_attr($target_value)));
    }
    $GLOBALS['targeted_script_handle'] = null;
    $GLOBALS['targeted_script_keys'] = null;
    $GLOBALS['targeted_script_values'] = null;

    if (empty($attrs)) {
      return $tag;
    }

    return preg_replace('/^<script/i', '<script '. implode(' ', $attrs), $tag);
  }, 10, 3);
}

NOTE: This function doesn't know which attributes <script> element already has, and it doesn't remember which attributes you added. Can be refactored as a singleton class which memorizes the handles with added attributes, though.
Usage Example 1
wp_enqueue_script('jquery');
add_script_attributes('jquery', 'crossorigin', 'anonymous');
add_script_attributes('jquery', 'integrity', 'sha256-
 QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=');

This renders as
<script integrity="sha256-
 QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous" src="path_to_jquery.js" id="jquery-js"></script>

Usage Example 2
wp_enqueue_script('jquery');
add_script_attributes('jquery', array('crossorigin', 'integrity'), array('anonymous', 'sha256-
 QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc='));

This also renders as
<script integrity="sha256-
 QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous" src="path_to_jquery.js" id="jquery-js"></script>

Usage Example 3
wp_enqueue_script('jquery');
add_script_attributes('jquery', array('crossorigin', 'integrity', 'foo', 'baz'), array('anonymous', 'sha256-
 QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=', 'bar'));

This will render as
<script integrity="sha256-
 QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous" foo="bar" baz="" src="path_to_jquery.js" id="jquery-js"></script>

TL;DR;
wp_script_add_data() function is NOT a way to go (doc). It is only accepts conditional as a key, and is used to add HTML browser conditional comments so your script will run on specific browsers. This was useful at the time when IE was around, thank the divine Lord it's not anymore.
wp_print_script_tag() function MIGHT be a way to go (doc), if you don't want to use the queue and you bind it to wp_head and wp_footer actions. It is used to print out a <script> element with provided attributes.
script_loader_tag filter IS the way to go (doc). In WP 6.0.2 on line 406 in wp-includes/class.wp-scripts.php (permalink) this filter is triggered and is used to filter individual script tags before they are "echo"ed to your templates. If I read comments here carefully I wouldn't have to dig through the source... ♂ But, TMYK!
P.S. I wonder why they didn't refactor wp-includes/class.wp-scripts.php to use wp_print_script_tag , probably cause they have this filter script_loader_src, but still it could be made to work.
Bonus
The almost identical function can be used for styles with style_loader_tag (doc, permalink)! It can be made as one function but I'm too lazy... (just like guys that contribute to WP).
function add_style_attributes($handle, $keys, $values) {
  $GLOBALS['targeted_script_handle'] = $handle;
  $GLOBALS['targeted_script_keys'] = $keys;
  $GLOBALS['targeted_script_values'] = $values;

  add_filter( 'style_loader_tag', function ( $tag, $handle, $href, $media ) {
    if ($GLOBALS['targeted_script_handle'] !== $handle) {
      return $tag;
    }

    $attrs = array();

    if (is_array($GLOBALS['targeted_script_keys'])) {
      foreach ($GLOBALS['targeted_script_keys'] as $key => $value) {
        $target_value = '';

        if (!empty($GLOBALS['targeted_script_values'])) {
          if (is_array($GLOBALS['targeted_script_values'])) {
            $target_value = array_key_exists($key, $GLOBALS['targeted_script_values']) ? $GLOBALS['targeted_script_values'][$key] : '';
          } else {
            if ($key === 0) {
              $target_value = $GLOBALS['targeted_script_values'];
            }
          }
        }

        array_push($attrs, sprintf('%s="%s"', $value, esc_attr($target_value)));
      }
    } else {
      $target_value = '';

      if (!empty($GLOBALS['targeted_script_values'])) {
        if (is_array($GLOBALS['targeted_script_values'])) {
          $target_value = $GLOBALS['targeted_script_values'][0];
        } else {
          $target_value = $GLOBALS['targeted_script_values'];
        }
      }

      array_push($attrs, sprintf('%s="%s"', $GLOBALS['targeted_script_keys'], esc_attr($target_value)));
    }
    $GLOBALS['targeted_script_handle'] = null;
    $GLOBALS['targeted_script_keys'] = null;
    $GLOBALS['targeted_script_values'] = null;

    if (empty($attrs)) {
      return $tag;
    }

    return preg_replace('/^<link/i', '<link '. implode(' ', $attrs), $tag);
  }, 10, 4);
}

A: You can add a CDN with integrity with Crossorigin by using add_action :
function add_jquery(){
echo '<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-
 QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>';
 }

 add_action( 'wp_head', 'add_jquery' );


text:
Q: how can i bring to uniform format tel. number how can i bring to uniform format tel. number?
using only regex
it can be +79998887766 or 8 999 8887766 or 8-999-888-77-66 etc.
but i need only +7 999 888-77-66
public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("Input your phone number: ");
        Scanner in = new Scanner(System.in);
        String number = in.nextLine();

what's next?

A: Given your three different formats of mobile numbers, you can reformat it to the common one you mentioned +7 999 888-77-66 by first capturing the numbers into five groups of numbers using following regex,
^\D*(\d)\D*(\d{3})\D*(\d{3})\D*(\d{2})\D*(\d{2})\D*$

And then replace it with,
+$1 $2 $3-$4-$5

To restore the number in desired format.
Check this demo
Java code demo,
List<String> numbers = Arrays.asList("+79998887766", "8 999 8887766", "8-999-888-77-66");
    numbers.forEach(x -> {
        System.out.println(x + " --> " + x.replaceAll("^\\D*(\\d)\\D*(\\d{3})\\D*(\\d{3})\\D*(\\d{2})\\D*(\\d{2})\\D*$", "+$1 $2 $3-$4-$5"));
    });

Output,
+79998887766 --> +7 999 888-77-66
8 999 8887766 --> +8 999 888-77-66
8-999-888-77-66 --> +8 999 888-77-66


text:
Q: Rights needed to see database files in Properties dialog? I have a contractor setting up a database application. The database is set up, the login for the app is set as the database owner, but has only 'public' at the server level.
When the contractor logs into SSMS with the database login, he sees no information in the Database Properties > Files page -- the table is empty. However, exec sp_helpdb database; returns all the info that should be showing in Properties.
Are there any rights I can grant that will show the file info in Properties, without granting excessive rights to anything else?
(SQL Server 2008 R2)

A: If I'm understanding correctly I believe you need to grant VIEW DEFINITION to your contractor's account. You can do this only on the DBs you want the contractor to access.


text:
Q: Minimizing the potential energy in a hyperelasticity problem I am currently using the FEniCS/DOLFINx package to simulate deformations on a mesh volume.
Following this tutorial, I am using the following equation to find $u$ such as $L(u)=0$:
$$L = \vec{\nabla} \vec{v} \cdot P ~\vec{dx} - \vec{T} \cdot \vec{v} ~\vec{ds}$$ (I may have forgotten integrals here)
with

*

*$P$ the first Piola Kirchhoff stress $P = \dfrac{\partial \psi}{\partial F}$ with $F$ the deformation gradient.

*$\vec{dx}$ and $\vec{ds}$ the volume and surface element

*$\vec{T}$ a traction force applied on the surface.

Originally, the goal would be to minimize the potential energy, which writes itself as:
$$\Pi = \int_{\Omega} \psi (u) \,dx - \int_{\partial \Omega} T\cdot u \,ds$$
with $\psi$ the energy density function.
My question is: what is the link between these two equations ? How to get to the first one starting from the second one ? I know that the Gateaux derivative is used in that case but I don't know how to apply it to $\Pi$.

A: I got an answer on the FEniCS forum from @kamensky, so I will paste the answer given here to close the subject:
If you've studied calculus of variations before, it may help to use the
notation $\partial u$ for the test function instead of $v$, then think
about the Gateaux derivative of $\Pi$ with respect to $u$ in the direction
$\delta u$ to zero (by analogy to seeking the minimum of a univariate
function by looking for an argument such that its ordinary derivative is
zero):
$$d\Pi(\boldsymbol{u} ; \delta\boldsymbol{u}) = \delta \Pi = \int_\Omega
 \frac{\partial \psi}{\partial F} : \delta \boldsymbol F d \Omega -
 \int_{\partial\Omega} T \cdot \delta \boldsymbol u d \partial\Omega = 0,$$
where the variation $\delta \boldsymbol F$ is also a Gateaux derivative
with respect to the displacement of $\boldsymbol F = \nabla \boldsymbol u +
 \boldsymbol I$, i.e.
$$\delta \boldsymbol F = d\boldsymbol{F}(\boldsymbol u\,;
 \delta\boldsymbol{u}) = \nabla (\delta \boldsymbol u).$$
Making the substitutions
$$\partial \psi / \partial \boldsymbol F \rightarrow \boldsymbol P, \delta
 \boldsymbol F \rightarrow \nabla (\delta \boldsymbol u), \delta \boldsymbol
 u \rightarrow \boldsymbol v,$$
You recover the weak form
$$\int_\Omega \nabla \boldsymbol v : \boldsymbol P ~d\Omega - \int_{\partial
 \Omega} \boldsymbol T \cdot \boldsymbol v ~d\partial\Omega
 = 0 ~~\forall v.$$