text:
Q: Can NDSolve handle discontinuous data? Backslide introduced in 9.0, persisting through 11.0.1

It is possible to numerically solve a differential equation if not-smooth data are involved?
For example the following instruction return the error NDSolve::bvdisc:
NDSolve[{-u''[x] == UnitBox[(x - 0.5) 0.5/0.2], u[0] == 0,
  u'[1] == 0}, u, {x, 0, 1}]

NDSolve::bvdisc: NDSolve is not currently able to solve boundary value
  problems with discrete variables. >>

Here I suppose discrete variable means discontinuous functions but maybe the problem is completely different.
This error is reported in Mathematica 10, where the Finite Element Framework should be able to return weak, not classical, solutions and should be definitely able to deal with such a simple equation, but maybe we need to enable some option or methods.
Please note I know I can do
DSolve[{-u''[x] == UnitBox[(x - 0.5) 0.5/0.2], u[0] == 0,
  u'[1] == 0}, u, {x, 0, 1}]

but in more complex scenarios I cannot hope to get an analytical answer.

A: This is just an extended comment.
I'm not quite certain what's going on as we can easily implement a shooting method manually here.
(Shooting method, in short: parametrize in terms of u'[0] and very the parameter until u'[1] has the desired value.)
fun = ParametricNDSolveValue[{-u''[x] == UnitBox[(x - 0.5) 0.5/0.2], u[0] == 0, u'[0] == ud}, u, {x, 0, 1}, ud]

FindRoot[fun[ud]'[1], {ud, 1}]
(* {ud -> 0.4} *)

Plot[{UnitBox[(x - 0.5) 0.5/0.2], fun[0.4][x]}, {x, 0, 1}]

This gives the solution to you equation.

A: I've had difficulty before with UnitBox, although I've forgotten the exact context.  UnitStep usually works better.
sol = NDSolve[{-u''[x] == UnitStep[x - 0.3] - UnitStep[x - 0.7],
    u[0] == 0, u'[1] == 0}, u, {x, 0, 1}];

Plot[u[x] /. First[sol], {x, 0, 1}]

A: You can force NDSolve to use the finite element method:
uif = NDSolveValue[{-u''[x] == UnitBox[(x - 0.5) 0.5/0.2], u[0] == 0,
    u'[1] == 0}, u, {x, 0, 1},
   Method -> {"PDEDiscretization" -> "FiniteElement"}];

Possibly, this might be the default.
In any case if you compare to the analytical solution:
aif = DSolveValue[{Rationalize[-u''[x] == UnitBox[(x - 0.5) 0.5/0.2]],
    u[0] == 0, u'[1] == 0}, u, {x, 0, 1}];

The result looks good:
Plot[aif[x] - uif[x], {x, 0, 1}]

For a general case one should keep in mind, is that the quality of the solution will depend on the mesh having nodes or internal boundaries at the discontinuity. There is some documentation about this in the SolvingPDEwithFEM tutorial in the variable coefficients section and probably the mesh generation tutorial is also of interest.
Another option is to switch off "DiscontinuityProcessing"
NDSolve[{-u''[x] == UnitBox[(x - 0.5) 0.5/0.2], u[0] == 0,
  u'[1] == 0}, u, {x, 0, 1},
 Method -> {"DiscontinuityProcessing" -> False}]

to get the old behavior.


text:
Q: Can multiple PHP scripts run at the same time? I am building a turn-based multiplayer game with Flash and PHP.  Sometimes two users may call on the same PHP script at the same time.  This script is designed to write some information to the database.  But that script should not run if that information has already been written by another user, or else the game will break.  If PHP processes these scripts sequentially (similar to how MySQL queues up multiple queries), then only one script should run in total and everything should be fine.
However, I find that around 10% of the time, BOTH user's scripts are executed.  My theory is that the server sometimes receives both user requests to run the script at exactly the same time and they both run because neither detected that anything has been written to the database yet.  Is it possible that both scripts were executed at the same time?  If so, what are the possible solutions to this problem.

A: THis is indeed possible. You can try locking and unlocking tables at the beginning and end of your scripts.
Though this will slow down some requests, as they would have to first wait for the locked tables to be unlocked.

A: It doesnt matter, if it is PHP, C, Java what ever. At the same time can run max only as much processes, as you have CPUs (and cores). There can be running lets say 100 processes at the same time, if you have only 2 cores. Only 2 are running, rest is waiting.
Now it depends what you see under run. If you take it as active or if you take also waiting processes. Secondly, it depends on your system configuration, how many processes can wait and on your system specs.

A: Sounds, at first glance, like what keeps a 2nd instance of the script to roll just does not happen fast enough, 10% of the time... I understand that you already have some kind of a 'lock' like someone told you to add, which is great; as someone mentioned above, always put this lock FIRST THING in your script, if not even before calling the script (a.k.a in parent script). Same goes for competing functions / objects etc...
Just a note though, I was directed here by google and what i wanted to find out is if script B will run IN AN IFRAME (so in a 'different window' if you wish) if script A is not finished running; basically your title is a bit blurry. Thank you very much.
Fortunately enough we're in the same pants : I'm programing an Hearthstone-like card game using php (which I know, ain't suited for this at all, but I just like challenging tasks, (and okay, that's the only language i'm familiar with)). Basically I gotta keep multiple 'instants' or actions if you prefer from triggering while another set of global event/instant - instants - sub-instants is rolling. This includes NEVER calling a function that has an event into it into the same rolling snipet, EXCEPT if I roll a while on a $_SESSION variable with value y that only does sleep(1) (that happens in scritpt A); while $_SESSION["phase"] == "EndOfTurnEffects" and then continue to roll until $_SESSION["phase"] == "StandBy" (other player's turn), and I wish script B to mofity $_SESSION["phase"]. Basically if script B does not run before script A is done executing, I'm caught in an endless loop of the while statement...

A: That's very plausible that they do. Look into database transactions.
Briefly, database transactions are used to control concurrency between programs that access the database at the same time. You start a transaction, then execute multiple queries and finally commit the transaction. If two scripts overlap each other, one of them will fail.
Note that isolation levels can further give fine grained control of how much the two (or more) competing scripts may share. Typically all are allowed to ready from the database, but only one is allowed to write. So the error will happen at the final commit. This is fine as long as all side effects are happening in the database, but not sufficient if you have external side effects (Such as deleting a file or sending an email). In these cases you may want to lock a table or row for the duration of the transaction or set the isolation level.

A: Here is an example of SQL table locking that you can use so that the first PHP thread which grabs the DB first will lock the table (using lock name "awesome_lock_row") until it finally releases it. The second thread attempts to use the same table, and since the lock name is also "awesome_lock_row"), it keeps on waiting until the first PHP thread has unlocked the table.
For this example, you can try running the same script perhaps 100 times concurrently as a cron job and you should see "update_this_data" number field increment to 100. If the table hadn't been locked, all the concurrent 100 threads would probably first see "update_this_data" as 0 at the same time and the end result would have been just 1 instead of 100.
<?php
$db = new mysqli( 'host', 'username', 'password', 'dbname');

// Lock the table
$db->query( "DO GET_LOCK('awesome_lock_row', 30)" ); // Timeout 30 seconds

$result = $db->query( "SELECT * FROM table_name" );
if($result) {
    if ( $row = $result->fetch_object() )
        $output = $row;
    $result->close();
}

$update_id = $output->some_id;

$db->query( UPDATE table_name SET update_this_data=update_this_data+1 WHERE id={$update_id} );

// Unlock the table
$db->query( "DO RELEASE_LOCK('awesome_lock_row')" );
?>

Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azimuth greater than 360 in Veloview (Velodyne 32)? When I use Veloview, freezes at 1 of the frames and examine the data points, why are the azimuths greater than 360 degrees?

A: Per the HDL-32E manual, the rotational angle is given by a two byte integer value ranging between 0 and 35999.  Dividing that value by 100 gives you the degrees. What you see in the azimuth column is the raw integer value returned.
For example the first row entry would have an azimuth value of 143.89°.


text:
Q: Fixing ugly connections in circuitikz's logic circuit I have a circuitikz simple logic circuit. While connections are technically ok, the result is very ugly. How can I improve it?
MWE:
\documentclass[a4paper,12pt]{article}
\usepackage{circuitikz}
\begin{document}
            \begin{circuitikz}
                \ctikzset{logic ports=ieee}
                \draw

                % Inputs
                (-2,2) node[left=1](X1) {$X_1$}
                (-2,1) node[left=1](X2) {$X_2$}
                (-2,0) node[left=1](X2) {$X_3$}

                % Upper OR
                (3,2) node[or port](myor1) {}
                (myor1.out) node [anchor=south west] {$x_1+x_2$}

                % NOT
                (0,0) node[not port](mynot1) {}
                (mynot1.out) node [left=10, anchor=north west] {$\overline{x_3}$}

                % Bottom OR
                (2,0) node[or port,anchor=in 2] (myor2) {}
                (myor2.out) node [anchor=north west] {$x_1 + \overline{x_3}$}

                % AND
                (5,1) node[and port,anchor=in 2] (myand1) {}
                (myand1.out) node[anchor=west] {$U$}

                % Input links
                (-2,0) -| (mynot1.in)
                (-2,1) -| (myor1.in 2)
                (-2,2) -| (myor1.in 1) to[short,*-] (myor2.in 1)

                % Other links
                (mynot1.out) -| (myor2.in 2)
                (myor2.out) -| (myand1.in 2)
                (myor1.out) -| (myand1.in 1);
            \end{circuitikz}
        \end{document}

Result:

A: Well there is a very simple fix but not sure that's something you would want:
\documentclass{standalone}

\usepackage{circuitikz}

\begin{document}
\begin{circuitikz}
    \ctikzset{logic ports=ieee}
    \draw

    % Inputs
    (-2,2) node[left=1](X1) {$X_1$}
    (-2,1) node[left=1](X2) {$X_2$}
    (-2,0) node[left=1](X2) {$X_3$}

    % Upper OR
    (3,2) node[or port](myor1) {}
    (myor1.out) node [anchor=south west] {$x_1+x_2$}

    % NOT
    (0,0) node[not port](mynot1) {}
    (mynot1.out) node [left=10, anchor=north west] {$\overline{x_3}$}

    % Bottom OR
    (2,0) node[or port,anchor=in 2] (myor2) {}
    (myor2.out) node [anchor=north west] {$x_1 + \overline{x_3}$}

    % AND
    (5,1) node[and port,anchor=in 2] (myand1) {}
    (myand1.out) node[anchor=west] {$U$}

    % Input links
    (-2,0) -| (mynot1.in)
    (-2,1) -| (myor1.in 2)
    (-2,2) -| (myor1.in 1) to[short,*-] (myor1.in 1 |- myor2.in 1) to (myor2.in 1)

    % Other links
    (mynot1.out) -| (myor2.in 2)
    (myor2.out) -| (myand1.in 2)
    (myor1.out) -| (myand1.in 1);
\end{circuitikz}
\end{document}

And the output:

As you can see, "what input goes where" is not really readable.
So to solve this, I branch earlier:
\documentclass{standalone}

\usepackage{circuitikz}

\begin{document}
\begin{circuitikz}
    \ctikzset{logic ports=ieee}
    \draw

    % Inputs
    (-2,2) node[left=1](X1) {$X_1$}
    (-2,1) node[left=1](X2) {$X_2$}
    (-2,0) node[left=1](X2) {$X_3$}

    % Upper OR
    (3,2) node[or port](myor1) {}
    (myor1.out) node [anchor=south west] {$x_1+x_2$}

    % NOT
    (0,0) node[not port](mynot1) {}
    (mynot1.out) node [left=10, anchor=north west] {$\overline{x_3}$}

    % Bottom OR
    (2,0) node[or port,anchor=in 2] (myor2) {}
    (myor2.out) node [anchor=north west] {$x_1 + \overline{x_3}$}

    % AND
    (5,1) node[and port,anchor=in 2] (myand1) {}
    (myand1.out) node[anchor=west] {$U$}

    % Input links
    (-2,0) -| (mynot1.in)
    (-2,1) -| (myor1.in 2)
    (-2,2) -| (myor1.in 1)
    (1.5,2) to[short,*-] (1.5,2 |- myor2.in 1) to (myor2.in 1)

    % Other links
    (mynot1.out) -| (myor2.in 2)
    (myor2.out) -| (myand1.in 2)
    (myor1.out) -| (myand1.in 1);
\end{circuitikz}
\end{document}

And the result:

A: This is in the main point similar to @Archange's answer, it moves the starting point of your connection a bit to the left and then uses |-, but I also would advice you to use relative positioning as much as possible. This ensures easier modifications down the road and much better reusability.
The following uses only one fixed coordinate (0,0) and places everything else relatively to that.
\documentclass[a4paper,12pt]{article}
\usepackage{circuitikz}
\begin{document}
\begin{circuitikz}
  \ctikzset{logic ports=ieee}
  \draw
    % Inputs
    (0,0) node[left=1](X1) {$x_1$}
    ++(0,-1) node[left=1](X2) {$x_2$}
    ++(0,-1) node[left=1](X3) {$x_3$}

    % NOT
    (X3)++(1,0) node[not port,anchor=in](mynot1) {}
    (mynot1.out) node [left=10, anchor=north west] {$\overline{x_3}$}

    % Bottom OR
    (mynot1.out)++(1,0) node[or port,anchor=in 2] (myor2) {}
    (myor2.out) node [anchor=north west] {$x_1 + \overline{x_3}$}

    % Upper OR
    (X1-|myor2.in 1) node[or port, anchor=in 1](myor1) {}
    (myor1.out) node [anchor=south west] {$x_1+x_2$}
    ;
  % this finds the center between the two points, you could also do this using
  % the calc library instead
  \path(myor1.out)--coordinate(tmp)(myor2.out);
  \draw
    % AND
    (tmp)++(1,0)node[and port, anchor=west] (myand1){}
    (myand1.out) node[anchor=west] {$U$}

    % Input links
    (X3) -- (mynot1.in)
    (X2) -| (myor1.in 2)
    (X1) -- (myor1.in 1)
    ++(-.5,0) node[circ]{} |- (myor2.in 1)

    % Other links
    (mynot1.out) -| (myor2.in 2)
    (myor2.out) -| (myand1.in 2)
    (myor1.out) -| (myand1.in 1);
\end{circuitikz}
\end{document}

A: I usually draw the gates first and then draw the inputs last. I changed the order of inputs (I don't know if this is allowed). See the circuit below.

\documentclass[border=3mm]{standalone}
\usepackage{circuitikz}
\begin{document}
            \begin{circuitikz}
                \ctikzset{logic ports=ieee}
                \draw

                % Upper OR
                (3,2) node[or port](myor1) {}
                (myor1.out) node [anchor=south west] {$x_1+x_2$}

                % Bottom OR
                (3,0) node[or port] (myor2) {}
                (myor2.out) node [anchor=north west] {$x_1 + \overline{x_3}$}

                % AND
                (6,1) node[and port] (myand1) {}
                (myand1.out) node[anchor=west] {$U$}

                % NOT
                (myor2.in 2) ++(-3,0) node[not port,anchor=in](mynot1) {}
                (mynot1.out) node [anchor=north west] {$\overline{x_3}$}

                % Input links
                (myor1.in 1) -- ++(-4,0)node[left]{$x_2$}
                (myor1.in 2) -- (myor2.in 1) node[midway](j1){}
                (j1.center) to[short,*-] ++(-4,0)node[left]{$x_1$}
                (mynot1.in 1) -- ++(-1,0)node[left]{$x_3$}

                % Other links
                (mynot1.out) -- (myor2.in 2)
                (myor2.out) -| (myand1.in 2)
                (myor1.out) -| (myand1.in 1);
            \end{circuitikz}
        \end{document}


text:
Q: How to integrate AdminLTE into Yii2 Basic in manual way You know, yii2 with adminlte is exist in this git .
But if I use this using composer, it not gives me an educate.
You know, I want to learn step by step.
So I tried like this:

*

*I download adminlte in his official.

*In this zip file, I have one folder with name : "AdminLTE: 2.*"

*Then I Extract all the item in folder AdminLTE:2.* into vendor/bower/adminLTE/"bunch of file"

Now, I edit assets/AppAsset like this:
class AppAsset extends AssetBundle {
   public $basePath = '@webroot';
   public $baseUrl = '@web';
   public $sourcePath = '@bower/'adminLTE';

   public $css = [
    'adminLTE/dist/css/AdminLTE.min.css',
    'css/site.css',
   ];

public $js = [
       'adminLTE/dist/js/app.js'
];
public $depends = [
    'yii\web\YiiAsset',
    'yii\bootstrap\BootstrapAsset',
    'yii\bootstrap\BootstrapPluginAsset',
];

}

But, both css and js below is 404 ?
Any help it so appreciated

A: If you want to manually add AdminLTE there is no need to put it in the bower folder.
Place it in the /web folder (in case of Advanced Template it's /frontend/web or /backend/web).
You have got AppAsset already set for this folder but you have to remove $sourcePath because when this is set $basePath and $baseUrl are overriden.

A: Do not add theme inside the vendor for manual installation of theme. Follow below mentioned steps.
Step 1 : Download your adminlte and create a directory named theme inside a root
       ex. your_project/basic/themes ( i.e outside the web directory)

Step 2 : paste your adminlte theme folder inside newly created theme directory
Step 3 : Now you need to create asset to register all the csss and js required for adminlte theme
go to your_project/basic/assets directory and create a new file lets say, AdminLTEAsset.php

namespace app\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AdminLTEAsset extends AssetBundle {

    public $sourcePath = '@app/themes/adminlte/';
    public $css = [
        'dist/css/AdminLTE.css',
        'font-awesome-4.5.0/css/font-awesome.min.css',
        'ionicons/2.0.1/css/ionicons.min.css',
        'dist/css/skins/_all-skins.min.css',
        ];
    public $js = [
        'dist/js/app.js',
        'plugins/slimScroll/jquery.slimscroll.min.js',
        'plugins/fastclick/fastclick.min.js',
        'dist/js/demo.js',
        ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
        'yii\bootstrap\BootstrapPluginAsset',
    ];
}

Step 4: Now go to the themes/adminlte/layouts/main.php and register your newly created AdminLTEAsset. as follows.
$assets = app\assets\AdminLTEAsset::register($this);
$basUrl = $assets->baseUrl;

Step 5 : in your /config/web.php file add the following pathmap
'components'=>[
 'view' => [
            'theme' => [
                'pathMap' => ['@app/views' => '@app/themes/adminlte'],
                'baseUrl' => '@web/../themes/adminlte',
            ],
        ],
]

A: Embeding admin lte theme i yii2 basic
1) create yii project using composer
sudo du
cd /var/www/html
composer create-project yiisoft/yii2-app-basic basic 2.0.4
2)now create it accessible
chmod 777 -R project name
3) download admin lte theme by using
git clone https://github.com/bmsrox/baseapp-yii2basic-adminlte.git
4) now update composer
composer update
if token error then  create account in git and create token in setting tab by clicking genarate new token
copy and provide it to composer
5) update your web.php file in config
<?php

$params = require(__DIR__ . '/params.php');

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'layout'=>'column2',
    'layoutPath'=>'@app/themes/adminLTE/layouts',
    'components' => [

     'urlManager' => [
            'class' => 'yii\web\UrlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                ''=>'site/index',
                '<action:(index|login|logout)>'=>'site/<action>',
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>'
            ],
        ],

         'view' => [
            'theme' => [
                'pathMap' => ['@app/views' => '@app/themes/adminLTE'],
                'baseUrl' => '@web/../themes/adminLTE',
            ],
        ],

        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'n0VkMX1RmIa_ovJmwR3Gn_hdZyQ7SyKe',
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => require(__DIR__ . '/db.php'),
    ],
    'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = 'yii\debug\Module';

    $config['bootstrap'][] = 'gii';
    //$config['modules']['gii'] = 'yii\gii\Module';
    $config['modules']['gii'] = [
            'class' => 'yii\gii\Module',
            'generators' => [ //here
                'crud' => [ // generator name
                    'class' => 'yii\gii\generators\crud\Generator', // generator class
                    'templates' => [ //setting for out templates
                        'custom' => '@vendor/bmsrox/yii-adminlte-crud-template', // template name => path to template
                    ]
                ]
            ],
        ];
}

return $config;

6) update SiteController. Php in controller folder
replace actionLogout with following code
public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->redirect(Yii::$app->user->loginUrl);
    }

    public function beforeAction($action)
    {
        if (parent::beforeAction($action)) {
            // change layout for error action
            if ($action->id=='login')
                 $this->layout = 'login';
            return true;
        } else {
            return false;
        }
    }

7) if misconfiguration error then
update apche2
by using command
a2enmod rewrite
and restrart apache using
service apache2 restart
finished...........
best of luck


text:
Q: Python threading vs. multiprocessing in Linux Based on this question I assumed that creating new process should be almost as fast as creating new thread in Linux. However, little test showed very different result. Here's my code:
from multiprocessing import Process, Pool
from threading import Thread

times = 1000

def inc(a):
    b = 1
    return a + b

def processes():
    for i in xrange(times):
        p = Process(target=inc, args=(i, ))
        p.start()
        p.join()

def threads():
    for i in xrange(times):
        t = Thread(target=inc, args=(i, ))
        t.start()
        t.join()

Tests:
>>> timeit processes()
1 loops, best of 3: 3.8 s per loop

>>> timeit threads()
10 loops, best of 3: 98.6 ms per loop

So, processes are almost 40 times slower to create! Why does it happen? Is it specific to Python or these libraries? Or did I just misinterpreted the answer above?

UPD 1. To make it more clear. I understand that this piece of code doesn't actually introduce any concurrency. The goal here is to test the time needed to create a process and a thread. To use real concurrency with Python one can use something like this:
def pools():
    pool = Pool(10)
    pool.map(inc, xrange(times))

which really runs much faster than threaded version.

UPD 2. I have added version with os.fork():
for i in xrange(times):
    child_pid = os.fork()
    if child_pid:
        os.waitpid(child_pid, 0)
    else:
        exit(-1)

Results are:
$ time python test_fork.py

real    0m3.919s
user    0m0.040s
sys     0m0.208s

$ time python test_multiprocessing.py

real    0m1.088s
user    0m0.128s
sys     0m0.292s

$ time python test_threadings.py

real    0m0.134s
user    0m0.112s
sys     0m0.048s

A: The question you linked to is comparing the cost of just calling fork(2) vs. pthread_create(3), whereas your code does quite a bit more, e.g. using join() to wait for the processes/threads to terminate.
If, as you say...

The goal here is to test the time needed to create a process and a thread.

...then you shouldn't be waiting for them to complete. You should be using test programs more like these...
fork.py
import os
import time

def main():
    for i in range(100):
        pid = os.fork()
        if pid:
            #print 'created new process %d' % pid
            continue
        else:
            time.sleep(1)
            return

if __name__ == '__main__':
    main()

thread.py
import thread
import time

def dummy():
    time.sleep(1)

def main():
    for i in range(100):
        tid = thread.start_new_thread(dummy, ())
        #print 'created new thread %d' % tid

if __name__ == '__main__':
    main()

...which give the following results...
$ time python fork.py
real    0m0.035s
user    0m0.008s
sys     0m0.024s

$ time python thread.py
real    0m0.032s
user    0m0.012s
sys     0m0.024s

...so there's not much difference in the creation time of threads and processes.

A: Yes, it is true. Starting a new process (called a heavyweight process) is costly.
As an overview ...
The OS has to (in the linux case) fork the first process, set up the accounting for the new process, set up the new stack, do the context switch, copy any memory that gets changed, and tear all that down when the new process returns.
The thread just allocates a new stack and thread structure, does the context switch, and returns when the work is done.
... that's why we use threads.

A: In my experience there is a significant difference between creating a thread (with pthread_create) and forking a process.
For example I created a C test similar to your python test with thread code like this:
pthread_t thread;
pthread_create(&thread, NULL, &test, NULL);
void *res;
pthread_join(thread, &res);

and process forking code like this:
pid_t pid = fork();
if (!pid) {
  test(NULL);
  exit(0);
}
int res;
waitpid(pid, &res, 0);

On my system the forking code took about 8 times as long to execute.
However, it's worth noting that the python implementation is even slower - for me it was about 16 times as slow. I suspect that is because in addition to the regular overhead of creating a new process, there is also more python overhead associated with the new process too.


text:
Q: make asymmetric pairwise comparisons in a matrix I have a matrix with pairwise values but no symmetric, I mean, AxB is not the same as BxA. Here is a dummy example:
    A    B    C    D    E
A    1  0.7  0.8  0.8  0.9
B  0.2    1  0.2  0.8  0.3
C  0.3  0.4    1  0.5  0.6
D  0.4  0.9  0.8    1  0.4
E  0.8  0.2  0.8  0.8    1

I need to know how many [i,j] comparisons are higher or equal than 0.7 and how many comparisons [j,i] are also higher than 0.7 in order to remove high redundant elements. In the example, element A has a higher number of elements with B, C, D, and E and it should be removed in further analysis. I've thought in using table command for this
table1 <- apply(M, 1, table)
table2 <- apply(M, 2, table)

And then compare table1 with table2 for removing the redundant elements, does it would be a good approach?
Thanks

A: What do you want to do with the entries > 0.7? Set them to NA? Remove them? Regardless, this should get you going in the right direction:
#Assumes your data is named x
> which(x > 0.7, arr.ind = TRUE)
#----
  row col
A   1   1
E   5   1
B   2   2
D   4   2
...

#Set values = NA
x[which(x>0.7, arr.ind = TRUE)] <- NA
#---
    A   B   C   D   E
A  NA 0.7  NA  NA  NA
B 0.2  NA 0.2  NA 0.3
C 0.3 0.4  NA 0.5 0.6
D 0.4  NA  NA  NA 0.4
E  NA 0.2  NA  NA  NA


text:
Q: Bootstrap4 table - set constant height for rows I am trying to create a Bootstrap v4 table which has both a fixed column width and a fixed row height.
Any data within the cells which is too long should be truncated (either just not shown or if possible use something like text-truncate)
I have tried multiple things from previous posts but cannot seem to get it working.
Below is a snippet of the table with a fixed width but without the set height and an example of what it is I am trying to do.

$('#table').bootstrapTable({
  data: [{
      1: '1',
      2: '2',
      3: '3',
      4: '4',
      5: '5'
    },

    {
      1: '6',
      2: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
      3: '8',
      4: '9',
      5: '10'
    }

  ]
})
.set-width {
  min-width: 300px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/spacelab/bootstrap.min.css">
<link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.20.0/dist/bootstrap-table.min.css">

          Heading 1

          Heading 2

          Heading 3

          Heading 4

          Heading 5

A: The table will grow by default, you need a div inside the cell, and apply the CSS to this div.

$('#table').bootstrapTable({
data: [{
1: '1',
2: '2',
3: '3',
4: '4',
5: '5'
},

{
1: '6',
2: '
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
',
3: '8',
4: '9',
5: '10'
}

]
})
.set-width {
min-width: 300px;
}
.set-height {
max-height: 30px;
overflow: hidden;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/spacelab/bootstrap.min.css">
<link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.20.0/dist/bootstrap-table.min.css">

            Heading 1

            Heading 2

            Heading 3

            Heading 4

            Heading 5


text:
Q: Counting specify value across columns in r I have a table that looks something like this:
v1    v2    v3
pos   neg    pos
pos   pos    pos
neg   neg    neg

I want to create another column which has the winner between other three columns
v1    v2    v3    v4
pos   neg   pos   pos
pos   pos   pos   pos
neg   neg   neg   neg

A: As "winner" means the majority, the following will work:
df$v4 <- ifelse(rowMeans(df == "neg") > 0.5, "neg", "pos")

df$v4
[1] "pos" "pos" "neg"

This uses rowMeans to calculate the proportion of elements in each row that are "neg". This result is fed to ifelse where if the proportion is greater than 0.5 in a row, then "neg" is returned, otherwise, "pos" is returned.
Note that the columns must be character. That's why I use the as.is = TRUE argument below.
data
df <- read.table(header = TRUE, text = "v1    v2    v3
pos   neg    pos
pos   pos    pos
neg   neg    neg", as.is = TRUE)

A: Another possibility:
mydf$v4 <- apply(mydf, 1, function(x) names(which.max(table(x))))

which gives:
> mydf
   v1  v2  v3  v4
1 pos neg pos pos
2 pos pos pos pos
3 neg neg neg neg


text:
Q: How to pass a rotated image within an ImageView to another activity? In my app, I'm rotating an image on a button click. Now when I pass the image to another activity, I don't want to loose the image's rotation angle.
This is how I rotate the image.
In onclick of button 'rotate'
btn_rotate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            rotateImage(true);
        }

    });

public void rotateImage(boolean rotate) {
    RotateAnimation animation = null;
    if (rotate) {
        animation = new RotateAnimation(rotation, rotation + 90,
        picview.getWidth() / 2, picview.getHeight() / 2);
        rotation += 90;
        rotation %= 360;
    } else {
        animation = new RotateAnimation(0, rotation,
        picview.getWidth() / 2, picview.getHeight() / 2);

    }
    animation.setDuration(0);
    animation.setFillAfter(true);
    animation.setInterpolator(new LinearInterpolator());
    picview.startAnimation(animation);

}

I pass the rotation angle as:
send_image.putExtra("rotation_angle", rotation);

But in the receiving activity how do I apply the rotation_angle on the Image? Can someone please guide me.
Thanks.

A: As a best practices do not pass the bitmap from the intent as it is heavy object.
Instead you can have few options like
 1. In your application class with get and set bitmap
 2. Save rotated bitmap into Sdcard in one activity and retrieve that in other activity

Hope it helps


text:
Q: Am I inputting the correct data for randomisation tests for my single-case design in R? I'm currently doing randomisation tests (RTs) for a single-case design in R. A bit of context about my phases:
I am doing an AB design, which was staggered using a multiple baseline design across 5 participants.
Here is my phase layout over 9 weeks, with 7 data points per week: AA/BBBBBB
A = baseline; B = intervention; / = changeover phase with 7 possible start points
I have figured out how to calculate the randomisation test for all participants as a whole, but I'm struggling to do the randomisation test for each individual participant, as it asks for minimum phase length as opposed to the possible start points in a .txt file.
After Monte Carlo, I'm doing 1,000 randomisation distributions. For the RTs, I'm using the following code in R, based on a minimum of 14 baseline data points and a minimum of 42 intervention data points:
pvalue.random(design="AB", statistic="B-A", number=1000, limit=14)

For these calculations, R asks for the min number of data points for each phase (limit). Technically, the min number of data points for phase B is 42. However, as the transition phase is only 7 days, this means there's no time to have a 42-day baseline. So I've put the minimum phase length at 14 days to reflect the 2-week baseline. Is this right?


text:
Q: Visual Studio SQL Server database "copy if newer" still replaces database each time I'm pretty new to C# and SQL Server and I am working on an example for school using simple databases in Visual Studio 2019. I've connected to an external .MDF database file provided for the project and it's copied into my project folder (I've opted to place a copy of the database in the project folder).
Upon running my application, I make some changes to the data and save. Then on re-running the application, the data is the original data, without my previous changes. I've confirmed the save within the application works as the timestamp on the .mdf file in the debug folder is updated. However when I rerun, the .mdf file in the project folder is again copied to the debug folder.
I have set the "copy to output directory" property to copy always, copy if newer, and never copy, all with the same results. I assumed copy if newer would be the best option.
Any suggestions? For reference, the example is from "Starting out with Visual C#" 5th Edition by Tony Gaddis, chapter 12, tutorial 12-3. The tutorial doesn't mention the "copy to output directory" property and I'm not finding a resolution on other forums.

A: I found the reason I was running into this problem. I had erroneously changed the "copy to output directory" to "copy if newer" for the dataset (.xsd in solution explorer) rather than the database itself (.mdf in solution explorer).
Wanted to post in case other newbies ran into this issue.


text:
Q: Importing .class File Into Eclipse Project I have a single compiled .class file called "Searcher" that I downloaded from my computer, and now I would like to import it into an Eclipse project.  Here is what I have done so far.
1) Saved the .class file in an empty folder on my desktop
2) Created an empty eclipse project, right clicked the project and selected properties.
3) In the properties window I selected build path and clicked add external class folder
4) I added the folder with my .class file inside to the build path under "libraries"
5) In src I created a class with a main method.  I tried to instantiate the searcher class by entering
Searcher s = new Searcher();

