text:
Q: What the proper way to extract images from video stream with FFmpeg libraries by external request I have a command to stream video from Raspberry Pi camera to my server by RTP protocol.
libcamera-vid -o - -t 0 -g 30 --width 640 --height 480 | ffmpeg -re -f h264 -i pipe:0 -vcodec copy -strict experimental -f rtp rtp://SERVER

I want to extract .png image (to be sure that it's uncompressed and current image) from video by request from my server, but I don't know the proper way to do this without big CPU overhead.

*

*Use OpenCV VideoCapture and VideoWriter.
Grab the frame from camera, write it to RTSP using GStreamer, then check should you send it to server. It will cause overhead and it will re-encode the frames.

*Use FFmpeg libraries (libav) directly and write a C program for streaming, then make TCP client to recive commands. But is it possible to get the image when libavcodec stream my video?

*Capture images every n second using FFmpeg, then send them when necessary. Will cause overhead and image may not required now.
-r 1/60 output.png

*Patch system to capute video and pictures at same time.


text:
Q: How to convert html into react components by using CLI command html2react? I am trying to implement automated process of converting html into react components. I am following below link to automatically convert html into react components.
https://www.npmjs.com/package/html-to-react-components
but i am getting failure of command html2react. I also installed the package by using below command.
"npm i -g html-to-react-components".
But still it is saying "'html2react' is not recognized as an internal or external command,operable program or batch file".

A: The problem was that I installed the package globally. As i installed globally so i have to place my html file in C:/Users/YourComputerName/AppData/Roaming/npm.
and then from CLI I have to open the above folder and directory in which my html2react package is installed.
And then from that directory I have to implement the html2react command.
For clear understanding i am also attaching snapshot as well. CLI command description
Have a good learning.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Компоновка Qt в среде Visual Studio 2013 Здравствуйте.
Столкнулся с проблемой компоновки виджетов в Qt. Проблема в том, что большинство уроков и примеров выполнены в/для QtCreator и для студии не подходят.
Пример моего кода с компоновкой (MyClass.cpp):
ui.setupUi(this);
QLabel * label = new QLabel(tr("Name:"),this);
label2->show();
QlineEdit *line = new QlineEdit(this);

QGridLayout *mainLayout = new QGridLayout(this);
mainLayout->addWidget(label,0,0);
mainLayout->addWidget(line,1,1);

this->setLayout(mainLayout);

Получается так, как будто бы компоновки нет, виджет LineEdit перекрывает лэйбл:

А нужно, как вы поняли, вот так (это прост для примера пикча, QtDesigner не юзаю):

Слезть со студии не могу, надо что-то решать с ней.
Пример брал отсюда, но он для Creator'a, но суть та же.
CrosPlatform.ru
Пользую (все qt с оф. сайта):
Visual Studio 2013 Ultimate
Qt 5.4.1 msvc2013
Visual Studio Add-in 1.2.4 for Qt5
Привожу весь код:
Main.cpp
#include "myclass.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MyClass w;

    w.show();

    return a.exec();
}

MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H

#include <QtWidgets/QMainWindow>
#include "ui_myclass.h"
#include <QLabel>
#include <Qlineedit>
#include <QGridLayout>

class MyClass : public QMainWindow
{
    Q_OBJECT

public:
    MyClass(QWidget *parent = 0);
    ~MyClass();

private:

    Ui::MyClassClass ui;

};

#endif // MYCLASS_H

MyClass.cpp
#include "myclass.h"

MyClass::MyClass(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    QLabel * label = new QLabel(tr("Name:"),this);
    label->show();

    QLineEdit * line = new QLineEdit(this);
    line->show();

    QGridLayout * mainLayout = new QGridLayout(this);

    mainLayout->addWidget(label, 0, 0);
    mainLayout->addWidget(line, 1,1);

    this->setLayout(mainLayout);
}

MyClass::~MyClass()
{

}

A: Понятно. QMainWindow имеет свой собственный layout для размещения внутренних элементов, поэтому навязывание своего layout ни к чему не приведет, кроме того, что Вы имеете. Есть два варианта: отнаследовать MyClass от QWidget, либо создать новый виджет, вставить в него все элементы и layout, а затем установить его, как главный виджет:
        setCentralWidget(myWidget);
BTW, а зачем в коде ui.setupUi(this)? Вы, вроде, написали, что не пользуетесь дизайнером


text:
Q: Error Loading Operating System I have a hard drive that says Error Loading Operating System.  Previously it said, "Can Not find Windows/System32/Config" and I ran the copy over from the repair directory and that fix that, but now I get the previously mentioned error.  The hard drive is seen by the BIOS, but that's about all I know.
Anyone have any ideas on how to get this fixed?
Thanks!

A: See this article : How to Deal With "Error Loading Operating System".
It contains several suggestions on how to deal with this problem, among then is doing a repair installation of XP. Do this only as the last step, although I believe that this is probably the only solution that will work.
If you have important unsaved data on the disk, try to salvage it first using a rescue CD or a Linux live CD.


text:
Q: How to add a title for button in javascript My base code :
<button class="puple margin-right" type="button" onclick="setPasswordForm()" title="<?php echo $this->__('Change Password') ?>" class="button"><?php echo $this->__('Change Password') ?></button>


text:
Q: AWS S3 Bucket Policy Deny + Open With Signed URL I have a public S3 bucket and I want to make all the files within folderA to be access via signed URL but remain folderB access publicly.
Below is the folder structure:
- Bucket (public)
  - folderA <-- want to be access via Signed URL
    - file1
    - file2
  - folderB <-- remain public
    - file3
    - file4

I tried insert the policy below into the bucket. However, after I inserted the policy, the files is totally unable to access publicly and with signed URL too.
{
    "Version": "2012-10-17",
    "Id": "Policy1596533716384",
    "Statement": [
        {
            "Sid": "Stmt1596533705733",
            "Effect": "Deny",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectAcl"
            ],
            "Resource": "arn:aws:s3:::bucket/folderA/*"
        }
    ]
}

What configure is missing from the bucket policy ?
Any opinion is appreciate. Thanks.

A: All objects in Amazon S3 are private by default.
To make the contents of folderB public, you would need to add a Bucket Policy similar to:
{
    "Version": "2012-10-17",
    "Id": "Policy1596533716384",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::bucket/folderB/*"
        }
    ]
}

This makes everything in folderB public.
As for making everything in folderA accessible via pre-signed URLs, your application would be responsible for generating the pre-signed URLs. Typically, the flow would be:

*

*A user authenticates to your application

*The user requests access to a private object (in your case, this would be something in folderA)

*The application would check whether the user is entitled to access this object

*If they are entitled to access the object, then the application would generate a pre-signed URL, which provides time-limited access to the private object

*The application would give this signed URL to the user, either as a link or as part of an HTML page (eg in a <img> tag)

*The user's browser would access the object via the provided URL. S3 would validate that the URL is correctly signed and that the time period has not expired. If so, it grants access to the private object.

Note: When you click the Open button in the Amazon S3 console, the console is generating a pre-signed URL to allow you to access a private object. This pre-signed URL is generated when you click the button and it will only work if your IAM User has been granted access to the object. That is, it uses the permissions of the person using the console to generate a pre-signed URL.
Your policy is saying "Deny everybody access to folderA". This includes the IAM User that is using the console, which is why they are unable to access the file, even when using a pre-signed URL. The pre-signed URL only has access to objects that are available to the IAM User that generated the pre-signed URL.


text:
Q: How to find Hamiltonian Cycle in a graph using BFS? (the condition is that the graph is exactly hamiltonian) I am trying to solve the Hamiltonian Cycle problem.
The condition of my task is:
The group consists of N people. In it, everyone has exactly N / 2 friends. Friendship is symmetrical (if A is friend B, then B is friend A). One person in the group has a book (his number X), which everyone would like to read and then discuss with some of the others.
It is necessary to determine the method of transferring the book, in which it would visit everyone exactly once, passing only from friend to friend, and finally return to its owner.
That is, it satisfies the condition of the Dirac's theorem.
On small graphs my solutions works properly, but on big graphs my solution gives time limit exception.
Is there any method how it can be solved faster than O(n!)?

A: There is a polynomial-time algorithm to find hamiltonian cycles in graphs where every vertex degree is at least N/2.
It's described in "A Simple Extension of Dirac's Theorem on Hamiltonicity" Yasemin Büyükçolak, Didem Gözüpek, Sibel Özkan, Mordechai Shalom.


text:
Q: Matrix factorization to get the right solution Suppose the following matrix $A$ is given
$$\begin{pmatrix}
0.500 & -0.333 & -0.167\\
-0.500 & 0.667 & -0.167\\
-0.500 & -0.333 & 0.833\end{pmatrix}$$
with its transpose $A^T$. The product $A^TA=G$ yields
$$\begin{pmatrix} 0.750 & -0.334 & -0.417\\
-0.334  & 0.667 & -0.333\\
-0.417 & -0.333  & 0.750\end{pmatrix},$$
where $G$ is a Laplacian matrix. Note that matrices $A$ and $G$ are of rank 2, with the zero
eigenvalue corresponding to eigenvector $1_n=[1~ 1 ~1]^T$.
I wonder what would be the way to obtain $A$ if only $G$ is given. I tried
eigendecomposition $G=UEU^T$, and then set $A'=UE^{1/2}$, but obtained different result. I guess this has to do with rank deficiency. Could someone explain this? Clearly, the above example is for illustration; you could consider general Laplacian matrix decomposition of the above form.

Since, for instance, Cholesky decomposition could be used to find $G=LL^T$, the decomposition on $G$ could yield many solution. I'm interested in the solution that could be expressed as $$A=(I-1_nw),$$ where $I$ is a $3\times 3$ identity matrix, $1_n=[1~ 1~ 1]$, and $w$ being some vector satisfying $w^T1_n=1$. If it simplifies matters, you could assume that the entries of $w$ are non-negative.

A: One looks for $A=I-1_3w^T$ such that $G=A^TA$, with $1_3=[1\ 1\ 1]^T$ and $w=[w_1\ w_2\ w_3]^T$ such that $w^T1_3=1$. Using $1_3^T1_3=3$, this yields
$$
G=(I-w1_3^T)(I-1_3w^T)=I-w1_3^T-1_3w^T+3ww^T,
$$
that is, for every $i\ne j$,
$$
G_{ii}=1-2w_i+3w_i^2,\quad G_{ij}=-w_i-w_j+3w_iw_j.
$$
Introducing $v=3w-1_3$, one gets $v^T1_3=0$ and, for every $i\ne j$,
$$
v_i^2=3G_{ii}-2,\quad v_iv_j=3G_{ij}+1.\tag{$\ast$}
$$
One sees that, if a solution $A=I-1_3w^T$ exists, then $G_{ii}\geqslant\frac23$ for every $i$, and, for every $i\ne j$,
$$
(G_{ij}+\tfrac13)^2=(G_{ii}-\tfrac23)(G_{jj}-\tfrac23).
$$
In the present case, these conditions are met and the system of equations $(\ast)$ reduces to $v_1^2=v_3^2=\frac14$, $v_2=0$ and $v_1v_3=-\frac14$, hence $v_1=\pm\frac12$, $v_2=0$, $v_3=\mp\frac12$.
Since $w_i=\frac13(1+v_i)$ for every $i$, the solutions are $w=[\frac12\ \frac13\ \frac16]^T$ and $w=[\frac16\ \frac13\ \frac12]^T$.
In dimension $n$, the same technique applies, which yields the conditions
$$
nG_{ii}\geqslant n-1,\qquad
(nG_{ij}+1)^2=(nG_{ii}-n+1)(nG_{jj}-n+1),
$$
and the solutions
$$
w_i=\tfrac1n\left(1\pm\sqrt{nG_{ii}-n+1}\right).
$$


text:
Q: PHP form including an extra quotation mark in the variable name I have a slightly strange error (shown below)

This is the code in my login.php file
        <form action="loginScript.php" method="post">
            <input class="center" type="text" name="username" placeholder="Username" required>

            <input class="center" type="password" name="password" placeholder="Password" required>

            <input class="center" type="submit" value="Login">
        </form>

My loginScript.php file uses var_dump($_POST).

A: Remove name="username" and retype it. Did you copy and paste the code from somewhere? Probably your editor does not show hidden special characters.


text:
Q: Configuation file for hibernate has errors <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="hibernate.connection.url">jdbc:sqlserver://cdcvgdc2012t;DatabaseName=SMS</property>
        <property name="hibernate.connection.username">training</property>
        <property name="hibernate.connection.password">Tr@!n@n10</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>

        <property name="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</property>
        <property name="hibernate.hbm2ddl.auto">update</property>

        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
        <property name="hibernate.current_session_context_class">thread</property>

        <mapping resource="com/jwt/hibernate/bean/user.hbm.xml" />
    </session-factory>
</hibernate-configuration>


text:
Q: Reference 'unit' is ambiguous, could be: unit, unit I'm trying to load all incoming parquet files from an S3 Bucket, and process them with delta-lake. I'm getting an exception.
val df = spark.readStream().parquet("s3a://$bucketName/")

df.select("unit") //filter data!
        .writeStream()
        .format("delta")
        .outputMode("append")
        .option("checkpointLocation", checkpointFolder)
        .start(bucketProcessed) //output goes in another bucket
        .awaitTermination()

It throws an exception, because "unit" is ambiguous.

I've tried debugging it. For some reason, it finds "unit" twice.

What is going on here? Could it be an encoding issue?
edit:
This is how I create the spark session:
val spark = SparkSession.builder()
    .appName("streaming")
    .master("local")
    .config("spark.hadoop.fs.s3a.endpoint", endpoint)
    .config("spark.hadoop.fs.s3a.access.key", accessKey)
    .config("spark.hadoop.fs.s3a.secret.key", secretKey)
    .config("spark.hadoop.fs.s3a.path.style.access", true)
    .config("spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version", 2)
    .config("spark.hadoop.mapreduce.fileoutputcommitter.cleanup-failures.ignored", true)
    .config("spark.sql.caseSensitive", true)
    .config("spark.sql.streaming.schemaInference", true)
    .config("spark.sql.parquet.mergeSchema", true)
    .orCreate

edit2:
output from df.printSchema()
2020-10-21 13:15:33,962 [main] WARN  org.apache.spark.sql.execution.datasources.DataSource -  Found duplicate column(s) in the data schema and the partition schema: `unit`;
root
 |-- unit: string (nullable = true)
 |-- unit: string (nullable = true)

A: Reading the same data like this...
val df = spark.readStream().parquet("s3a://$bucketName/*")

...solves the issue. For whatever reason. I would love to know why... :(


text:
Q: viewpager transform is lagging I got a view pager with only to fragment I use this code for transform animation
viewPager.setPageTransformer(false, new ViewPager.PageTransformer() {

        @Override
        public void transformPage(View page, float position) {
            final float normalizedposition = Math.abs(Math.abs(position) - 1);
            page.setAlpha(normalizedposition);
            page.setScaleX(normalizedposition / 2 + 0.5f);
            page.setScaleY(normalizedposition / 2 + 0.5f);
            page.setRotationY(position * -10);
        }
    });

but what I don't understand why my application lag while transfer from fragment to fragment
what can I do to increase the performance of transaction
BTW I use a real device with 1 G ram for testing
thanks in advance


text:
Q: Using phantom.js to generate multiple HAR files I'm using the code from netsniff.js to generate a har file and I want to improve it to generate a har file from multiple links given in an array (named links in my below code).
There is another question here Using Multiple page.open in Single Script that might help me, but I have no idea how to implement the given solution in my code..
Below is my code (it logs FAIL to load the address in the output file if the links array contain more than one item):
"use strict";
if (!Date.prototype.toISOString) {
    Date.prototype.toISOString = function () {
        function pad(n) { return n < 10 ? '0' + n : n; }
        function ms(n) { return n < 10 ? '00'+ n : n < 100 ? '0' + n : n }
        return this.getFullYear() + '-' +
            pad(this.getMonth() + 1) + '-' +
            pad(this.getDate()) + 'T' +
            pad(this.getHours()) + ':' +
            pad(this.getMinutes()) + ':' +
            pad(this.getSeconds()) + '.' +
            ms(this.getMilliseconds()) + 'Z';
    }
}
var entries = [];
function createHAR(address, title, startTime, resources)
{
    resources.forEach(function (resource) {
        var request = resource.request,
            startReply = resource.startReply,
            endReply = resource.endReply;

        if (!request || !startReply || !endReply) {
            return;
        }

        // Exclude Data URI from HAR file because
        // they aren't included in specification
        if (request.url.match(/(^data:image\/.*)/i)) {
            return;
        }

        entries.push({
            startedDateTime: request.time.toISOString(),
            time: endReply.time - request.time,
            request: {
                method: request.method,
                url: request.url,
                httpVersion: "HTTP/1.1",
                cookies: [],
                headers: request.headers,
                queryString: [],
                headersSize: -1,
                bodySize: -1
            },
            response: {
                status: endReply.status,
                statusText: endReply.statusText,
                httpVersion: "HTTP/1.1",
                cookies: [],
                headers: endReply.headers,
                redirectURL: "",
                headersSize: -1,
                bodySize: startReply.bodySize,
                content: {
                    size: startReply.bodySize,
                    mimeType: endReply.contentType
                }
            },
            cache: {},
            timings: {
                blocked: 0,
                dns: -1,
                connect: -1,
                send: 0,
                wait: startReply.time - request.time,
                receive: endReply.time - startReply.time,
                ssl: -1
            },
            pageref: address
        });
    });

    return {
        log: {
            version: '1.2',
            creator: {
                name: "PhantomJS",
                version: phantom.version.major + '.' + phantom.version.minor +
                    '.' + phantom.version.patch
            },
            pages: [{
                startedDateTime: startTime.toISOString(),
                id: address,
                title: title,
                pageTimings: {
                    onLoad: page.endTime - page.startTime
                }
            }],
            entries: entries
        }
    };
}
var page = require('webpage').create()
var fs = require('fs');
var count = 0;
function processSites(links)
{
    page.address = links.pop();
    var path = 'file' + count + '.har';
    page.resources = [];
    console.log("page resources:", page.resources)
    count = count + 1;
    page.onLoadStarted = function () {
        page.startTime = new Date();
    };
    page.onResourceRequested = function (req) {
        page.resources[req.id] = {
            request: req,
            startReply: null,
            endReply: null
        };
    };

    page.onResourceReceived = function (res) {
        if (res.stage === 'start') {
            page.resources[res.id].startReply = res;
        }
        if (res.stage === 'end') {
            page.resources[res.id].endReply = res;
        }
    };

    page.open(page.address, function (status) {
        var har;
        setTimeout(function () {
            if (status !== 'success') {
                console.log('FAIL to load the address');
                phantom.exit(1);
            } else {
                page.endTime = new Date();
                page.title = page.evaluate(function () {
                    return document.title;
                });
                entries = [];
                har = createHAR(page.address, page.title, page.startTime, page.resources);
                // console.log(JSON.stringify(har, undefined, 4));
                fs.write(path, JSON.stringify(har), 'w');

                if(links.length > 0)
                {
                    processSites(links);
                }
                else
                {
                    phantom.exit();
                }
            }
        }, 10000);
    });

}

var links = ["http://stackoverflow.com", "http://marvel.com"];

processSites(links);

Update:
The above code generate two har files file1.har and file2.har, but the second har file also contains the har code generated from both links, and it should only have the har code for the first link...
Fixed this by setting var har = " "

A: You can't iterate opening pages in PhantomJS in a simple loop because page.open method is asynchronous. It doesn't wait for first site to be processed, opening the second right away.
I've rewritten your script to use recursion: next site will be opened only after the current is processed. (Note: if any of the sites in queue will fail to load the whole process will halt, but you can easily rewrite the script to avoid that).
if (!Date.prototype.toISOString) {
    Date.prototype.toISOString = function () {
        // ...
    }
}

var entries = [];

function createHAR(address, title, startTime, resources)
{
    // ...
}

var page = require('webpage').create()

function processSites(links)
{
    page.address = links.pop();

    console.log("PAGE ADDRESS: ", page.address);
    page.resources = [];

    page.onLoadStarted = function () {
        page.startTime = new Date();
    };
    page.onResourceRequested = function (req) {
        page.resources[req.id] = {
            request: req,
            startReply: null,
            endReply: null
        };
    };

    page.onResourceReceived = function (res) {
        if (res.stage === 'start') {
            page.resources[res.id].startReply = res;
        }
        if (res.stage === 'end') {
            page.resources[res.id].endReply = res;
        }
    };

    page.open(page.address, function (status) {
        var har;
        setTimeout(function () {
            if (status !== 'success') {
                console.log('FAIL to load the address');
                phantom.exit(1);
            } else {
                page.endTime = new Date();
                page.title = page.evaluate(function () {
                    return document.title;
                });
                har = createHAR(page.address, page.title, page.startTime, page.resources);
                console.log(JSON.stringify(har, undefined, 4));

                if(links.length > 0)
                {
                    processSites(links);
                }
                else
                {
                    phantom.exit();
                }
            }
        }, 10000);
    });

}

var links = ["http://edition.cnn.com", "http://stackoverflow.com"];

processSites(links);


text:
Q: Apache uses one of the virtual hosts as the default I am using Apache with configured virtual hosts. As long as I am calling the existing virtual hosts, everything works fine.
When I call the server either with plain IP address or with a URL that does not match any virtual host, Apache uses one of the virtual host. I have no idea why is that.
The main httpd.conf (comments removed):
ServerTokens OS
ServerRoot "/etc/httpd"
PidFile run/httpd.pid
Timeout 60
KeepAlive Off
MaxKeepAliveRequests 100
KeepAliveTimeout 15

<IfModule prefork.c>
    StartServers       8
    MinSpareServers    5
    MaxSpareServers   20
    ServerLimit      256
    MaxClients       256
    MaxRequestsPerChild  4000
</IfModule>
<IfModule worker.c>
    StartServers         4
    MaxClients         300
    MinSpareThreads     25
    MaxSpareThreads     75
    ThreadsPerChild     25
    MaxRequestsPerChild  0
</IfModule>

Listen 80

LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_alias_module modules/mod_authn_alias.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule ldap_module modules/mod_ldap.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule include_module modules/mod_include.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule expires_module modules/mod_expires.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule info_module modules/mod_info.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule cache_module modules/mod_cache.so
LoadModule suexec_module modules/mod_suexec.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule version_module modules/mod_version.so

Include conf.d/*.conf

User apache
Group apache

ServerAdmin admin@mydomain.com
ServerName www.mydomain.com:80
UseCanonicalName On
DocumentRoot "/var/www/html"

<Directory />
    AllowOverride None
</Directory>

<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

<IfModule mod_userdir.c>
    UserDir disabled
</IfModule>

DirectoryIndex index.html index.html.var
AccessFileName .htaccess

<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy All
</Files>

TypesConfig /etc/mime.types
DefaultType text/plain
<IfModule mod_mime_magic.c>
    MIMEMagicFile conf/magic
</IfModule>

HostnameLookups Off

ErrorLog logs/error_log

LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
CustomLog logs/access_log combined

ServerSignature On
Alias /icons/ "/var/www/icons/"

<Directory "/var/www/icons">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

<IfModule mod_dav_fs.c>
    # Location of the WebDAV lock database.
    DAVLockDB /var/lib/dav/lockdb
</IfModule>

ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>

IndexOptions FancyIndexing VersionSort NameWidth=* HTMLTable Charset=UTF-8
AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip

AddIconByType (TXT,/icons/text.gif) text/*
AddIconByType (IMG,/icons/image2.gif) image/*
AddIconByType (SND,/icons/sound2.gif) audio/*
AddIconByType (VID,/icons/movie.gif) video/*

AddIcon /icons/binary.gif .bin .exe
AddIcon /icons/binhex.gif .hqx
AddIcon /icons/tar.gif .tar
AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv
AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip
AddIcon /icons/a.gif .ps .ai .eps
AddIcon /icons/layout.gif .html .shtml .htm .pdf
AddIcon /icons/text.gif .txt
AddIcon /icons/c.gif .c
AddIcon /icons/p.gif .pl .py
AddIcon /icons/f.gif .for
AddIcon /icons/dvi.gif .dvi
AddIcon /icons/uuencoded.gif .uu
AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl
AddIcon /icons/tex.gif .tex
AddIcon /icons/bomb.gif core

AddIcon /icons/back.gif ..
AddIcon /icons/hand.right.gif README
AddIcon /icons/folder.gif ^^DIRECTORY^^
AddIcon /icons/blank.gif ^^BLANKICON^^

DefaultIcon /icons/unknown.gif

ReadmeName README.html
HeaderName HEADER.html
IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t
AddLanguage ca .ca
AddLanguage cs .cz .cs
AddLanguage da .dk
AddLanguage de .de
AddLanguage el .el
AddLanguage en .en
AddLanguage eo .eo
AddLanguage es .es
AddLanguage et .et
AddLanguage fr .fr
AddLanguage he .he
AddLanguage hr .hr
AddLanguage it .it
AddLanguage ja .ja
AddLanguage ko .ko
AddLanguage ltz .ltz
AddLanguage nl .nl
AddLanguage nn .nn
AddLanguage no .no
AddLanguage pl .po
AddLanguage pt .pt
AddLanguage pt-BR .pt-br
AddLanguage ru .ru
AddLanguage sv .sv
AddLanguage zh-CN .zh-cn
AddLanguage zh-TW .zh-tw
LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW
ForceLanguagePriority Prefer Fallback
AddDefaultCharset UTF-8
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl    .crl
AddHandler type-map var
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
Alias /error/ "/var/www/error/"

<IfModule mod_negotiation.c>
<IfModule mod_include.c>
    <Directory "/var/www/error">
        AllowOverride None
        Options IncludesNoExec
        AddOutputFilter Includes html
        AddHandler type-map var
        Order allow,deny
        Allow from all
        LanguagePriority en es de fr
        ForceLanguagePriority Prefer Fallback
    </Directory>
</IfModule>
</IfModule>
BrowserMatch "Mozilla/2" nokeepalive
BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0
BrowserMatch "RealPlayer 4\.0" force-response-1.0
BrowserMatch "Java/1\.0" force-response-1.0
BrowserMatch "JDK/1\.0" force-response-1.0
BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully
BrowserMatch "MS FrontPage" redirect-carefully
BrowserMatch "^WebDrive" redirect-carefully
BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully
BrowserMatch "^gnome-vfs/1.0" redirect-carefully
BrowserMatch "^XML Spy" redirect-carefully
BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully

NameVirtualHost *:80
NameVirtualHost *:443

Besides httpd.conf, there is a couple of .conf files in conf.d directory, mainly for the particular virtual hosts purposes. I tried to remove all of them from this directory and restart Apache, but it had no influence on the result. Better said, if there wasn't anything in conf.d directory, then the server was working as expected - returning the contents of /var/www/html when I call the server using IP address.
Once I returned any of .conf files with the definition of virtual host into conf.d directory and restarted apache, it immediately started to return the contents of its .../public_html directory
The .conf for one of the virtual hosts is as follows:
<VirtualHost *:80>
     ServerName www.myvirtualhostdomain.com
     DocumentRoot /var/www/www.myvirtualhostdomain.com/http_www/public_html
     <Directory /var/www/www.myvirtualhostdomain.com/http_www/public_html>
        Allow from All
        Options +Indexes
        Allowoverride All
     </Directory>
     ServerAlias myvirtualhostdomain.com
     ErrorLog /var/log/httpd/www.myvirtualhostdomain.com-error_log
     TransferLog /var/log/httpd/www.myvirtualhostdomain.com-access_log
</VirtualHost>

I also tried to remove ServerName and UseCanonicalName directives, but no effect.
Also adding a "general" virtual server into httpd.conf had no effect. I tried to add the following into the very end of httpd.conf, i.e. before other .conf files are loaded, but still the same result.
<VirtualHost *:80>
    DocumentRoot /var/www/html
    ServerName www.myanotherdomain.com
</VirtualHost>


text:
Q: How can I structure my express app where I only need to open a mongodb connection once? Note: Please read the edited portion of this post before answering, it might save you time and answers one of my questions.
The problem I'm having is pretty simple but I'm pretty new to this overall and I'm having issues figuring out how to implement a mongodb database connection properly in a node/express app.
I'm using express 3.x and am basing my app layout around this project supplied by the author of Express:
https://github.com/expressjs/express/tree/d8caf209e38a214cb90b11ed59fd15b717b3f9bc/examples/blog (now removed from repo)
I have no interest in making a blog however the way the app is structured appears to be quite nice. The routes are separated and everything is organized nicely.
My problem is I might have 5-6 different route js files and each route js file might have anywhere between 1 and 15 routes; of those routes 1 or 15 might want to access the db.
So my problem is it seems like a really terrible idea to do a db.open(...) every single time I want to query the db. I should mention at this point I'm using the native mongo-db driver (npm install mongodb).
I would also need to include a file like this:
http://pastebin.com/VzFsPyax
...in all of those route files and all of my model files. Then I'm also dealing with dozens upon dozens of open connections.
Is there a way I can structure my app in such a way where I only make 1 connection and it stays open for the duration of the session (having a new one made every request would be bad too)?
If so, how can I do this? If you know the answer please post a code sample using tj's blog app (the one linked earlier in this post) structure as a base guide. Basically have a way where the routes and models can use the db freely while being in separate files than the db open code.
Thanks.
EDIT
I made some progress on solving one of my issues. If you look at tj's blog example he initializes his routes in the app.js like so:
require('./routes/site')(app);
require('./routes/post')(app);

And in the routes js file it starts like this:
module.exports = function(app){

I stumbled on a project earlier today where I saw someone pass 2 variables in the modules.exports call -> function(app, db). Then figured wow could it be that easy, do I need to just adjust my routes to be (app, db) too? Yeah, it seems so.
So now part 1 of the problem is solved. I don't have to require a mongo.js file with the connection boilerplate in every route file. At the same time it's flexible enough where I can decide to pick and choose which route files pass a db reference. This is standard and has no downside right?
Part 2 of the problem (the important one unfortunately) still exists though.
How can I bypass having to do a db.open(...) around every query I make and ideally only make a connection once per session?

A: I made a very simple module hub for this case that replaces the use of a global space.
In app.js you can create db connection once:
var hub = require('hub');
hub.db = new Db('foobar', new Server('10.0.2.15', 27017, {}), {native_parser: false});

And use it from any other files:
var hub = require('hub');
// hub.db - here link to db connection

This method uses a feature of 'require'. Module is only loaded for the first time and all the other calls gets a reference to an already loaded instance.
UPDATE
That's what I mean:
In main file like app.js we create Db connection, open it and store into hub:
app.js:
var hub = require('hub');
hub.mongodb = require('mongodb');
hub.mongodbClient = new hub.mongodb.Db('foobar', new hub.mongodb.Server('10.0.2.15', 27017, {}), {native_parser: false});
hub.mongodbClient.open(function(error) {
    console.log('opened');
});

Now in any other file (message for example) we have access to opened connection and can simple use it:
message.js:
var hub = require('hub');
var collection = new hub.mongodb.Collection(hub.mongodbClient, 'message');

module.exports.count = function(cb) {
    collection.count({}, function(err, count) {
        cb(err, count);
    });
};

A: Other solution is to pass database to the router via request, like this:
app.js
var db = openDatabase();

var app = express();

app.all('*', function(request, response, next)
    {
    request.database = db;
    next();
    });

app.get('/api/user/:id', Users.getByID);

users.js
var Users =
    {
    getByID: function(request, response)
        {
        request.database.collection('users').findOne(...)
        response.send(user);
        }
    };

module.exports = Users;

A: Really silly. In the documentation it seems like db.open requires to be wrapped around whatever is using it, but in reality you can use it without a callback.
So the answer is to just do a db.open() in your database connection module, app.js file or where ever you decide to setup your db server/connection.
As long as you pass a reference to the db in the files using it, you'll have access to an "opened" db connection ready to be queried.


text:
Q: Gaussian kernel isn't showing up I = fspecial('gaussian', [11, 11], 2);
imshow(I);

This code was supposed to generate the following 11x11 image.

But, it's not doing so,

It's totally black.
Why?
How can I generate the above image using fspecial?


text:
Q: gvisMotionChart - Date format won't show as desired - "date.format="%m" I've data from 2014-01-01 to 2015-02-26.
And i want to show it within a MotionChart from googleVis package, with the timevar showing: months, instead of concreate date: "1/1/15".
I call the data like this:
Ikasa_Adwords <- read.csv("...Ikasa_Adwords.csv",
                          header = T)

Ikasa_Adwords$date <- as.Date(Ikasa_Adwords$date)

Then apply this to generate the MotionChart:
M <- gvisMotionChart(Ikasa_Adwords, idvar="campaign", timevar="date",
                      xvar="ad.cost",yvar="impressions", date.format="%m")

plot(M)

Image:

As you see: I've "date.format="%m" but, still date is shonw as "1/1/15". Why?
My data (first rows):
      date             campaign         sessions    ad.cost ad.clicks   impressions
1   2014-01-01  Brand Search - Motos      0           1.35      7        21
2   2014-01-01  Brand Search - Autos      2           0.28      1        6
3   2014-01-01  Brand Search - Aviones    21          3.76      20       187
4   2014-01-01  Brand Search - Barcos     7           1.21      3        10
5   2014-01-01  Brand Search - Camiones   9           1.37      6        33

OutPut from str() function:
 str(Ikasa_Adwords)
'data.frame':   7878 obs. of  6 variables:
 $ date       : Date, format: "2014-01-01" "2014-01-01" "2014-01-01" ...
 $ campaign   : Factor w/ 45 levels "(not set)","Brand Search - Motos,..: 2 3 5 7 9 10 12 14 16 17 ...
 $ sessions   : int  0 2 21 7 9 14 0 9 11 5 ...
 $ ad.cost    : num  1.35 0.28 3.76 1.21 1.37 ...
 $ ad.clicks  : int  7 1 20 3 6 9 1 9 7 4 ...
 $ impressions: int  21 6 187 10 33 84 9 105 47 25 ...

A: This example a bit better actually and it may help you.
myStateSettings <-'
{"xZoomedDataMin":1199145600000,"colorOption":"2",
"duration":{"timeUnit":"M","multiplier":1},"yLambda":1,
"yAxisOption":"4","sizeOption":"_UNISIZE",
"iconKeySettings":[],"xLambda":1,"nonSelectedAlpha":0,
"xZoomedDataMax":1262304000000,"iconType":"LINE",
"dimensions":{"iconDimensions":["dim0"]},
"showTrails":false,"uniColorForNonSelected":false,
"xAxisOption":"_TIME","orderedByX":false,"playDuration":15000,
"xZoomedIn":false,"time":"2010","yZoomedDataMin":0,
"yZoomedIn":false,"orderedByY":false,"yZoomedDataMax":100}
'
M6a <- gvisMotionChart(Fruits, "Fruit", "Year",
                       options=list(state=myStateSettings))
plot(M6a)

See the difference when you change "timeUnit":"M" to "timeUnit":"Y"; this may help.


text:
Q: sms credit deduction concurrency issue I currently writing an sms system for the end user. however, When I do the testing on the function i encounter sms credit deduction error.
There are three table in this function which are company, user and transaction.
I did many testing on this function. just cant get the credit deduction correctly.
for example there are 1000 credit in each table.
Initial value
company.sms_bal     = 1000
user.user_credit_bal= 1000
transaction.transaction_balance = 1000
testing #1
deduct 1 credit on each table. it deducts correctly.
company.sms_bal     = 999
user.user_credit_bal= 999
transaction.transaction_balance = 999
testing #2
deduct 2 credit on each table. it deducts incorrectly,
company.sms_bal     = 997
user.user_credit_bal= 997
transaction.transaction_balance = 998 suppose to be 997.
P/S it does not always deduct incorrectly, just sometimes. Please kindly advice me. However if you are unsure my question just let me know I am willing to assist you.
Below is the function for your reference
function process_send_sms($data){
global $CONF, $Q, $OUT, $DB, $DBSH, $CODE, $LANG;

//
//  check credit
//
$check_credit = check_credit($data);

if($check_credit['status'] == '100'){

    //
    // check credit and update credit and update track
    //
    // get $company_credit_bal
    $DBSH->u_select('company', $company_data, array(
        'company_id' => $company_id,
    ));
    $company_credit_bal = $company_data['sms_bal'];
    // get $user_credit_bal
    $DBSH->u_select('user', $user_data, array(
        'user_id' => $user_id,
    ));
    $user_credit_bal = trim($user_data['user_credit_bal']);
    $number_bulk_mt  = trim($total_credit);

    //
    // update company
    //
    $rows = $DBSH->update(array(
        'table'  => 'company',
        'set'    => array(array('sms_bal = ?', $company_credit_bal - $number_bulk_mt),),
        'where'  => array(array('company_id = ?', $company_id),),));

    $rows = $DBSH->update(array(
        'table'  => 'user',
        'set'    => array(array('user_credit_bal = ?', $user_credit_bal - $number_bulk_mt),),
        'where'  => array(array('user_id = ?', $user_id),),));

}else{
    $return_data['error'] = $check_credit['error'];
}

if($check_credit['status'] == '100'){
    //
    // insert to the track
    //
    $arr = debug_backtrace();
    $function_name =  $arr[0]["function"];
    $data = array(
        'no_phones'             => $total_credit,
        'company_id'            => $company_id,
        'user_id'               => $user_id,
        'msg_type'              => $function_name,
        'track_mt_create_time'  => $timestr,
        'track_mt_update_date'  => $timestr,
    );

    $DBSH->u_insert('bulk_mt_log_track', $data);
    $ref_id = $DBSH->u_lastid('bulk_mt_log_track');

    if($sendsmscsv == 'Y'){
        foreach($phone_tem as $k => $v){
            $phone_no = $v['phone'];
            $message  = $v['message'];
            $coding   = 1;
            if($v['lang'] == '2'){
                $coding = 3;
            }
            $check_credit = $credit_class->check_per_credit($phone_no,$is_intern);
            $send_c_code  = $check_credit['c_code'    ];
            $per_credit   = $check_credit['per_credit'];
            if($phone_no){
                do{
                    $msgid = session_get()."_".$user_id;
                    $check_valid === false;
                    $found = $DBSH->u_count('bulk_mt_log_data', array(
                        'msgid' => $msgid,
                    ));
                    if(!$found){
                        $check_valid === true;
                    }
                    $found = $DBSH->u_count('bulk_mt_log', array(
                        'msgid' => $msgid,));
                    if(!$found){
                        $check_valid === true;
                    }
                }while($check_valid === false);
                //
                //  Perform merge sms
                //
                $message = process_message_merge($phone_no,$user_id,$message,$company_id);

                if($coding == '3'){

                    $len = mb_strlen($message, 'UTF-8');

                    $arr = array();
                    for( $i=0; $i<$len; $i++){
                       $arr[] = mb_substr($message,$i,1,'UTF-8');;
                    }

                    $message2="";
                    foreach($arr as $k => $substr){
                        $message2 .= uniord($substr);
                    }
                    $message = $message2;
                }
                else{
                    $coding = 0;
                }
                $data = array(
                        'bulk_mt_log_id'   => null,
                        'user_id'          => $user_id,
                        'company_id'       => $company_id,
                        'mt_to'            => $phone_no,
                        'campaign'         => $campaign_name,
                        'mt_status'        => 'P',
                        'mt_text'          => $message,
                        'coding'           => $coding,
                        'msgid'            => $msgid,
                        'is_intern'        => $is_intern?$is_intern:'NOT',
                        'per_credit'       => $per_credit ? $per_credit:'0',
                        'mt_from'          => $mt_from?$mt_from:'',
                        'send_c_code'      => $send_c_code,
                        'mt_create_date'   => $timestr,
                        'mt_update_date'   => $timestr,
                        'ref_id'           => $ref_id,
                        'gateway_id'       => $gateway_id,
                        );
                $DBSH->u_insert('bulk_mt_log', $data);

                $rows = $DBSH->select(array(
                    'field' => array('*'),
                    'table'  => 'transaction',
                    'where'  => array(array('company_id = ?', $company_id),
                                     array('transaction_balance > ?', 0),
                                     array('transaction_sms_expire_date > ?', $timestr),),
                    'order' =>  'transaction_sms_expire_date ASC',
                ));
                $data_transaction_id = array();
                while($row = $DBSH->fetchRow(DB_FETCHMODE_ASSOC)){
                    $data_transaction_id[] = $row[transaction_id];
                }
                $transaction_id = $data_transaction_id[0];
                if($transaction_id){
                    $rows = $DBSH->update(array(
                    'table'  => 'transaction',
                    'set'    => array(array('transaction_balance = transaction_balance - '.$per_credit),),
                    'where'  => array(array('company_id = ?',   $company_id),
                                     array('transaction_id = ?',    $transaction_id),),
                    ));
                }
            }
        }
    }else{
        if ($phone){
            foreach($phone as $k => $phone_no){
                foreach($sms_message as $km => $message){

                    $check_credit = $credit_class->check_per_credit($phone_no,$is_intern);
                    $send_c_code  = $check_credit['c_code'    ];
                    $per_credit   = $check_credit['per_credit'];
                    if($phone_no){
                        do{
                            $msgid = session_get()."_".$user_id;
                            $check_valid === false;
                            $found = $DBSH->u_count('bulk_mt_log_data', array(
                                'msgid' => $msgid,
                            ));
                            if(!$found){
                                $check_valid === true;
                            }
                            $found = $DBSH->u_count('bulk_mt_log', array(
                                'msgid' => $msgid,));
                            if(!$found){
                                $check_valid === true;
                            }
                        }while($check_valid === false);
                        //
                        //  Perform merge sms
                        //
                        $message = process_message_merge($phone_no,$user_id,$message,$company_id);

                        if($message_type == 'unicode'){
                            $coding = 3;
                            $len = mb_strlen($message, 'UTF-8');

                            $arr = array();
                            for( $i=0; $i<$len; $i++){
                               $arr[] = mb_substr($message,$i,1,'UTF-8');;
                            }

                            $message2="";
                            foreach($arr as $k => $substr){
                                $message2 .= uniord($substr);
                            }
                            $message = $message2;
                        }
                        else{
                            $coding = 0;
                        }
                        $data = array(
                            'bulk_mt_log_id'   => null,
                            'user_id'          => $user_id,
                            'company_id'       => $company_id,
                            'mt_to'            => $phone_no,
                            'campaign'         => $campaign_name,
                            'mt_status'        => 'P',
                            'mt_text'          => $message,
                            'coding'           => $coding,
                            'msgid'            => $msgid,
                            'is_intern'        => $is_intern?$is_intern:'NOT',
                            'per_credit'       => $per_credit ? $per_credit:'0',
                            'send_c_code'      => $send_c_code,
                            'mt_create_date'   => $timestr,
                            'mt_update_date'   => $timestr,
                            'ref_id'           => $ref_id,
                            'mt_from'          => $mt_from?$mt_from:'',
                            'gateway_id'       => $gateway_id,
                        );
                        $DBSH->u_insert('bulk_mt_log', $data);

                        $rows = $DBSH->select(array(
                            'field' => array('*'),
                            'table' => 'transaction',
                            'where' => array(array('company_id = ?', $company_id),
                                            array('transaction_balance > ?', 0),
                                            array('transaction_sms_expire_date > ?', $timestr),
                                        ),
                            'order' => 'transaction_sms_expire_date ASC',
                        ));

                        $data_transaction_id = array();
                        while($row = $DBSH->fetchRow(DB_FETCHMODE_ASSOC)){
                            $data_transaction_id[] = $row[transaction_id];
                        }
                        $transaction_id = $data_transaction_id[0];
                        if($transaction_id){
                            $rows = $DBSH->update(array(
                                'table'  => 'transaction',
                                'set'    => array(array('transaction_balance = transaction_balance - '.$per_credit),),
                                'where'  => array(array('company_id = ?',   $company_id),
                                                array('transaction_id = ?', $transaction_id),),
                            ));
                        }
                    }
                }
            }
        }
    }

}else{
    $return_data['error'] = $check_credit['error'];
}

if($return_data){
    $return_data['status'] ='102';
}else{
    $return_data['status'] ='100';
}
return $return_data;

}


text:
Q: How to monitor which apps are "calling home'? I want to monitor one app on my phone to see what webservice it is accessing when it first launches.  I remember seeing an article on TUAW a while ago that detailed using Charles snooper, or something like that to set up a network to detect that.  However, I can't find it.  Anyone know where it went?

A: For a fully featured application to monitor other applications' network usage (all traffic, not just http), try Little Snitch.
EDIT
Apologies, missed the whole key "app on my phone" bit. There is no way for one process to inspect or intercept data from any other app, since all apps are sandboxed. The only way to get close to accomplishing this is through a jailbreak.
Otherwise, you would have to enable logging on your router, and the specifics on how to do this or how easy it is depends on your firewall/modem/router. Little Snitch may still be able to help you here if you have your Mac act as the wireless access point.

A: Is this what you're looking for?
http://www.tuaw.com/2011/02/21/how-to-inspect-ioss-http-traffic-without-spending-a-dime/


text:
Q: How to do a directory redirect I've seen websites have profile pages do things like 'http://www.example.com/myusername/ show the the person with the username 'myusername's' profile. I was wondering how to do this?
I've seen examples on how to do this with htaccess but it does a full redirect, not allowing post data, get data, etc. How could I do this?

A: Use .htaccess's mod_rewrite option to create rewrites that will maintain the query string and/or posted data. A quick example (taken from CodeIgniter) :
RewriteEngine on
RewriteCond $1 !^(index\.php|[Javascript / CSS / Image root Folder name(s)]|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

This will mean that all requests go to index.php and your index.php script would be setup to parse this URL into a proper class and/or function. This allows for a single entry point that can be managed by a system. This is used by all major systems, from Wordpress to Magento to Laravel 4 to CodeIgniter.

A: .htaccess allows to "post" (the right word would be GET) data in a querystring using a directory-like style
You have to activate the RewriteEngine and then write a rule to convert the querystring expected by your page in a directory-style sintax, in order to write these rules you have to use some regular expression to map the elements in the url that will be recognised as the variables and the respective values of you querystring
For example
if you want to rewrite a query string like this:
www.sitename.com/showimages.php?album=sea&photo=mysurf

in a query like this:
www.sitename.com/sea/mysurf

you have to write the sequent rule:
 RewriteEngine on
 RewriteRule ^([a-z0-9]+)/([a-z0-9]+)/?$ /showimages.php?album=$1&photo=$2 [NC,L]

here is an interesting and simple guide to ".htaccess URL rewrite" http://edward-designer.com/web/htaccess-url-rewrite-simplified/
I apologize for my bad English
Hope this helps


text:
Q: Have I understood what Arduino is correctly? Just before I go out and buy an Arduino starter kit, can someone confirm I understand what it is?
As I understand it, I can use a simulator to create the behaviour I want. Once I'm happy with the code I compile it, connect the Arduino Uno to my computer (with a "blank chip attached) and flash the chip. Then I can remove the chip, and put it on a breadboard, or Matrix Strip or suchlike and work it into a project.
Is that right?

A: Not quite, no.
The Arduino is a whole system in itself.
While it is possible to remove the chip from the board and use it in your own systems this is seldom done.
With the Arduino you program your "sketch" (as they call it) in a subset of C++ based on a system called "Wiring".  You then upload this to the Arduino board.  The board already has the chip on it, and you leave it there.  There are connections on the board to link it to your other systems.
You can change your "sketch" as many times as you like and re-upload it to the Arduino until you get it right.
While there are simulators, they are seldom used as it's easiest to just upload to the Arduino directly and have it interact properly with your external hardware.

A: You can definitely remove the chip from the arduino, and use it on a bare board or in another project. The chip on the arduino uno and older versions of the arduino duemilanove is an atmega328 (some versions have an atmega168). You can find the actual reference to the chip at the atmel website (can't post links because not enough karma) . The thing to take care of is that the pin numbers are actually quite different from those on the arduino board. Here is a page with the actual pinout, in case you want to use it in another project or read up things in the datasheet: http://www.arduino.cc/en/Hacking/PinMapping168 When you remove the chip, be careful to not bend the legs of the chip. I usually use a flat screwdriver I insert under the chip on one side, and carefully wiggle my way halfway through. Then repeat on the other side, et voila, clean pulling of the chip. Be careful when plugging it back in as well, as sometimes one leg gets a bit outside of its receiving slot and bends when pushing it back down.
What makes arduino "special" as a development board is the environment used to program it. Similar to processing (it uses the same code base), it's a kind of simplified frontend to the c++ language. The code you write in the arduino editor gets some stuff added in front and in back, and is compiled using avr-g++ to a working executable. It also gets linked to what is called the "core", which can be found in the folder hardware/cores/arduino in the Arduino folder. It initializes a few things (like timers and serial interface), and implements the helper functions we all know and love: digitalWrite, analogRead, etc... In case you want to know more about avr-gcc programming in general, there are a lot of tutorials around. I can recommend the website http://www.avrfreaks.net/, which has a lot of links and tutorials.
This binary file is then uploaded to the chip on the arduino using a program called avrdude, which again is called automatically by the processing like GUI. This program will upload the binary file through the serial port, to what is called a bootloader on the atmega328. A bootloader is a small program (usually 2kB or 4kB) that is stored permanently on the chip. If you remove it, use it in another board, and plug it back, you'll be able to use the arduino software again. The arduino chip uses a slightly modified version of the stk500 protocol, and requires a patch to avrdude. It takes a bit of will to actually overwrite the bootloader, but that is something that is quite possible. You can then either use a standard programmer to reflash the arduino. You can actually use another arduino as a flash programmer: google for arduino ISP

A: No, you misunderstood. The chip isn't blank (also you don't insert the chip into Arduino. It comes with the Arduino). It has a special bootloader which is actually the core of the Arduino platform and which allows Arduino not to have a special programmer to program the chips. So it will not work with blank chips at all. Furthermore you're limited only to chips which are supported by the bootloader or are very similar.
Also from what I can see, the Arduino IDE doesn't have a simulator, so you're out of luck on that point.
The main point of Arduino is that it hides the physical operation of the chip itself from the programmer making it easier to use for those that find it too complicated to start programming the chip directly. It offers a simplified C-like programming language and it has a large library of functions which make it easy to connect various peripherals. The PCB itself is useful since it allows users to have a good quality base from which to make their own devices and saves them the trouble of making a PCB which will drive the AVR themselves or using some type of prototyping board.
Basically what you want is regular Atmel's IDE called AVR Studio which does have a simulator (you can download it freely and check if it suit your needs). On the hardware side, you'll need either a programmer, if the IDE's simulator is fine, or a in-circuit emulator which will allow you to directly debug the code on the chip. The emulator itself is pretty expensive, but there are some other products that will allow you to step through the code too.
Do note that it is possible to make an AVR programmer using Arduino but that isn't a major advantage over other programmers available on the Internet or the official programmer.

A: You can in fact use the Arduino to clone itself into a bare ATMEGA chip, using the ArduinoISP sketch.  Some might consider that an obscure capability, others use it routinely.
Primarily what the Arduino idea gets you is two things: a bootloader in the chip, so that you can load functional programs using a serial port rather than a special programmer tool (most current boards have a built-in USB-serial converter).  Secondarily, there's an IDE and set of libraries intended to make embedded development easier for newbies - it's worth noting that not everyone who uses the hardware and bootloader uses the IDE and libraries - some prefer to code for the AVR chip directly.
Additionally, there is a physical/electrical interface design for accesorry "shields" which stack onto the main board and provide a wide range of add-ons (though these generally are not cost competitive with other micro-controllers/boards that have such peripherals built-in)
You can buy Arduino compatible boards from many sources and in many form factors, either assembled or as kits, you can also buy atmega chips pre-loaded with an Arduino or similar bootloader.

A: The Propeller micro controller from parallax.com fits what you describe. The "Propeller Educational Kit" comes the Propeller chip, an EEPROM, a USB to Serial plug, breadboard and other few discrete components and a well written and easy to read manual. It takes few minutes to build the circuit on the breadboard and you are ready to write and download programs to the EEPROM. You program it in an easy to learn language called SPIN, as well as PASM (Propeller Assembly).
The Propeller is the very first micro controller I "played" with. I use the kit to program an EEPROM, then put the EEPROM in another "stand alone" Propeller based circuit I built on a stripboard. Stand alone meaning it does not have the USB to serial plug.


text:
Q: Facebook: Graph API not able to get lead generation forms created for particular page https://graph.facebook.com/v12.0/page-id/leadgen_forms?access_token=access_token
not able to get data of lead generation forms created for this page anyone any comment meanwhile i am making API on python
Getting this error response
{
"error": {
"message": "(#100) Tried accessing nonexisting field (leadgen_forms) on node type (Application)",
"type": "OAuthException",
"code": 100,
"fbtrace_id": "A2khWnhkIxvEywUcRj-rGt4"
}
}

A: It will be called like this finally i found this solution this question is pending on even Facebook forum since last one year.
https://graph.facebook.com/v12.0/page_id/leadgen_forms?pretty=0&fields=leads_count,name,page,status,created_time,about,context_card,tracking_parameters&limit=25&access_token=access_token


text:
Q: Firefox keyword search using javascript I want to use a travel planner making full use of Firefox' Keyword Searches.
The keyword search basically just inputs a string somewhere in a predefined URL, e.g. google.com/search?q=%s with cats and dogs will go to https://www.google.com/search?hl=en&q=cats%20and%20dogs.
Q1: However, the URL needs the (current) date, so this needs to be entered variably as well.
Because we need a starting location and final location we need to enter two search string, which is possible (explained here).
Q2: I would also like to be able to e.g. enter 'h' for my home address.
The URL format of the travel planner is as follows:
https://www.ns.nl/reisplanner/#/?vertrek=STARTLOCATION%20Centraal&vertrektype=treinstation&aankomst=ENDLOCATION&aankomsttype=treinstation&type=vertrek&tijd=2023-03-03T15:59&firstMileModality=PUBLIC_TRANSPORT&lastMileModality=PUBLIC_TRANSPORT&disabledTransportModalities=
I currently have:
javascript:var%C2%A0s='%s';
url='https://www.ns.nl/reisplanner/#/?vertrek=%s&vertrektype=treinstation&aankomst=%s&aankomsttype=treinstation&type=vertrek&tijd=currentDateInRightFormat&firstMileModality=PUBLIC_TRANSPORT&lastMileModality=PUBLIC_TRANSPORT&disabledTransportModalities=';
const h='My Home Street 1 My Home Town'
const w='My Work Street 1 Work City'
const currentDateInRightFormat = new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0].slice(0,16));
t='';
qc=0;
chunks=url.split('%s');

for(i=0; i<s.length; i++){
    if(s.charAt(i)=='%22')qc=qc^1;
    t+=((s.charAt(i)==' '&&qc)?'^':s.charAt(i));
}
args=t.split(/\s/);

nurl='';

for(i=0; i<chunks.length; i++){
    nurl+=chunks[i];
    if(args[i]!=undefined)%C2%A0{
        args[i]=args[i].replace(/\^/g,' ');
        nurl+=args[i];
    }
}
location.replace(nurl,'< BR>');

So I would like to be able to:

*

*enter the currentDateInRightFormat in the URL

*use the string 'h' which then inputs my predefined home address, string 'w' for work, etc.


text:
Q: Solving a system of linear equations using matrices I am trying to find a solution to the equation $\pi A = 0$ where $A$ is an $n\times n$ matrix as follows:
$$A = \begin{bmatrix}
    -6 & 6 & 0 \cdots & \, & \, & \, & 0\\
    1 & -7 & 6 & 0 &\cdots & \,  & 0 \\
    0 & 2 & -8 & 6 & 0 &\cdots & 0 \\
    \vdots & \ddots & \\
    0 & \dots & \dots & \,  && n-1 & -n-5
    \end{bmatrix}$$
So I have $-k-5$ as the diagonal element for the $k^\text{th}$ row, $6$ above the diagonal and $k$ as the element below the diagonal element for the $k^\text{th}$ row. May I know how I can solve for $\pi$ which is a row vector of size $n$?

A: In general, if $A$ is a $n\times n$ matrix, the system $xA = 0$ has an unique solution if and only if $A$ is row-equivalent to the $n\times n$ identity matrix $I_{n\times n}$.
Now, the matrix $A$ you presented in the problem is indeed row-equivalent to $I_{n\times n}$. I will not provide a full proof, but a sketch instead, which I hope to be useful.
I came with this solution by manually row-reducing $A$ from $n=1$ up to $n=4$ and noticing I was actually doing the same steps over and over. I'll show you what I did when row-reducing the $n=4$ case in order; first let's get $A$ to echelon form:

*

*Multiply row $1$ by $-1/6$, then add $-1$ times row $1$ to row $2$.

*Then, multiply row $2$ by $-1/6$, then add $-2$ times row $2$ to row $3$.

*Then, multiply row $3$ by $-1/6$, then add $-3$ times row $3$ to row $4$.

*Then, multiply row $4$ by $-1/6$.

Now, let's get $A$ to it's row-reduced-echelon form:

*

*Add $1$ times row $4$ to row $3$.

*Add $1$ times row $3$ to row $2$.

*Add $1$ times row $2$ to row $1$.

In general, for any $n$, if you want to get from $A$ to $I_{n\times n}$, the steps to take are:

*

*To get $A$ in echelon form: for each $ 1 \leq i \leq n$, starting from $i=1$, first multiply the $i$-th row by $-1/6$, then add $-i$ times row $i$ to row $(i+1)$ (except when $i=n$, because there's no $(n+1)$-th row in a $n\times n$ matrix).

*To reduce it: for each $1 \leq i \leq n$, add $1$ times row $i$ to row $(i-1$) (again, except when $i=1$, for there is no $0$-th row in a matrix).

*$A$ is now in row reduced echelon form, and it is row-equivalent to $I_{n\times n}$.

This means that the system $xA=0$ has indeed an unique solution, which is $x=0$.


text:
Q: Magicsuggest with Codeigniter output with post is quoted with square brackets I have finally got magicsuggest working with json on codeigniter. The only issue that i have now is that when i post the values are like ["1"], is there any way (other than preg_replace() or str_replace) that i can strip everything so that i have just the number or string without the quotes and square brackets.
Below is the controller function
public function json_hotelquery() {
    $query = $this -> tourquery -> get_hotels();

    $return_arr = array();
    foreach ($query->result() as $row) {
        $row_array['id'] = $row->id;
        $row_array['name'] = $row->hotelname;

        array_push($return_arr,$row_array);
    }
    $this->output->set_content_type('application/json');
    $this->output->set_output(json_encode($return_arr));

}

and this is the jquery for magicsuggest
$('#hotel_name').magicSuggest({
    selectionPosition: 'bottom',
    selectionStacked: true,
    maxSelection : 1,
    displayField: 'name',
    data: '<?php echo site_url('dashboard/json_hotelquery'); ?>'
});

And this is the output from post
Array([hotel_name] => ["5"])

A: Sorry for the delay maldivianGeek. I'm the author of the plugin and have been overbooked the past couple of months :( Anyways with the latest 2.0 release the passed values will just be like if you were passing a bunch of checkbox values. You can check out the new documentation and tutorial page that explains that pretty well.
Cheers


text:
Q: How to split a string at every four words in c#? I'm using C# 4.0 and have come across a situation where I have to split a whole string by every four words and store it in a List object.
So suppose my string contains: "USD 1.23 1.12 1.42 EUR 0.2 0.3 0.42 JPY 1.2 1.42 1.53", the result should be:
USD 1.23 1.12 1.42
EUR 0.2 0.3 0.42
JPY 1.2 1.42 1.53

It shall be saved into a List object. I have tried the following
List<string> test = new List<string>(data.Split(' ')); //(not working as it splits on every word)

A: Of course my answer is not as glamour as the linq ones, but I wish to post this old school method.
void Main()
{
    List<string> result = new List<string>();

    string inp = "USD 1.23 1.12 1.42 EUR 0.2 0.3 0.42 JPY 1.2 1.42 1.53";
    while(true)
    {
        int pos = IndexOfN(inp, " ", 4);
        if(pos != -1)
        {
            string part = inp.Substring(0, pos);
            inp = inp.Substring(pos + 1);
            result.Add(part);
        }
        else
        {
            result.Add(inp);
            break;
        }
    }
}

int IndexOfN(string input, string sep, int count)
{
    int pos = input.IndexOf(sep);
    count--;
    while(pos > -1 && count > 0)
    {
        pos = input.IndexOf(sep, pos+1);
        count--;
    }
    return pos ;
}

EDIT:
If there is no control on the numbers on the input string (for example, if some money has only 1 or 2 values) then there is no way to substring correctly in blocks of 4 the input string.
We can resort to Regex
List<string> result = new List<string>();

string rExp = @"[A-Z]{1,3}(\d|\s|\.)+";
// --- EUR with only two numeric values---
string inp = "USD 1.23 1.12 1.42 EUR 0.2 0.42 JPY 1.2 1.42 1.53";
Regex r = new Regex(rExp);
var m = r.Matches(inp);
foreach(Match h in m)
   result.Add(h.ToString());

this pattern accepts also numbers with comma as decimal separator and money symbols without any numbers ("GPB USD 1,23 1,12 1.42 "
string rExp = @"[A-Z]{1,3}(,|\d|\s|\.)*";

RegEx Expression Language - Quick Reference

A: Easiest way would be to first split it at every word into a list, then write a little loop that re-combines each group of four words.

A: With a little Linq magic:
var wordGroups = text.Split(' ')
                     .Select((word, i) => new { Word = word, Pos = i })
                     .GroupBy(w => w.Pos / 4)
                     .Select(g => string.Join(" ", g.Select(x=> x.Word)))
                     .ToList();

A: The reactive framework guys have an bunch of extensions for IEnumerable<T>. One of them is Buffer which does what you want so simply.
Here it is:
var text = "USD 1.23 1.12 1.42 EUR 0.2 0.3 0.42 JPY 1.2 1.42 1.53";
var result = text.Split(' ').Buffer(4);

And that gives:


text:
Q: Fetching Merge Commit in Azure Devops Server 2019 Results in Excessive Files I have been observing some very odd behavior with our Azure Devops Server 2019 server.  Occasionally fetches pull down vastly more data than necessary to complete a fetch.  This usually happens around large merges, however yesterday it happened with a relatively simple one.
I had two branches which were diverged by about a dozen commits.  I had both branches fully checked out on my machine.  I used a pull request to merge them together.  Upon doing a fetch from my machine after the pull request completed, it required pulling down 28,000 files and 2GB of information and took an exceedingly long time to pull.
Any ideas why this would happen?  The merge did not have any conflicts, only one side of the merge had changes since the last merge. (An ours merge indicating that a set of environmental configuration changes from the branch being merged in were irrelevant.)  All the commits aside from the clean merge commit were already on my machine and checked out.  This should have been a very simple operation, not require resending an appreciable portion of my repository.

A: I was able to solve the major case we were running in to, but not the initial illustration I used in this question.
The majority of our users that were running in to a problem like this were due to limited refs being enabled and a large limited ref got joined to the history chain by an "ours" merge.  That isn't relevant to the particular case I experienced as I had relevant histories locally, but other people may encounter this problem due to a merge including previously unreferenced history much earlier in the history.
For now I haven't been able to reproduce my initial error, so I'll have to wait until the next time I see it (it tends to happen around branch cuts where the hidden history isn't a factor as well.)  But if anyone else has any additional ideas, I'd love to hear them.
If anyone else encounters a similar error, using GIT_TRACE_PACKET to get the list of haves and wants is super helpful for working your way through the history and finding out the origin of the objects being fetched.

A: I was able to track down the root issue to a defect in Azure Devops Server.  It appears that Azure Devops Server responds with an "ACK ready" prematurely during the fetch_pack/upload_pack negotiation phase.  Despite two entire branch histories being undiscovered (for branches currently in the want list), Azure Devops gives a ready and begins the pack transfer.


text:
Q: Evaluating integral $\int\frac{2(\cos x + \sin x)}{\sin 2x} dx$ Evaluate
$$\int\frac{2(\cos x + \sin x)}{\sin 2x} dx$$
I have tried a few times and came up with an answer
$$-\ln | \csc x + \cot x| +\frac 12\ln |\tan x + \sec x| + C$$
which is incorrect. I just need someone to explain what is wrong with my answer.

A: Use $\sin2x =2\sin x\cos x$,
$$\int\frac{2(\cos x + \sin x)}{\sin 2x} dx
=\int\frac1{\sin x} dx+ \int \sec x dx $$
$$=\ln \tan \frac x2 + \ln (\tan x + \sec x) + C$$
where the two integrals are obtained as follows
$$\int\frac{dx}{\sin x}=\int\frac{dx}{2\sin \frac x2\cos\frac x2}
=\int\frac{\sec^2\frac x2dx}{2\tan\frac x2}=\ln \tan \frac x2 $$
$$\int \sec x dx = \int \frac{\sec x\tan x + \sec^2 x}{\tan x + \sec x}dx
=\int \frac{d(\tan x+ \sec x)}{\tan x + \sec x}=  \ln (\tan x + \sec x)$$


text:
Q: How can I tell which process is newest? I have a utility which runs a process with elevated privilges (effectively allowing us to run stuff that requires admin privilege from scripts).
I need to check this utility is working, and the way I am doing this is to open a command prompt with admin privilege, detect if it has opened (if the utility is not working, it will fail to open the command prompt) and then close the command prompt again.
I can do this fine, but I want to handle the situation where a user has already got a command prompt open, by identifying which process opened most recently.
The code I have at the moment is:
C:\myutility.exe cmd
$proc = Get-CimInstance Win32_Process -Filter "name='cmd.exe'"

$isnull = ($proc -eq $null)

if (!$isnull) { #Process did not start

    $latest = $proc[$proc.Length-1]
    $owner = Invoke-CimMethod -InputObject $latest -MethodName GetOwner
    foreach ($p in $proc) {
        $command = "powershell stop-process -id " + $p.Handle
        c:\myutility.exe powershell stop-process -force -id $p.Handle
    }
    if ($owner.User -eq "Administrator") {
        write-output $true
    } else { # User is not Admin userx`
        write-output $false
    }

} else { #Failed to start administrator cmd prompt
    write-host $false
}

And I want to add something whether the process is the latest one. I wondered if using the process handle would be sufficient, but I'm not 100% that the highest handle ID is the latest process.
Is there a more reliable way to do this?


text:
Q: IIS Point new subdomain to existing virtual directory So Currently I have a site accessible by http://hostname/myvirtualdirectory/home.aspx If you go to http://hostname/myvirtualdirectory it automatically goes to home.aspx... good!
However when I go to http://hostname it gives the IIS start page.
Question 1:
How do I make this redirect to the virtual directory myvirtualdirectory/home.aspx
I have pointed a subomdain mysubdomain.myurl.com at the server, everything works pretty much the same if I go to http://mysubdomain.mysite.com/ I get the start page but going directly to http://mysubdomain.mysite.com/myvirtualdirectory does go to the home.aspx page
Question 2
Once I point everything correctly in the answer to question 1 do I need to do anything extra to handle the subdomain?
Thanks!

A: I'm going to assume you're using IIS 7.0 or above.
Answer to question 1)
Ensure you have the HTTP Redirection feature installed, and then setup a redirct on the root website, details here: http://www.iis.net/configreference/system.webserver/httpredirect
Answer to question 2)
You don't need to do anything extra to handle the sub domain unless you've set up multiple websites on the server, from your question I'm guessing that's not the case.


text:
Q: how to include css and js files to php template? i have built my simple template for php site.
the problem is that i don knw the nice way to include my css  and javascript files .
here is my index.php file
<?php
include'core/template.php';
$temp=new Template();
$settings=array("title","page_title","welcome_word");
$values=array("RIS - Home","Results Information System","Welcome to result
               Information      system");
$temp->header($settings,$values);
$temp->footer();

?>

here is my template.php file
<?php
class Template {
public function header($setting,$values){
    $file=file_get_contents("http://localhost/RIS/src/header.php");
    $count=0;
    foreach ($setting as $setting) {
        $file=str_replace('{'.$setting.'}',$values[$count],$file);
        $count++;
    }
    echo $file;

}

public function footer(){
    $file=file_get_contents("http://localhost/RIS/src/footer.php");
    echo $file;
}
}

?>

here is my header.php file
<!DOCTYPE html>

    <title>{title}</title>

{page_title}

            {welcome_word}

    My contents goes here...

here is my footer.php file

Copyright © RIS 2013.

i have my css files and js files are in assets folder  so how do i include them in my template?

A: For CSS files:
<!DOCTYPE html>

    <title>{title}</title>
    <link rel="stylesheet" href="path/to/assets/yourcss.css" type="text/css">

{page_title}

            {welcome_word}

    My contents goes here...

and for javascripts:

Copyright © RIS 2013.

A: I would use output buffers & include instead of file_get_contents, include'core/template.php'; here is a blankspace missing.
In your case, why not just put the CSS and JS into header.php ?
Or if you want non-blocking, put CSS in header.php and JS in footer.php

A: Why do you use "file_get_contents", you can use "include_once" to include your footer file.
For your template, put a marker for the css, and build your css array in php then inject it to your marker.
Hope it helps.


text:
Q: Using non-default editors with /edit command I was recently trying to use non-default editors (such as atom or sublime) with the /edit command in JShell. To do that, I set the editor with the following command:
/set editor -wait atom
As the documentation states, when I type the /edit command JShell creates a temporary file opened by the editor of my choice. The code that is saved in the file gets evaluated by JShell. However I cannot make it evaluate the changes immediately after i hit save. They are being evaluated in the shell after a few seconds after saving in the editor.
Is there any way to have them evaluated immediately, the same as by hitting "Accept" in the EditPad (the default editor)?


text:
Q: Getting phantom 'b' when converting numpy object array to datetime I have a large data set with many columns. I am making each column an array. The first column is time in $H:$M:$S
00:00:00
00:00:01
00:00:02
...
23:59:58
23:59:59

When I put this into an array, it makes an object array. I use this to convert it to datetime:
time1=np.array2string(time)
dt.datetime.strptime(time1, "%H:%M:%S")

However, I keep getting an error:
ValueError: time data "[b'00:00:00' b'00:01:00' b'00:02:00' ... b'23:57:00' b'23:58:00'\n b'23:59:00']" does not match format '%H:%M:%S'

When I look at the actual array, it indeed does have that phantom 'b', but there is no 'b' in my dataset. It generates it out of thin air. What is causing this?
UPDATE:
I tried
time1=np.array2string(time)
time_strings = [dt.datetime.strptime(t, "%H:%M:%S") for t in time1]

and received the error:
ValueError: time data '[' does not match format '%H:%M:%S'

Not sure why a bracket is in there. It still appears to be making a 'b'.

A: your input seems to be an array of byte objects. you'll need to decode the bytes to string before you can parse them with strptime.
example:
from datetime import datetime
import numpy as np

time = np.array([b'00:00:00', b'00:00:01', b'00:00:02'])

dt_list = [datetime.strptime(t.decode(encoding='utf-8'), "%H:%M:%S") for t in time]

# dt_list
# [datetime.datetime(1900, 1, 1, 0, 0),
#  datetime.datetime(1900, 1, 1, 0, 0, 1),
#  datetime.datetime(1900, 1, 1, 0, 0, 2)]

note: 'utf-8' is the default, adjust if you have a different encoding.


text:
Q: Pass session variable from one ear to another ear Actually i have deployed two ears test.ear and test1.ear on jboss 5.x server.
test.ear contains index.jsp page in this jsp i have set a session variable like :
session.setAttribute("Initiated","true")

From index.jsp i am forwarding control to action(struts2 action class) class present in test1.ear.
But when i am retrieving variable from action class,it is null
Map session = (Map)ActionContext.getContext().getSession();
String sessionExistence=(String)session.get("Initialted");

So How can i share session variable from jsp of test.ear to struts2 action class present in test1.ear.

A: You cannot have sharing session across different applications. The reason is simple, there will be conflicts in attribute names which might result in overriding values.
You can only send parameters along with the request while forwarding to another application.

A: If you want to share in-memory (or persistent too) information between several different applications consider using a Data Grid like Infinispan
See an Infinispan tutorial to get started. hope it helps.


text:
Q: Find the eigenvalues of a projection operator
A projection operator $P$ is defined as $P^2$=$P$. Use this definition to find the eigenvalues of this operator.

In this question is it necessary to define what the projection operator is? And won't the eigenvalue just be zero?

A: If $\mathbf x$ is an eigenvector of $P$ with eigenvalue $\lambda$, then $P(\mathbf x) = \lambda \mathbf x$.  If $P^2 = P(P) = P$, then $P(P(\mathbf x)) = P(\lambda \mathbf x) = \lambda^2 \mathbf x$, but this must also equal $\lambda \mathbf x$.  Therefore the eigenvalues of $P$ can only be members of your base field such that $\lambda^2 = \lambda$.
Assuming your base field is $\Bbb R$, there's one more value that satisfies this equation besides $\lambda =0$.  What is it?

A: Let $\lambda$ be an eigenvalue of $P$ for the eigenvector $v$. You have $\lambda^2 v = P^2 v = P v = \lambda v$. Because $v \neq 0$ it must be $\lambda^2 = \lambda$. The solutions of the last equation are $\lambda_1 = 0$ and $\lambda_2 = 1$. Those are the only possible eigenvalues the projection might have...

A: The eigenvalues are $0$  and $1$. Indeed, we know that for a projector $P$ defined on a vector space $E$, we have
$$ E= \ker P\oplus \operatorname{im}P=\ker P\oplus \ker(I-P) $$
$\ker P$  is the eigenspace associated with the eigenvalue $0$, $\ker(I- P) $  the eigenspace associated with the eigenvalue $1$. As $E$ is the direct sum of these eigenspaces, we have all eigenspaces, and all eigenvalues.

A: Geometrically, eigenvalues are the scaling factors by which particular vectors are scaled when multiplied by the respective matrix. Since the projection matrix projects a vector to its column space (or you can think of some nonzero subspace $W$), one such type of vector is the vector that is already living in that subspace. (Projecting a vector to its plane/subspace does not change it right?)
However, when doing so, the length doesn't change, so one eigenvalue must be $1$.
What about the vector that is perpendicular to $W$? Where will it go after the projection? Yes, it goes to the origin and hence the second eigenvalue must be $0$.
Although this approach does not prove anything, it gives a nice neat geometric intuition.


text:
Q: Validating int value I am having difficulties doing a simple validation of a text field that has as a value - an int variable.
I need the following;

*

*permit only digits

*don't allow a value of 0 or bellow

*It has to be mandatory to fill the field according to the rules above.

This is the validator I created, but it does not work as I desire. Can you have a look at it and tell me where I am making the mistake?
public void validateProductValue(FacesContext context,
            UIComponent validate, Object value) {
        FacesMessage msg = new FacesMessage("");
        String inputFromField = (String) value;
        String simpleTextPatternText = "^([0-9]+$)?";
        Pattern textPattern = null;
        Matcher productValueMatcher = null;
        textPattern = Pattern.compile(simpleTextPatternText);
        productValueMatcher = textPattern.matcher(inputFromField);

        if (!productValueMatcher.matches()) {
            msg = new FacesMessage("Only digits allowed");
            throw new ValidatorException(msg);
        }

        if (inputFromField.length() <= 0) {
            msg = new FacesMessage("You must enter a value greater than 0");
            throw new ValidatorException(msg);
        }

        if (Integer.parseInt(inputFromField.toString().trim()) <= 0) {
            msg = new FacesMessage("0 or bellow is not permited");
            throw new ValidatorException(msg);
        }
    }

This is how I call the field:
<h:inputText id="productValue" value="#{newOfferSupportController.productValue}" validator="#{newOfferSupportController.validateProductValue}"/>

This the validation shown in the browser:

Text
/newoffer.xhtml @44,184
validator="#{newOfferSupportController.validateProductValue}":
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

A: First of all your regex is wrong. You need to put $ at the end, like this ^([0-9]+)?$.
This doesn't work as you might expect:
if (inputFromField.length() <= 0) {
  msg = new FacesMessage("You must enter a value greater than 0");
  throw new ValidatorException(msg);
}

inputFormField.length() is the length of the text, which can't be less than 0 and even if it were greater than 0 you could enter a negative value, e.g. "-1" which has length 2.
If I see the exception correctly, you're getting a ClassCastException. Take a look at line 44 (which you are told by the exception message), which I guess is String inputFromField = (String) value; Did you define a converter for that field? If so value might be an Integer and not a String.
Edit:
Note that your validator actually tries to do two things: convert the input to an integer and validate the integer value. In JSF you normally have two classes that do this:

*

*first a converter is called in order to convert the string to an integer and the other way round, especially if your model field is an Integer - this is where you'd check if you actually got an integer

*second you validate the integer value, e.g. by enforcing a minimum - here you're using a validator

Also note that there are already built in validators, that do what you want. Take a look at <f:validateLongRange minimum = "0"/> for example.

A: You should be able to enforce the conditions your looking just using a regular expression:
    ^[1-9]+[0-9]*$

A: First, is value actually an instance of String? Or can it be cast to an Integer?
If not, do this:
if (value == null) {
   throw new ValidatorException("No input value");
}

String inputValue = (String) value;

try {
   int v = Integer.parse(inputValue);

   if (v <= 0) {
      throw new ValidatorException("Input less than or equal to 0");
   }

} catch (NumberFormatException e) {
   throw new ValidatorException("Input is not an integer");
}


text:
Q: Macro with optional parameter returning calculated length I'm trying to define a macro returning a calculated length, but making the parameter optional breaks the macro (error Missing number, treated as zero.):
\documentclass{article}

\usepackage{xfp}
\usepackage{numprint}

\newcommand{\testa}[1]{\fpeval{#1*0.03}\linewidth}
\newcommand{\testb}[1][1]{\fpeval{#1*0.03}\linewidth}

\begin{document}

\lenprint[pt]{\testa{1}}% prints 10,34958 pt

\lenprint[pt]{\testa{2}}% prints 20,69915 pt

\lenprint[pt]{\testb}% gives ERROR and prints 0.030 pt

\lenprint[pt]{\testb[2]}% gives ERROR and prints 0.060 pt

\end{document}

Can you help understand why?
Is there a way to make the parameter optional without breaking the working macro?
N.B. The above MWE uses \lenprint, but I'm asking for a solution working in general or at least with \addtolength, since my real world need is to use the macro as argument of \addtolength.

A: You can define \testb as expandable macro. For example:
\long\def\testb#1{\ifx[#1\afterfi{\testbA[}\else\afterfi{\testbA[1]#1}\fi}
\def\testbA[#1]{\fpeval{#1*0.03}\linewidth}
\long\def\afterfi#1#2\fi{\fi#1}

It will not work in all cases but your case works:
\lenprint[pt]{\testb}% works

\lenprint[pt]{\testb[2]}% works


text:
Q: Automatically mount partition when needed Can anyone suggest a method of mounting a partition (e.g. an NFS share) when a user changes into the directory it is set to be mounted to, and not on the system startup?
So far I've been unable to propose such a method, aside from editing BASH built-in cd implementation and forcing an fstab/mtab check before the working directory is actually changed.

A: http://www.linux-consulting.com/Amd_AutoFS/autofs-3.html#ss3.1 <-- That's what you want to use.


text:
Q: Enable a directory with .htacces I have the following .htaccess config:
RewriteEngine on
RewriteBase /
RewriteRule ^model/([^/\.]+)/?$ /model/index.php?u=$1 [L,NC,QSA]
RewriteRule ^collections/([^/\.]+)/?$ /collections/index.php?c=$1 [L,NC,QSA]
RewriteRule ^general/([^/\.]+)/?$ /general/index.php?p=$1 [L,NC,QSA]
RewriteRule ^blog/([^/\.]+)/?$ /blog/index.php?e=$1 [L,NC,QSA]
RewriteRule ^blog/archive/ /blog/archive/index.php [L,NC,QSA]

What I need is just enable http://example.org/blog/archive/ url and now in such directory there is an index.php file.
The problem is that the above rule /blog/ take the action instead of the last one.
What should I do?

A: Change the order of your rules:
RewriteEngine on
RewriteBase /

RewriteRule ^model/([^/.]+)/?$ /model/index.php?u=$1 [L,NC,QSA]
RewriteRule ^collections/([^/.]+)/?$ /collections/index.php?c=$1 [L,NC,QSA]
RewriteRule ^general/([^/.]+)/?$ /general/index.php?p=$1 [L,NC,QSA]
RewriteRule ^blog/archive/ /blog/archive/index.php [L,NC,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^blog/([^/.]+)/?$ /blog/index.php?e=$1 [L,NC,QSA]

However if /blog/archive/ is a real directory then you don't even need any rewrite rule if you add this line on top of your .htaccess:
DirectoryIndex index.php

This will load index.php by default for any directory.


text:
Q: Calculating inverse matrices directly I'm trying to find the inverse matrix of
$$ \begin{bmatrix}
  3 & 4 \\
  6 & 2
 \end{bmatrix}$$
I set up the following equation:
$$
\begin{bmatrix}
  a & b \\
  c & d
 \end{bmatrix}
\,
\begin{bmatrix}
  3 & 4 \\
  6 & 2
 \end{bmatrix}
=
\begin{bmatrix}
  1 & 0 \\
  0 & 1
 \end{bmatrix}
$$
So
\begin{cases}
3a+6b = 1 \\[4px]
4a+2b = 0 \\[4px]
3c+6d = 1 \\[4px]
4c+2d = 0
\end{cases}
I solve $a,b,c,d$ and get
\begin{cases}
a = \dfrac{1}{-9} \\[4px]
b = \dfrac{4}{18} \\[4px]
c = \dfrac{1}{-9} \\[4px]
d = \dfrac{4}{18}
\end{cases}
But I get $c,d$ wrong. They are supposed to be
\begin{cases}
c = \dfrac{6}{18} \\[4px]
d = \dfrac{-3}{18}
\end{cases}
Why does my way not work?

A: It is $3c+6d=0$ and $4c+2d=1$.

A: You just switched $1$ with $0$ in the last two equations.
However, for $2\times2$ matrices there's a very simple method. Provided $ad-bc\ne0$, we have
$$
\begin{bmatrix} a & b \\ c & d\end{bmatrix}^{-1}=
\frac{1}{ad-bc}
\begin{bmatrix} d & -b \\ -c & a\end{bmatrix}
$$

Switch the diagonal elements and change the sign to the nondiagonal one, then divide by the determinant.

This can be verified by doing the multiplication.
In your case, $ad-bc=6-24=-18$, so
$$
\begin{bmatrix} 3 & 4 \\ 6 & 2 \end{bmatrix}^{-1}=
-\frac{1}{18}
\begin{bmatrix} 2 & -4 \\ -6 & 3\end{bmatrix}=
\begin{bmatrix}-1/9 & 2/9 \\ 1/3 & -1/6 \end{bmatrix}
$$
Important note. This cannot be extended to bigger matrices.


text:
Q: How to pass variable to SOAP Request. Variable contains a value read from xls using groovy script I have some set of data in xls for a SOAP webservice. Using Groovy script I can read the data and can print using variables. But how can I use this variable into Webservice XML.
I feel Property Transfer feature won't help me here as value are being picked from XLS
Currently I have tried:

*

*in Groovy line is :
def myTestCase = context.testCase;
myTestCase.setPropertyValue("web:StateCode", d[1]);

OR
testrunner.testcase.setPropertyValue("web:StateCode", d[1]);
AND In SOAP Request I have passed variable as:
<web:StatefCode>${d[1]}</web:StateCode>

A: There are multiple solutions to your problem. The easiest, which seems you are attempting, is to store the value in a test case property:
def data    // something from your Excel
testRunner.testCase.setPropertyValue('stateCode', data)

To use this in a subsequent request, use property expansion: ${TestCase#stateCode#}.


text:
Q: Difference between android automotive and android auto What´s the difference between android auto and android automotive?
https://www.android.com/intl/en_en/auto/
https://source.android.com/devices/automotive/

A: Android Auto is an application for smartphone integration. All the data is rendered on the smartphone and mirorrored on the head-unit of the vehicle. There is no possiblity to use Android Auto in the car without smartphones. Additionally Android Auto is not able to influence vehicle functions.
Android Automotive is an open source project by Google which runs native on the head-unit of the vehicle. It is the connected-car-platform of the vehicle like mercedes me connect in Mercedes Banz vehicles. With Android Automotive it is possible to contrll vehicle functions and remote services. No smartphone is needed. One of the first cars equipped with Android Automotive is the Polestar 2 launching in 2020. One big advantage of Android Automotive is that OEMs are able to adapt the design layout to the brand specific UI.

A: Android Auto is powered by a smartphone using an application. The application can be run on the phone, or by plugging the phone into an Android auto compatible head unit. The phone then "projects" an interface onto the cars head unit, giving access to maps/waze, phone calls, play music/compatible apps. It even has an OEM app segment, although most of the time that just takes the user out of android auto and back to the cars interface.
Android Automotive is instead run on a computer in the vehicle, and is a full android OS experience rather than an extension of the phone. Android Automotive can control HVAC and some other car systems depending on the implementation by the cars manufacturer. It doesn't require a smartphone to be plugged in, while still giving a similar experience to android auto.
https://arstechnica.com/cars/2017/05/android-automotive-hands-on-google-is-finally-ready-to-talk-about-its-car-os/

A: Android Automotive is a car system that cantain radio,audio,video and so on.
Android Auto:use the phone to connect the car displya with usb,then you can run the phone's apps onto he cars head unit.

A: Android Auto is an app that our smartphone can be operate by the headunit on the car. So, you just plug the USB cable to headunit then easily manage to open any app on your phone directly from the headunit screen.
Android Automotive is an app or maybe an operating system for car headunit system that can access or managing android application on the device. Like our phone on the headunit without owning the real smartphone.