6) When I hovered over the error message, I was told to "import Searcher", so the program obviously recognized the class.
7) After clicking import, an import declaration appeared at the top of my class,
"import searcher.Search;"
8) Search is the name of the folder, and searcher is the name of my class. Unfortunately, with that import declaration, I am still getting an error before I run the program.
In short, what do I need to do to use the functionality of the searcher class, and other classes In the future?  What should I do to fix my way of importing this class into Eclipse?  Thank you.


text:
Q: Parse Array inside of an JSON Object with C# I'm trying to parse an array inside of a json Object but it's not working, here is the code:
public void JsonParserPersonal(string file)
        {
            string fullname;
            string email;

            var json = System.IO.File.ReadAllText(file);
            var objects = JObject.Parse(json);
            var arrays = JArray.FromObject(json);

            fullname = (string)objects["NameComponents"]["FullName"];
            email = (string)arrays["EmailAddresses"]["ItemValue"];
            SearchReplacePersonal(fullname, email);
        }

Here is the JSON data:
{
    "NameComponents": {
        "FullName": "XXX"
    },
    "EmailAddresses": [
        {
            "IsPersonal": true,
            "IsBusiness": false,
            "FieldName": "Email1Address",
            "DisplayTitle": "Email",
            "ItemValue": "xxx@yyy.com"
        }
    ]
}

All I want is to get the "ItemValue" inside of "EmailAddresses".
When I run this code, this is the error I get:
System.ArgumentException: 'Object serialized to String. JArray instance expected.'
I'm using Visual Studio 2019.
Thanks!

A: When accessing JArray, you should specify the index
var objects = JObject.Parse(json);
var jarray = objects["EmailAddresses"];

Console.WriteLine((string)objects["NameComponents"]["FullName"]);
Console.WriteLine((string)jarray[0]["ItemValue"]);

Or iterate JArray
foreach(var item in jarray)
{
    foreach(JProperty property in item.Children())
    {
        Console.WriteLine($"{property.Name} - {property.Value}");
    }
}


text:
Q: Spark Web UI, shows non-zero Memory Storage numbers even if I don't persist data My spark application shows non-zero amounts in the Memory Storage even if I don't use persist or cache. Does spark cache my data even if I don't use persist/cache ?

A: It is possible that Spark optimization is attempting to "broadcast" your smaller datasets to each worker to save on network usage.
Quoted from Scaladocs

A broadcast variable. Broadcast variables allow the programmer to keep
  a read-only variable cached on each machine rather than shipping a
  copy of it with tasks. They can be used, for example, to give every
  node a copy of a large input dataset in an efficient manner. Spark
  also attempts to distribute broadcast variables using efficient broadcast algorithms to reduce communication cost.

Also, in memory shuffling will cost you RAM.
Quoted from Medium

Internally, results from individual map tasks are kept in memory until
  they can't fit. Then, these are sorted based on the target partition
  and written to a single file. On the reduce side, tasks read the
  relevant sorted blocks.


text:
Q: Installing Fedora: does it matter what I make the hostname? I'm in the process of setting up a Fedora machine just for use on my in-house lan (not exposed to the internet.)
This seems like a slightly stupid question, but I can't seem to find a definitive answer anywhere: does it matter what I make the hostname?
The default is "localhost.localdomain" - should I leave that, change it to something meaningful, or just set it to something like "fedoramachine" or "bilbo"?

A: It helps to set some name.
But, from a networking standpoint, the name does not matter.
Some other notes that might be useful.


text:
Q: How to fix skew trapezoidal distribution sampling output sample size I am trying to generate a skewed trapezoidal distribution using inverse transform sampling.
The inputs are the values where the ramps start and end (a, b, c, d) and the sample size.
a=-3;b=-1;c=1;d=8;
SampleSize=10e4;
h=2/(d+c-a-b);

Then I calculate the ratio of the length of ramps and flat components to get sample size for each:
firstramp=round(((b-a)/(d-a)),3);
flat=round((c-b)/(d-a),3);
secondramp=round((d-c)/(d-a),3);
n1=firstramp*SampleSize; %sample size for first ramp
n3=secondramp*SampleSize; %sample size for second ramp
n2=flat*SampleSize;

And then finally I get the histogram from the following code:
quartile1=h/2*(b-a);
quartile2=1-h/2*(d-c);

y1=linspace(0,quartile1,n1);
y2=linspace(quartile1,quartile2,n2);
y3=linspace(quartile2,1,n3);

%inverse cumulative distribution functions
invcdf1=a+sqrt(2*(b-a)/h)*sqrt(y1);
invcdf2=(a+b)/2+y2/h;
invcdf3=d-sqrt(2*(d-c)/h)*sqrt(1-y3);

distr=[invcdf1 invcdf2 invcdf3];

histogram(distr,100)

However the sampling of ramps and flat components are not equal, looks like this:

I fixed this by trial and error, by reducing the sample size of the ramps by half:
n1=0.5*firstramp*SampleSize; %sample size for first ramp
n3=0.5*secondramp*SampleSize; %sample size for second ramp
n2=flat*SampleSize;

This made the distribution look like this:

However this makes the output sample less than what is given in input.
I've also tried different combinations of changing the sample sizes of ramps and flat.
This also works:
n1=0.75*firstramp*SampleSize; %sample size for first ramp
n3=0.75*secondramp*SampleSize; %sample size for second ramp
n2=1.5*flat*SampleSize;

It increases the output samples, but it's still not close.
Any help will be appreciated.
Full code:
a=-3;b=-1;c=1;d=8;
SampleSize=10e4;%*1.33333333333333;
h=2/(d+c-a-b);
firstramp=round(((b-a)/(d-a)),3);
flat=round((c-b)/(d-a),3);
secondramp=round((d-c)/(d-a),3);

n1=firstramp*SampleSize; %sample size for first ramp
n3=secondramp*SampleSize; %sample size for second ramp
n2=flat*SampleSize;

quartile1=h/2*(b-a);
quartile2=1-h/2*(d-c);

y1=linspace(0,quartile1,.75*n1);
y2=linspace(quartile1,quartile2,1.5*n2);
y3=linspace(quartile2,1,.75*n3);

%inverse cumulative distribution functions
invcdf1=a+sqrt(2*(b-a)/h)*sqrt(y1);
invcdf2=(a+b)/2+y2/h;
invcdf3=d-sqrt(2*(d-c)/h)*sqrt(1-y3);

distr=[invcdf1 invcdf2 invcdf3];

histogram(distr,100)
%end

A: I don't know Matlab so I was hoping somebody else would jump in on this, but since nobody did here goes.
If I'm reading your code correctly what you did is not an inversion.  Inversion is 1-1, i.e., one uniform input produces one outcome.  You seem to be using a technique known as the "composition method".  In composition the overall distribution is comprised of component pieces, each of which is straightforward to generate.  You choose which component to generate from based on their proportions/probabilities relative to the whole.  For density functions, probability is found as the area under the density curve, so your first mistake was in sampling the components relative to the width of each component rather than using their areas.  The correct sampling proportions are 2/13, 4/13, and 7/13 for what you designated the firstramp, flat, and secondramp components, respectively. A second mistake (which is relatively minor) was to assign exact sample sizes to each of the components.  Having probability 2/13 does not mean that exactly 2*SampleSize/13 of your samples will be from the firstramp, it means that's the expected sample size for that component.  The expected value of a random variate is not necessarily (or even likely to be) the outcome you will actually get.
In pseudocode, the composition approach would be
generate U ~ Uniform(0,1)
if U <= 2/13:
   generate and return a value from firstramp
else if U <= 6/13:
   generate and return a value from flat
else:
   generate and return a value from secondramp

Note that since each of the generate options will use one or more uniforms, and choosing between the options requires a uniform U, this is not an inversion.
If you want an actual inversion, you need to quantify your density, integrate it to get the cumulative distribution function, then apply the inversion technique by setting F(X) = U and solving for X.  Since your distribution is made of distinct components, both the density and cumulative density will be piecewise functions.
After deriving the height based on the requirement that the areas of the two triangles and the flat section must add up to 1, I came up with the following for your density:
       | (x + 3) / 13       -3 <= x <= -1
       |
f(x) = | 2 / 13             -1 <= x <= 1
       |
       | 2 * (8 - x) / 91    1 <= x <= 8

Integrating this and collecting terms produces the CDF:
       | (x + 3)**2 / 26                    -3 <= x <= -1
       |
F(x) = | (2 + x) * 2 / 13                   -1 <= x <= 1
       |
       | 6 / 13 + [49 - (x - 8)**2] / 91     1 <= x <= 8

Finally, determining the values of F(x) at the break points between the segments and applying inversion yields the following pseudocode algorithm:
generate U ~ Uniform(0,1)
if U <= 2 / 13:
    return 2 * sqrt( (13 * U) / 2 ) - 3
else if U <= 6 / 13:
    return (13 * U) / 2 - 2:
else:
    return 8 - sqrt( 91 * (1 - U) )

Note that this is a true inversion.  The outcome is determined by generating a single U, and transforming it in different ways depending on which range it falls in.


text:
Q: How to avoid background / frame break in code listings with math / mathescape? I have lots of C++ sources with LaTeX formulas in the comments. Ideal for using the listings packages to pretty print the source. However, most of the formulas break either, the background or the frame lines when the formula is "tall" (e.g. contains an integral or a sum) as seen in the following working example and preview. The question is: how can I force listing not to break the frame on tall lines produced by tall math equations?
\documentclass{article}
\usepackage[]{listings}
\usepackage{xcolor}
 \lstset{
        backgroundcolor=\color[gray]{0.9},
        frame=single,
        mathescape=true,
}
\lstset{language=C++}
\begin{document}

\begin{lstlisting}
for(i = 0; i < 10; i++)
{
// gratuitious equation $\mathcal{D}_3(x) = \frac{x^n}{n} \int_{0_0}^{x^2} \frac{t^n}{e^t-1}dt$
*p++ = i;
House h = new house();
int romms = h.getRooms():
}
\end{lstlisting}

\end{document}

Note: If this is an intrinsic limitation of listings packages, then the real question could be how can equations be force to use the normal vertical space as much as possible in math mode. For example to force integrals and sums to be even shorter than inline math model.
I am also aware of this other question: listings with background color and mathescape broken, but that only solved for a particular math symbol.

A: You have at least two options to correct for this behaviour.

*

*If your mathematical equations (contained within the escaping $...$) is fairly simple and usually only contains a one line, and perhaps even does not have any other code above/below it, then you can \smash the escaped content:
\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\begin{document}
\lstset{%
  backgroundcolor=\color[gray]{0.9},%
  frame=single,%
  mathescape=true,%
}
\lstset{language=C++}%

\begin{lstlisting}
for(i = 0; i < 10; i++)
{
// gratuitious equation $\smash{\mathcal{D}_3(x) = \frac{x^n}{n} \int_{0_0}^{x^2} \frac{t^n}{e^t-1}dt}$
*p++ = i;
House h = new house();
int romms = h.getRooms():
}
\end{lstlisting}

\end{document}

However, as you can see, even from this small example, the bottom part of the equation is overwritten with the background colour. This is because the algorithm is typeset sequentially, overwriting anything with a depth below the baseline. So this option is very restrictive, and typically only works if your mathematical expression does not drop below the baseline. Pretty restrictive...

*You can use a different environment to draw the frame and background. The mdframed package does an excellent job of this:
\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\usepackage{xcolor}% http://ctan.org/pkg/listings
\usepackage[framemethod=TikZ]{mdframed}% http://ctan.org/pkg/mdframed
\begin{document}
\lstset{%
%  backgroundcolor=\color[gray]{0.9},
%  frame=single,
  mathescape=true,
}
\lstset{language=C++}%

\begin{mdframed}[backgroundcolor=black!15,outerlinewidth=0.25pt,outerlinecolor=black,%
  innerleftmargin=5pt,innerrightmargin=5pt,innertopmargin=0pt,innerbottommargin=0pt]
\begin{lstlisting}
for(i = 0; i < 10; i++)
{
// gratuitious equation $\mathcal{D}_3(x) = \frac{x^n}{n} \int_{0_0}^{x^2} \frac{t^n}{e^t-1}dt$
*p++ = i;
House h = new house();
int romms = h.getRooms():
}
\end{lstlisting}
\end{mdframed}

\end{document}

In the above example, mdframed uses tikz to draw the frame. It is possible to automate this process of using mdframed in conjunction with listings. For this, the etoolbox package provides hooked to add code before the beginning and after the end of an environment (lstlisting in this case). For this, the macros \BeforeBeginEnvironment and \AfterEndEnvironment is helpful. It is crucial to add code in this manner, since lstlisting modified catcodes for formatting:
\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\usepackage{xcolor}% http://ctan.org/pkg/listings
\usepackage[framemethod=TikZ]{mdframed}% http://ctan.org/pkg/mdframed
\usepackage{etoolbox}{% http://ctan.org/pkg/etoolbox

\mdfdefinestyle{listingstyle}{%
  backgroundcolor=black!15,outerlinewidth=0.25pt,outerlinecolor=black,%
  innerleftmargin=5pt,innerrightmargin=5pt,innertopmargin=0pt,innerbottommargin=0pt%
}

\begin{document}

\lstset{mathescape=true,language=C++}%

\BeforeBeginEnvironment{lstlisting}{\begin{mdframed}[style=listingstyle]}
\AfterEndEnvironment{lstlisting}{\end{mdframed}}

\begin{lstlisting}
for(i = 0; i < 10; i++)
{
// gratuitious equation $\mathcal{D}_3(x) = \frac{x^n}{n} \int_{0_0}^{x^2} \frac{t^n}{e^t-1}dt$
*p++ = i;
House h = new house();
int romms = h.getRooms():
}
\end{lstlisting}

\end{document}

In the above modification, a new mdframed style listingstyle is defined and used as style=listingstyle in the option argument to the mdframed environment. The output is similar to the previous example.


text:
Q: Concerning a modification of the division with remainder I just did the following exericse:

Prove that for given intergers $a$ and $b$ with $b>0$ holds:
There are unique integers $q$ and $r$ such that $a = qb+r$ and $-b/2 < r \le b/2$.

I did the following:
$$-b/2 < r = a-qb \le b/2$$
$$\implies \frac{a}{b} + \frac{1}{2} > q \ge  \frac{a}{b}-\frac{1}{2} $$
$$\implies q = \lceil{ \frac{a}{b} + \frac{1}{2}\rceil}$$
I am insecure about the ceil in the end, could you tell me if I am right?

A: If there are two $q$s such that $$a=bq_1+r_1$$and $$a=bq_2+r_2$$we have $$|r_1-r_2|=|q_1-q_2|b\ge b$$which is impossible since $-\dfrac{b}{2}<r_1,r_2\le\dfrac{b}{2}$ then $q_1=q_2$ and so is $r_1=r_2$

A: I find the argument below simpler.
We have $a = Qb+R$, with $0 \le R < b$.
If $R \le b/2$, then take $q=Q, r=R$.
If $R > b/2$, then take $q=Q+1, r=R-b$. Then $-b/2 < R <0 < b/2$.


text:
Q: automorphism $(Z/2Z)^n$ I am preparing for an exam in elementary group theory and while studying a proof by my professor, I came across something I just don't seem to understand. In his proof he claims that, considering a map from $(Z/2Z)^n$ to itself ($Z$ being the set of integers), the correspondence $(x_1 , ... , x_n)\to(x_2 , ... , x_n , x_1)$ is an isomorphism. Why is this correspondence an isomorphism?
Also, is it true that the correspondence $(x_1 , ... , x_n)\to(x_{a_1}, ... , x_{a_{n-1}} , x_{a_n})$, where $0 < a_i < n+1$ and $a_i = a_j <=> i=j$, is also an isomorphism from $(Z/2Z)^n$ to itself?

A: Hints
Fill in details :
Observe that $\;G:=\left(\Bbb Z/2\Bbb Z\right)^n\;$ can be seen as a vector space over the field $\;\Bbb F_2:=\Bbb Z/2\Bbb Z\;$, with the obvious termwise addition and scalar product.
Then, an automorphism of the abelian group $\;G\;$ is the same as an automorphism of the vector space $\;G_{\Bbb F_2}\;$ , and the map you show there is the one determined by the linear operator changing any ordered basis $\;\{e_1,...,e_n\}\;$ into the ordered basis $\;\{e_2,...,e_n,e_1\}\;$


text:
Q: c++ code not giving output (topic : recursion and 2D vector)
*

*You are given a number n, representing the number of rows.

*You are given a number m, representing the number of columns.

*You are given n*m numbers, representing elements of 2d array a. The numbers can be 1 or 0 only.

*You are standing in the top-left corner and have to reach the bottom-right corner.
Only four moves are allowed 't' (1-step up), 'l' (1-step left), 'd' (1-step down) 'r' (1-step right). You can only move to cells which have 0 value in them. You can't move out of the boundaries or in the cells which have value 1 in them (1 means obstacle)

*Complete the body of floodfill function - without changing signature - to print all paths that can be used to move from top-left to bottom-right.

this is the question and here is the link for reference https://www.pepcoding.com/resources/online-java-foundation/recursion-backtracking/flood-fill-official/ojquestion#
i used the following code and checked it many times i dont find any error in it please help me figure out whats wrong, i am coding in c++

#include <iostream>
#include <string>
#include <vector>

using namespace std;

void floodfill(vector<vector<int>> maze, int sr, int sc, string psf, vector<vector<int>> visited)
{
    if (sr < 0 || sc < 0 || sr == maze.size() || sc == maze[0].size() ||
        maze[sr][sc] == 1 || visited[sr][sc] == 1)
            return;
    if (sr == maze.size() - 1 && sc == maze[0].size() - 1)
    {
        cout << psf << endl;
        return;
    }
    visited[sr][sc] == 1;
    floodfill(maze, sr - 1, sc, psf + "t", visited);
    floodfill(maze, sr, sc - 1, psf + "l", visited);
    floodfill(maze, sr + 1, sc, psf + "d", visited);
    floodfill(maze, sr, sc + 1, psf + "r", visited);
    visited[sr][sc] == 0;
}

int main()
{
    int n, m;
    cin >> n >> m;
    vector<vector<int>> arr(n, vector<int>(m));
    vector<vector<int>> visited(n, vector<int>(m));
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            cin >> arr[i][j];

    floodfill(arr, 0, 0, "", visited);
}

please someone help thnx..

A: You need to add references to your vectors. C and C++ are pass by value languages you need to explicitly tell C++ that you are passing by reference.
void floodfill(vector<vector<int>>& maze, int sr, int sc, string psf, vector<vector<int>>& visited)
{
    if (sr < 0 || sc < 0 || sr == maze.size() || sc == maze[0].size() ||
        maze[sr][sc] == 1 || visited[sr][sc] == 1)
            return;
    if (sr == maze.size() - 1 && sc == maze[0].size() - 1)
    {
        cout << psf << endl;
        return;
    }
    visited[sr][sc] = 1;
    floodfill(maze, sr - 1, sc, psf + "t", visited);
    floodfill(maze, sr, sc - 1, psf + "l", visited);
    floodfill(maze, sr + 1, sc, psf + "d", visited);
    floodfill(maze, sr, sc + 1, psf + "r", visited);
    visited[sr][sc] = 0;
}

Also I think you may want to do assignment here visited[sr][sc] == 1;


text:
Q: Something like an operation filter in WCF REST? I am looking for something like the AuthorizeAttribute in MVC, something I can use like this:
    [WebGet(UriTemplate = "data/{spageNumber}")]
    [WebCache(CacheProfileName = "SampleProfile")]
    [WcfAuthorize]
    public IEnumerable<SampleItem> GetCollection(String spageNumber)
    {
        Int32 itemsPerPage = 10;
        Int32 pageNumber = Int32.Parse(spageNumber);
        return Enumerable.Range(pageNumber * itemsPerPage, itemsPerPage)
                         .Select(i => SampleItem.Create(i));
    }

That WcfAuthorizeAttribute, will try to authenticate the user with FormsAuthentication, and set the context's IPrincipal, or return a HTTP 401 Unauthorized.
I have tried with a IOperationBehavior, but I gets executed in the first method, whichever it be, not in the method I have set the attribute.
How can this be achieved in WCF REST?
Regards.
PS: I have seen the RequestInterceptor example in the Starter Kit, but what I want is put it in some methods only, and the example looks like a filter you execute in all the operations.

A: You can use AOP to achieve this. I have used PostSharp as an AOP tool to achieve this functionality. You can also find a sample on their website. The OnMethodEntry gets executed before a method (that is decorated with this attribute) is executed and you can perform your validation there.
I did a quick sample to test this and it worked.
[Serializable]
[ProvideAspectRole(StandardRoles.Security)]
public class WcfAuthorizeAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        //extract forms authentication token here from the request and perform validation.
    }
}

And you could decorate your WCF methods like below.
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1
{
    [WcfAuthorize]
    [WebGet(UriTemplate = "")]
    public List<SampleItem> GetCollection()
    {
        return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } };
    }


text:
Q: what will happen if my cpu usuage stays 100% for 30 mins or so on linux server I have Amazon Ec2 small instance with 1.7Gb RAM. I have 3 websites running on them.
I have the scripts which does the web crawling every day and perform some caluclation.
I have not deployed them yet. But i want to know that if those scripts run for 30 mins and processor usage is 100% what will happen to websites. Will they stop working, or be slow?
I am not sure.
Sites are not high traffic.

A: I highly doubt you will experience ill effects with low traffic, but you could quite easily run tests on the speed and such.


text:
Q: PHP constant not defined I am working with a database project and I have created a seperate file to keep all the database information name 'config.php'. And for the database I keep another 'database.php' file in the same directory.
------------------------config.php--------------
<?php
defined('DB_SERVER') ? null : define('DB_SERVER',"localhost");
defined('DB_USER')   ? null : define('DB_USER',"gallery");
defined('DB_PASS')   ? null : define('DB_PASS',"phpOTL123");
defined('DB_NAME')   ? null : define('DB_NAME',"photomania");
?>

------------------------databae.php-------------
<?php
require_once("config.php");
class MySQLDatabase{
    private $conn;

    function __construct(){
        $this->open_connection();
    }
    public function open_connection(){
        $this->conn = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
        if(!$this->conn){
            die("Database Connection Failure :(".mysql_errno());
        }else{
            $db_select = mysqli_select_db($this->conn,DB_NAME);
            if(!$db_select){
                die("Can't select the database".mysql_errno());
            }
        }
    }
    public function close_connection(){
        if(isset($this->conn)){
            mysqli_close($this->conn);
            unset($this->conn);
        }
    }
}

$database = new MySQLDatabase;
?>

the problem is when I include database.php in the index file using
require_once("../includes/database.php");

it gives following errors.

Notice: Use of undefined constant DB_SERVER - assumed 'DB_SERVER' in
  C:\XAMPP\htdocs\gallery\includes\database.php on line 11
Notice: Use of undefined constant DB_USER - assumed 'DB_USER' in
  C:\XAMPP\htdocs\gallery\includes\database.php on line 11
Notice: Use of undefined constant DB_PASS - assumed 'DB_PASS' in
  C:\XAMPP\htdocs\gallery\includes\database.php on line 11
Warning: mysqli_connect(): php_network_getaddresses: getaddrinfo
  failed: No such host is known. in
  C:\XAMPP\htdocs\gallery\includes\database.php on line 11
Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses:
  getaddrinfo failed: No such host is known. in
  C:\XAMPP\htdocs\gallery\includes\database.php on line 11 Database
  Connection Failure :(

Any help ??????

A: you problem seems to lie in following line
require_once("config.php");

try replacing it with
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "config.php");

A: If you have to check if a constant is defined before defining it, you're structuring something wrong. Just remove the checks, define them, and always use require_once.


text:
Q: How can RegEx named match HTML attributes and ignore order? I currently have the following RegEx workflow to match WordPress caption tags and subsitute them by Jekyll caption tags:
import sys, re

def re_sub(pattern, replacement, string):
    def _r(m):
        # Now this is ugly.
        # Python has a "feature" where unmatched groups return None
        # then re.sub chokes on this.
        # see http://bugs.python.org/issue1519638

        # this works around and hooks into the internal of the re module...

        # the match object is replaced with a wrapper that
        # returns "" instead of None for unmatched groups

        class _m():
            def __init__(self, m):
                self.m=m
                self.string=m.string
            def group(self, n):
                return m.group(n) or ""

        return re._expand(pattern, _m(m), replacement)

    return re.sub(pattern, _r, string)

def parseCaptions(content):
    """
    [caption id="attachment_76716" align="aligncenter" width="500"] WER calculation[/caption]

    to

    {% caption align="aligncenter" width="500" alt="WER calculation" text="WER calculation" url="../images/2013/11/WER-calculation.png" %}
    """
    import re

    pattern = '\[caption(.*?)align="(?P<align>.*?)"(.*?)caption="(?P
.*?)"(.*?)\]' + \
        '<a(.*?)href=\"(?P<url>(.*?))\"(?P<asonst>.*?)>' + \
        '<img(.*?)src=\"(?P<imgurl>http://martin-thoma.com/wp-content/uploads/(?P<innerurl>(.*?)))\" ' + \
            '(class=\"(?P<imgclass>.*?)\")?\s*' + \
            'title=\"(?P<title>.*?)\"\s*' + \
            '(alt=\"(?P<alt>.*?)\")?\s*' + \
            'width=\"(?P<width>.*?)\"\s*' + \
            'height=\"(?P<height>.*?)\"\s*' + \
            '(?P<isonst>.*?)/>' + \
        '\s*' + \
        '(?P<text>.*?)\[/caption\]'
    pattern = re.compile(pattern)
    results = [m.groupdict() for m in pattern.finditer(content)]
    for result in results:
        for key, value in result.items():
            print("%s:\t%s" % (key, value))

    content = re_sub(pattern, '{% caption align="\g<align>" width="\g<width>" caption="\g
\g<text>" url="../images/\g<innerurl>" alt="\g<alt>" title="\g<title>" height="\g<height>" class="\g<imgclass>" %}', content)

    return content

My regex is not very good, because the order of attributes inside a tag does not matter in reallity, but it matters for my regex. How can I make the regex match any order within a tag (but at most once or match the latest occurence)?
(edit: another reason why this RegEx is suboptimal is that all groups should replace " by ')


text:
Q: input_sentences = [text.split("") for text in df["text"].values.tolist()] I am new to coding, can someone please explain to me what this line of code is doing:
input_sentences = [text.split("") for text in df["text"].values.tolist()]

where text is a column containing sentences in my excel dataset df

A: to understand this line what knowlede you require

*

*list comprehensionlink1

*tolist functionlink2

*pandas serieslink3

*spilt()link4
Now Jump to our code
  input_sentences = [text.split("") for text in df["text"].values.tolist()]

Understand step by step
  df["text"].values.tolist()

df['text] is series which define using index and value from that we are extracting only value then it is converted into list
  for text in df["text"].values.tolist()

this is just for loop which is iterating our list and each single value from list inserted into text
text.split("")

from above the value inserted in text are seperated by space  and at last stored inside 2d list

A: df["text"].values.tolist()

Transforms your column 'test' in a list of the values you had in the column.
[text.split("") for text in df["text"].values.tolist()]

This line takes each element text of the previous list and split the words by the char "". Here it is empty. If you split by "," or by "." you will have for text="blabla,blabla"
text.split(",") will give you a list : ["blabla","blabla"]
So in the end you will have a list of list of words contained in your dataframe's column.


text:
Q: Normalize a String to create a safe URL in Java I'm writing a library in Java which creates the URL from a list of filenames in this way:
final String domain = "http://www.example.com/";

String filenames[] = {"Normal text","Ich weiß nicht", "L'ho inserito tra i princìpi"};

System.out.println(domain+normalize(filenames[0]);
//Prints  "http://www.example.com/Normal_text"
System.out.println(domain+normalize(filenames[1]);
//Prints  "http://www.example.com/Ich_weib_nicht"
System.out.println(domain+normalize(filenames[2]);
//Prints  "http://www.example.com/L_ho_inserito_tra_i_principi"

Exists somewhere a Java library that exposes the method normalize that I'm using in the code above?
Literature:

*

*Which special characters are safe to use in url?

*Safe characters for friendly url

A: Taking the content from my previous answer here, you can use java.text.Normalizer which comes close to normalizing Strings in Java. An example of normalization would be;
Accent removal:
String accented = "árvíztűrő tükörfúrógép";
String normalized = Normalizer.normalize(accented,  Normalizer.Form.NFD);
normalized = normalized.replaceAll("[^\\p{ASCII}]", "");

System.out.println(normalized);

Gives;
arvizturo tukorfurogep

A: Assuming you mean you want to encode the strings to make them safe for the url. In which case use URLEncoder:
final String domain = "http://www.example.com/";

String filenames[] = {"Normal text","Ich weiß nicht", "L'ho inserito tra i princìpi"};

System.out.println(domain + URLEncoder.encode(filenames[0], "UTF-8"));
System.out.println(domain + URLEncoder.encode(filenames[1], "UTF-8"));
System.out.println(domain + URLEncoder.encode(filenames[2], "UTF-8"));


text:
Q: Популярность Java Вопрос довольно глупый, но прошу не смеяться. В чем причина популярности Java? Почему она получила такое широкое распространение?
A: Вероятнее всего из-за ее абсолютной платформонезависимости (наличие ява машины) и довольно развитой парадигмы ООП.
В освоении java тоже довольно простой язык, тоже самое можно сказать и касательно портирования с java на другие ЯП при условии знания оных.
P.s: если где-то не прав, прошу поправить
A: Тема замусоленная, и наиболее полные ответы можно найти на англоязычных ресурсах.
Рекомендую почитать Why do people use java? и Why is C# suddenly so popular?
Вторая тема хороша сравнением подходов Microsoft и Sun/Oracle к развитию языка и платформы.
Также обращайте внимание на комменты, поскольку в них чаще всего находятся очень дельные замечания  к основным тезисам ответов - например, про костыли на java при разработке кросс-платформенных приложений и тому подобные вещи, которые приходят с опытом.

A: Ещё свои 5 копеек к популярности добавил garbage collector (сборщик мусора), система отвечающая за автоматическое освобождение памяти путём удаления объектов на которые уже нет ссылок, строгая типизация (спорно, есть программисты которым не нравится), отказ от множественного наследования в пользу интерфейсов(также спорно), огромный архив библиотек по всему интернету, которые можно свободно использовать и переделывать не опасаясь проблем с копирайтом, детальные подсказки и отлавливание ошибок на уровне компиляции...
A: Я выделю несколько принципиальных моментов:

*

*Платформенная независимость (естественно с оговорками)

*Автоматическая сборка мусора

*И все методы по умолчанию (и почти всегда) виртуальные (в терминах С++)

*Отсутствие множественного наследования

*Правильный маркетинг языка (write once use everywhere). Изначально языком владела 1 компания Sun и она не допустила растекания спецификаций языка по множеству версий как это случилось с С/С++/SQL иже с ними.

P.S. Я считаю, что из всего этого списка наиболее важное свойство это п.3 - в самый раз для "быдлокодеров" не сумевших асилить "брульянтную" философию C++. Уверен, что 99% Java кодеров даже не подозревает об этом свойстве их любимого языка. И, кстати, это правильно!
A: Хотел бы добавить что во многих известных языках реализация ООП делалась на основе Java, что лишь подтверждает то, насколько хорошо в java оно реализовано...
Ну и добавьте к этому кроссплатформенность, + разработка ПО для мобильных девайсов = успех...
Кстати - не так далеко от java C#, да и C++ будет жить вечно...
A: Я бы сказал - сбалансированность. Нет крупных недостатков, и нет сложных наворотов. Все очень стройно и логично. Когда разберешься - чувствуешь себя уверенно, не опасаясь подводных камней.
A: Все плюсы джавы отходят на 2й план из-за ее простоты изучения, тут можно спорить, но не признать тот факт, что она проще в своем понимании от С++, С, ASP.NET, Perl, Python и тд, нельзя


text:
Q: Why dynamic languages don't have private member definition feature in classes (like objective c or python)? Why do dynamic languages lack the ability to define private members in classes?
Is there any implementation concern on this feature? Is it possible for this feature to be implemented for a dynamic language?

A: There are countless answers to this sort of thing, "Why doesn't language X have feature Y?"  And the answer is simply because the people involved in creating/evolving the language didn't put it there.  Computer languages are like <insert anything here that has variations across members in the set>, not all are the same.  (Which most of us are thankful for. ;)
Oy, moving target question...
I'm not an expert in Objective-C, but a quick Googling for "private member function in dynamic languages" turned up some hits that seem to imply that Objective-C does have private member support for classes.

A: This can be implemented for dynamic languages. Indeed, in Smalltalk, all members are always private.
The reason why this is not common is that there is no point in having both public and private members. External code should not access the internals of other classes as a matter of design. This can be achieved by just not doing that - it is not easy to do that accidentally.
Python solves this by having everything be public, and allowing programmers to do this if necessary, which creates maximum flexibility. Smalltalk solves this by having everything be private, and forcing programmers to create accessors if access from other code is desired.
As to implementation concerns, access checks are relatively expensive (in that for at least some attribute accesses, there will be extra operations, and the more subtle the rules, the more complex the checks), so the all private and all public models are much more attractive than anything with intermediate access levels.

A: You can use a class expansion in Objective-C to make something not visible to other classes. Ex.
//at the top of MyClass.m
@interface MyClass ()
@property (strong, nonatomic) id myPrivateProperty;
@end

Other than that, there's not much to say as it's too broad a question (still).

A: Or, in addition the answer by @Mettable:
@interface MyObject : NSObject {
    @private
    id _myIvar;
    id _myOtherIvar;
}

.
.
.

@end

I don't know about Python, but I think this SO answer might help.


text:
Q: toggle text on mouseover what i would like to do is toggle a text vertically from bottom to top inside a div.
i have managed to do that but only from top to bottom.
any ideas?
here's the code

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut placerat purus elit, sit amet dignissim dui elementum in. Nunc elementum tempor nulla quis mollis. Nunc et nibh eu magna pharetra condimentum ac ut felis.Nunc et nibh eu magna pharetra condimentum ac ut felis.Nunc et nibh eu magna pharetra condimentum ac ut felis.

    #box1 {
        width:340px;
        height:200px;
        background-color:#ccc;
        float:left;
    }

    #box1text {
    height:50px;
    overflow:hidden;
    opacity:0.5;
    padding:10px 10px;
    text-align:justify;

    }

$(document).ready(function() {

  $("#box1text").hover(
    //on mouseover
    function() {
      $(this).animate({
        height: '+=150'
        }, 'slow'
      );
    },
    //on mouseout
    function() {
      $(this).animate({
        height: '-=150px'
        }, 'slow'
      );
    }
  );

});

here's the demo
http://jsfiddle.net/atseros/YrFaQ/

A: If you want a pure CSS solution, I've made it from scratch, you can use display: table-cell; and use vertical-align: bottom; to align the text to the bottom, and than use transition for smoothing up.
Demo
div {
    display: table-cell;
    height: 150px;
    width: 300px;
    background: #f5f5f5;
    vertical-align: bottom;
}

div span {
    display: block;
    height: 40px;
    overflow: hidden;
    -webkit-transition: all .5s;
    -moz-transition: all .5s;
    transition: all .5s;
}

div:hover span {
    height: 150px;
}

Alternatively, you can use position: relative; on the container element and than use position: absolute; for the child and provide top, bottom values respectively..
Demo 2

Even if the browser fails to transit the element, still it will toggle the effect but without the smoothness. This will be useful to few users who just use jQuery to achieve such effect, but by using this, you will save 90KB of library. (But anyways, jQuery FTW)

A: http://jsfiddle.net/kasperfish/YrFaQ/1/
just position your box1text to the bottom of box1. You can do this by giving your box1 container a relative position. this way you can position any child element (box1text) absolute inside the container. Have a look at the css...
#box1 {
    width:340px;
    height:200px;
    background-color:#ccc;
    float:left;
    position:relative;
}

#box1text {
    height:50px;
    overflow:hidden;
    opacity:0.5;
    padding:5px 5px;
    position:absolute;
    left:0;
    bottom:0
}


text:
Q: Empty string SQL not working I have a table of grades where each grade cannot be NULL. Each grade is a text so I'm guessing if the column is empty then it is an empty string, ' '. I want to select the columns where the grade is empty. I'm doing:
SELECT student FROM simulated_records WEHRE grade = ' ';

but this is not working and I dont understand why. Is there a right way of doing it? I'm new to SQL.

A: If you want select columns with empty grade column then why you're looking for " "? There is empty space. Try this
SELECT student FROM simulated_records WHERE grade IS NULL;

A: The following will address two scenarios that could be present in your database table. The first is a "null value" i.e. the value was never set and null values are allowed.   The second is the empty string.
SELECT student FROM simulated_records WHERE trim(grade) = '' OR grade IS NULL

A: each grade cannot be NULL so no need to check with "grade is NULL" just do
SELECT student FROM simulated_records WEHRE TRIM(grade) = '';


text:
Q: Converting a .flac or .mp3 file into an .mp4 to be DASH compatible I would like to know if it's possible to convert a .flac or a .mp3 file into a .mp4 file (without image or video) in order to be DASH compatible.
The goal is to make my audio files (.flac or .mp3) segmented and compatible with the DASH spec so I can stream audio segments with a web-server.
I already tried to use GPAC MP4Box and ffmpeg but both doesn't seem to support really well audio-only.
I would like some guidance if someone already has experience with this.


text:
Q: pyqt context menu with multiple qlineedit widgets I hope someone can help me out with this.
I have a pyqtgraph context menu and want to add my own Z-Axis. I can create a qlineedit widget but I am not able to create multiple widget on the same line in the context menu as show below (e.g. radio button and 2 text boxes on same line)

As a minimum I would like to achieve:-
Z Axis -> [input value], string, [input value]
I've had a look in qmenu but couldn't find what I needed. Anyone know how to achieve this.
Also if anyone knows how to change the size of the X Axis qlineedit boxes and make them bigger it would be great as they are a bit squashed as you can see.

A: Someone on a different forum was able to help me with the answer so I thought I would also post it here for future users.
What you have to do is go into the site-packages for python and find pyqtgraph/graphicsItems/ViewBox/. In there are several files called

axisCtrlTemplate_*.py

A couple of lines down in the ui_form is the following line which you just need to increase the width (e.g. 450)

Form.setMaximumSize(QtCore.QSize(450, 16777215))

Hey presto fixed.
Also in the same location is a file called

ViewBoxMenu.py

you can see how the context menu is written here and I will use this information to create my min and max values which are created in a ui (qtdesigner) and then added to the menu


text:
Q: SQL Statement Capture from within Visual Studio 2012 or MS SQL 2012 I'm using Visual Studio 2012 and MS SQL Server 2012 for a C++ application.
I understand there's a way to capture SQL statements from both programs (some sort of trace profiler) for individual tables but I've run across very few tutorials on how to do perform this, and unfortunately they tend to be a bit vague on specific steps- almost as if they assume you should already know how to do this.  Is there a way to perform this capture/trace for statements that span multiple tables?  If so, how?
Unfortunately, the code I inherited is 20K lines of spaghetti code so it makes sense to capture the resulting statement before it's sent to the DB rather than spending a few weeks stepping through it.

A: SQL Server Profiler from the Tools menu in SSMS. You can filter to capture the calls from certain logins and depending on the connection string used you can also filter by application name. For more details msdn.microsoft.com/en-us/library/ms173799(v=sql.110).aspx
To make it easier to profile just the calls you are looking for, if you add: Application Name=MyAppName; to the connection string your app uses you can then filter in SQL Profiler by Application Name Like MyAppName.


text:
Q: Can't open drive marked as System in Disk Management in W7 Reinstalled Windows 7 64bit recently on my new HDD. Now one of my drives I use as storage is marked with status "Healthy (System, Active, Primary Partition)" and I can't open it to view the contents as Right-Click -> Open is grey'd out and it doesn't show up in "My Computer".
What do I do to remedy this without losing what's on this drive?

A: Solved by Right Clicking the drive in Disk Management and assigning it a drive letter


text:
Q: DIsplay attribute image if it exists in folder I'm adding some information to my product page and I'm not very familiar with php.
Can anyone help me and indicate how can I place these two echo in to a valid if. So it should place an image if the image exist's in folder and if it doesn't then put attribute text.
<?php echo $_product->getAttributeText('gol_marca'); ?>

<?php $brand=$_product->getAttributeText('gol_marca');
      echo ''?>

A: I have face same problem in one of my project. I have already find the solution for that.
<?php
$file= Mage::getBaseDir('media') . '/catalog/brands/'.strtolower(preg_replace('`[^~a-z0-9-._]`i', '', $brand)).'.gif';

if(file_exists($file)){
    $merk_file = Mage::getBaseUrl('media') . 'catalog/brands/'.strtolower(preg_replace('`[^~a-z0-9-._]`i', '', $brand)).'.gif';
}
else{
  "nothing to do."
}
?>

We can check the url based on media folder.
If you facing some problem then let me know.


text:
Q: Lambda Function to Compare 2 Lists With Multiple Criteria I have a lambda function that I need to use to compare 2 lists and return those records from one list that are in the second list. The lambda function has 4 comparisons. The first three search within the original list, while the 4th is the part that does the comparison.
IEnumerable<IssueDataModel> keywordissues = _adoSqlService.Search_Keyword(searchText);
IEnumerable<IssueDataModel> returnedIssues = issueList;
returnedIssues = issueList.Where(s => s.issueId.ToLower().Contains(searchText.ToLower()) ||
    s.issueTitle.ToLower().Contains(searchText.ToLower()) ||
    s.issueDescription.ToLower().Contains(searchText.ToLower()) ||
    s.issueId.Intersect(keywordissues.Select(y => y.issueId))
);
return returnedIssues;

The problem I'm having is the part were I do the "intersect". I'm getting the following error:
string does not contain a definition for 'Intersect' and the best extension method overload 'Queryable.Intersect<string>' requires a receiver of type 'IQueryable<string>'
How can I perform this short of doing this on the SQL side?


text:
Q: i need help adding the leap year functionality into my python program import math
repeat = True
date = raw_input('Enter a date in the format MM/DD/YYYY') #Prompts user to input

while repeat:
   date_month = date[0:2] #Takes the input's month and keeps its value for the varible date_month
   date_day = date[3:5] #Takes the input's day and keeps its value for the varible date_day
   date_year = date[6:10] #Takes the input's year and keeps its value for the varible date_year
   if 00 < int(date_month) < 13:
      if 00 < int(date_day) < 32:
         if 0000 < int(date_year) < 2017:
               date = raw_input('The date you entered is valid, enter another date in the format MM/DD/YYYY')
   else:
      date = raw_input('invalid date found! Please enter another date in the format MM/DD/YYYY')

A: Roll-your-own parser code is silly. Python has batteries included for this:
import datetime

repeat = True
datestr = raw_input('Enter a date in the format MM/DD/YYYY')

while repeat:
    try:
        # Parse to datetime, then convert to date since that's all you use
        date = datetime.datetime.strptime(datestr, '%m/%d/%Y').date()
    except ValueError:
        pass  # Handle bad dates in common code
    else:
        if 0 < date.year < 2017:
            datestr = raw_input('The date you entered is valid, enter another date in the format MM/DD/YYYY')
            continue  # Bypass invalid date input common code

    # Both exception and invalid years will fall through to this common code
    datestr = raw_input('invalid date found! Please enter another date in the format MM/DD/YYYY')

Obviously, as written, this doesn't actually terminate the loop under any conditions, but neither does your original code. The advantage here is that strptime does the heavy lifting; it validates many more things that your original code, through a single try/except, and handles tricky stuff like days of the month by month without special checks. You can access the year, month and day attributes of the date object it parses as before, as Python native ints, no individual int conversions as you go.
Note that if you wanted to use locale appropriate date representations, the format you chose happens to exactly match for en_US locale, and you could make it more portable to non-U.S. users by just using datetime.datetime.strptime(datestr, '%x') (though you'd have to make the raw_input prompt dynamic to match); that works the same as '%m/%d/%Y' for en_US, but switches ordering and separators for, say, a German locale, which would make it equivalent to '%d.%m.%Y'.

A: It is as simple as this:
>>> import calendar
>>> print(calendar.isleap(1999))
False
>>> print(calendar.isleap(2004))
True

A: There a more problems with the question than just if the year is leap or not. @Dex'ter solution will indeed tell you if year is leap or not, but thing is you can't really ask for that in the end. So your first question should be is the user input date a leap year:
 if calendar.isleap(date_year):

, followed by month for which your code is functional. And than you)ll have another problem in the day.
 if 00 < int(date_day) < 32:

This will give you erroneous results no matter if the year is leap or not because there are plenty of months than don't have 31 days. For that I would advise:
 >>> from calendar import monthrange
 >>> monthrange(2011, 2)

EDIT: and by the way this last function supports leap year as well.

A: I rewrite your program.I wish it will help
import math
from datetime import datetime
repeat = True
date = raw_input('Enter a date in the format MM/DD/YYYY :')
while repeat:
    try:
        datetime.strptime(date, "%m/%d/%Y")
        date = raw_input('The date you entered is valid, enter another date in the format MM/DD/YYYY :')
    except ValueError:
        date = raw_input('invalid date found! Please enter another date in the format MM/DD/YYYY :')


text:
Q: Apache camel browse queue without polling it I need to log my database with events on my ActiveMQ.
With logging I mean messages can't be consumed.
Is the folowwing thing possible
public class QueueRouteBuilder extends RouteBuilder {
@Override
public void configure(){
 from("browse:activemq:KBC)
.process(new QueueProcessor());
}
}

A: That camel route is event driven. I.e. it has to somehow poll events of that queue to know whats been dealt with.
I would, instead, go for copies to a queue used for logging. This can be done in two ways with ActiveMQ.

*

*Mirrored queues. That is - every queue has a mirror with all messages copied to it. You simply read of the mirror to do logging/monitoring.

*Virtual Destinations. You can setup a Composite Queue that forwards the message to multiple queues (one for real usage and one for logging). However, this has to be done via config on all involved queues.

*To allow easy wire-tapping, you can switch to topics. It's easy to tap of the messages by simply adding a subscriber. If you really need the queue semantics, you can use Virtual Topics which is the best of the two worlds - topics with queues!


text:
Q: Can I give an ng-form a name that I can check with $pristine? I looked at the documentation for ng-form:
http://docs.angularjs.org/api/ng.directive:ngForm
But it gives me almost no examples and I am still very confused.  What I would like to do is to have a table with input fields and then check if fields on the table are unchanged? I don't want to include this in a form so I was wondering if I can use ng-form.
My HTML looks like this:
<form name="itemForm">
<table>
....
</table>
<button type="submit" data-ng-disabled="itemForm.$pristine">
</form>

Can I do this with an ng-form directive enclosed in a DIV and still set the name in the same way?

A: Yes you can do it with ng-form directive also
Demo: Fiddle


text:
Q: If a group acts properly and coboundedly on a hyperbolic space, each finite subgroup has a (uniformly) bounded orbit. I am trying to solve the following problem:
"Let $G$ be a group acting properly, coboundedly and by isometries on a hyperbolic space $X$. Show that there is a constant $C$ such that any finite subgroup $H$ of $G$ has an orbit of diameter at most $C$.
Deduce that any hyperbolic group has finitely many conjugacy classes of finite subgroups."
I have understood the proof of Theorem III$.\Gamma.3.2$ on Bridson and Haefliger's "Metric spaces of non-positive curvature", pages 459-460, but it deals directly with the second part of my question, using only the usual action of $G$ on its Cayley graph, and not on a general hyperbolic space.
Since the first part of the question is itself interesting, I am looking for a hint on how to show:
"Let $G$ be a group acting properly, coboundedly and by isometries on a hyperbolic space $X$. Show that there is a constant $C$ such that any finite subgroup $H$ of $G$ has an orbit of diameter at most $C$."
My idea is to use the fact that in Cay$(G)$ the statement holds, in order to deduce it for a general $X$. From the Milnor-Svarc lemma we know that for any $x_0 \in X$ the map $$f \colon g \mapsto gx_0$$ extends to a quasi-isometry between Cay$(G)$ and $X$, and $f$ is also $G$-equivariant and therefore maps each $H$-orbit $A \subseteq$ Cay$(G)$ into an $H$-orbit $B \subseteq X$. But there could be points in $B$ that are far from the image $f(A)$, and I do not know whether coarse surjectivity of $f$ can be useful to show boundedness of $B$.

A: If a group $G$ acts on a $\delta$-hyperbolic space with a bounded orbit, say $O$, then Lemma III.$\Gamma.3.3$ produces a subset $C \subset O$ (namely, the set of the quasi-centers) of diameter at most $5 \delta$, and which is defined isometrically so that, because $O$ is $G$-invariant, $C$ must be $G$-invariant as well. Thus, taking some $x \in C$, the orbit $G \cdot x$ has diameter at most $5 \delta$.
I think this argument is due to Brady, Finite subgroups of hyperbolic groups (also available on his webpage). Alternatively, use your other question.


text:
Q: How to create trigger to check geometry validity? I want to create trigger to check geometry validity in spatial table. I have a table:
CREATE TABLE vec_geometry
(
  id bigserial
  is_valid boolean,
  invalid_reason character(128),
  geom geography
)

When I try to create trigger function I get the error:
CREATE FUNCTION geom_valid_check() RETURNS trigger AS
$BODY$
WITH test as (SELECT * FROM ST_IsValidDetail(NEW.geom))
UPDATE vec_geometry
SET is_valid = (SELECT valid FROM test),
    invalid_reason = (SELECT reason FROM test)
WHERE id = NEW.id;
RETURN NULL;
$BODY$
LANGUAGE plpgsql VOLATILE NOT LEAKPROOF;

An error has occurred:

ERROR:  syntax error at or near "WITH"
LINE 3: WITH test as (SELECT * FROM ST_IsValidDetail(NEW.geom))

How to rewrite function to make it work?

A:
Referring to the documentation, I suspect that you want to do something like the following
CREATE TABLE vec_geometry
(
  id bigserial,
  is_valid boolean,
  invalid_reason character(128),
  geom geography
);

CREATE FUNCTION geom_valid_check() RETURNS trigger AS $geom_valid_check$
DECLARE
    val valid_detail;
BEGIN
    val := ST_IsValidDetail(NEW.geom::Geometry);
    NEW.is_valid = valid(val);
    NEW.invalid_reason = reason(val);
    RETURN NEW;
END;
$geom_valid_check$
LANGUAGE plpgsql VOLATILE NOT LEAKPROOF;
CREATE TRIGGER vec_geometry_is_valid BEFORE INSERT OR UPDATE ON vec_geometry
    FOR EACH ROW EXECUTE PROCEDURE geom_valid_check();

INSERT INTO vec_geometry VALUES (1,NULL,NULL,ST_GeomFromText('POLYGON((0 0, 1 1, 1 2, 1 1, 0 0))'));

SELECT * FROM  vec_geometry;

You will notice that it is not trying to update the table directly, but is changing the NEW row before it is inserted or updated into the table.


text:
Q: Add to language syntax in Netbeans/Eclipse This may seem like seem like a bit of a weird/uncommon request but I am trying to find out if it is possible. I would like to add to the language syntax in Netbeans or Eclipse easily without needing to create an entirely new language. According to this question How to add more syntax elements for eclipse it is not possible in Eclipse, but that was asked in 2008 so maybe things have changed.
The reason I want to do it is I am developing in node.js and it uses callbacks quite heavily. So it would be nice if I could make the word 'callback' and 'callback()' be highlighted in a different colour so it can be easily seen in amongst the rest of the code.
Thanks for your help!

A: The css thing is really easy:
go to Options/Miscellaneous/Files, create new file extension less and then select proper MIME type text/x-css. I Believe that it is possible to extend syntax highlighting in NetBeans IDE but you have to write your own plugin to do that.


text:
Q: Java resident memory growing when Executors.newCachedThreadPool used I am using Executors.newCachedThreadPool() to process client api requests. It seems that resident memory of the java process grows with time when average 10tps traffic and it does not get decreased. In addition when looking at thread id, it also shows that threads are not reused. Is there any solution for this. I am using Java 7.

A: I would record when a task is started and finished as it seems you have an increasing number of threads. I would try using a relatively small fixed size pool instead to ensure they are reused and it will show if you have a bug causing a resource leak.
I would also consider using a recent version of Java such as 8 or 11 though I didn't think it would make a difference in this case.


text:
Q: Python: Export huge number as string from Excel File trying to get a column from excel file, this column has values like= 819195861645728953,213234621044503745. When I get the dataframe device column change all the values as: 8.19195861645729e+17, 2.132346210445037e+17 even if I changed to str or put this:
File['device'] = File.apply(lambda x: "'" + str(x.device) , axis = 1)

The value always showed in wrong format
Here is the code:
import pandas as pd

NewFilePath =r'C:\Users\318459\Downloads\\'#AQUI CAMBIO
NewFile='AAACB Main 5.7.2021.xlsx' #AQUI CAMBIO
NewFilePath =NewFilePath.replace('\\', '/')
File= pd.read_excel(f'{NewFilePath}{NewFile}', sheet_name="Sheet1")

File['device']=File['device'].values.astype(str)
File=File[['device']]

Regards

A: You need to stop pandas from inferring the dtype when it imports the data, otherwise it's too late. Do this by specifying the dtype upon import.
File = pd.read_excel(f'{NewFilePath}{NewFile}', sheet_name='Sheet1',
                     dtype={'device': 'str'})


text:
Q: Highcharts tooltip not displaying corrosponding text value, instead displaying 'undefined' I have a list of text values with their corresponding score values (value X and value y). I am able to plot a dot at the intersection of value x and value y. Hovering over the dot displays the location value of the dot on x,y coordinates but for the corresponding text value it is displaying unidentified.

Here is the json representation of my array object which i received from my server side code.
array[1]
object{
AvgIPA:7, IdeaId:17989, Likes:3, Status:2, StatusString:"Published", Title:"Spread the word", UserFullName:"Anurag Acharya", XAxis:9, YAxis:5, ZAxis:7}

Now i send only the relevant data to my series from practicalityscore array. Here is the representation of that data.
practicalityscore [1]
[5, 7, "Spread the word"]

Here is the screenshot of how browser is displaying the data on chart
Instead of undefined, "Spread the word" should get displayed.

A: You may try to modify your formatter as following , change this.point.name to this.point.series.name
function(){
    return 'Practicality: '+
        Highcharts.numberFormat(this.x,0) +
        '
Avg IPA: '+
        Highcharts.numberFormat(this.y,0) +
        '
Idea: '+  this.point.series.name;
}

Not sure if I understand your objective correctly, hope this help
I tried to create a similar jsfiddle example base on my understand
http://jsfiddle.net/unshz5uu/

A: You need to replace your array for point with object. It should be  {x: 5, y:7, name: "Spread the word"}. Then in formatter refer to this.point.options.name


text:
Q: Issue with signal handling, interrupt handling While the process is executing a blocking system call, say read or write, signal has arrived.
Does the system call is terminated with the error EINTR?
Does the system call is restarted after handling the system call?
Suppose, system call is terminated with the error EINTR, Kernel handles the signal before returing to user space.
Does the signal handle is executed in user mode/kernel mode?
If its in user mode, does there'll be return to the instruction after the system call(read/write) during which signal arrived or again it goes to kernel mode after handling the signal and returns to the user from ret_from_syscall. How the execution is resumed at the instruction next to the system call during which signal arrived?
Is it possible to restart the system by passing SA_RESTART flag in sigaction?

A: Signal is executed in user mode, but with a different user context, then return to kernel, which return to user_mode with ret_from_syscall.
The behaviour of system call when signal handler are installed with SA_RESTART depends on the system call.
A description of which system call are restarted is available in recent version of the signal overview manpage :
man 7 signal

If the SA_RESTART flag is not used, system call is not restarted.