text:
Q: Why is this usort not ordering an array of dates? I am trying to order this array chronologically:
$ta = array (
    0 => '20/05/2012',
    1 => '08/01/2011',
    2 => '23/10/2010',
    3 => '27/07/2013',
    4 => '28/01/2011',
    5 => '21/10/2010',
    5 => '18/07/2013',
);

function comp2($a, $b) {
    if ($a == $b)
        return 0;

    return ($a < $b) ? 1 : -1;
};

usort($ta,'comp2');

This returns:
  Array
(
  [0] => 28/01/2011
  [1] => 27/07/2013
  [2] => 23/10/2010
  [3] => 20/05/2012
  [4] => 18/07/2013
  [5] => 08/01/2011
)

I have also converted dates with strtotime after changing to mm/dd/yyyy to no avail.

A: You can simply use usort like as
usort($ta,function($a,$b){
    return strtotime(str_replace('/', '-', $a)) - strtotime(str_replace('/', '-', $b));
});

Brief Explanation :
Here the date structure that you have is American Date Format which is m/d/Y. So that needs to be replace into European Date Format first i.e. d-m-y . You can check this answer for PHP date conversion to strtotime.
Demo

A: Just sorting them as strings will not work, as it will order them alphabetically. The first of january 1988 will then come before the last of december 2015 since it starts with the first characters - the days.
So you will have to convert the strings to dates. The problem here is that strtotime() doesnt accept the dd/mm/YYYY format. Using this workaround you get the following code:
function comp2($a, $b) {
    $x = toDate($a);
    $y = toDate($b);
    if ($x == $y) return 0;
    return ($x < $y) ? 1 : -1;
}

function toDate($d) {
    return strtotime(str_replace('/', '-', $d));
}

If you have a lot of dates to sort, this is not very efficient, though. The same date will be compared to multiple dates, and therefore converted multiple times. That is a waste of resources. So if performance is an issue, loop through the array an convert all dates and then sort it just using sort(). After that you can convert back to whatever format you want using date().


text:
Q: Execute php code stored in database

                      <?php echo $content->content ?>

Im trying to build a custom CMS for a project. This block of code is stored in database but the problem is that the php code cannot execute its functionality like echo.
I tried to use {{ $content->content }} but the browser reads it as a string.
Through my research I encountered eval() but cannot make it to work and they said that it's too risky.

A: You have to end it with ; in <?php echo $content->content ?> first as <?php echo $content->content; ?> So, you can use printf as <?php echo printf('%s',$content->content); ?>
So, if you are using objects, maybe you have to write the function that you have into your class that you were instanced before. So, the output had to be:
<?php echo printf('%s', $content->content() ); ?>

Please see that we have to end ->content() as a function that exists inside your class.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Upload file and form data to server using AngularJS and Web API I am trying to upload file and form data to server using Angular and Web API.I am using the following code.
Service:
 App.factory('myService', ['$http', function ($http) {
    return {
        uploadFile: function (url, file) {
            return $http({
               url: url,
               method: 'POST',
               data: file,
               headers: { 'Content-Type': undefined },
               transformRequest: angular.identity
            });
        },
        otherFunctionHere: function (url, stuff) {
            return $http.get(url);
        }
    };
}]);

Controller
  $scope.uploadFile = function() {
      var fileInput = document.getElementById('fileInput');
      fileInput.click();
       if(fileInput.files.length === 0) return;
       var file = fileInput.files[0];
       var payload = new FormData();
       payload.append("stuff", "some string");
       payload.append("file", file);
       myService.uploadFile('/api/CsxForm/Upload', payload).then(function(response){
        }).catch(function(response){
        });
    }

API
[Route("api/CsxForm/Upload")]
[HttpPost]
public IHttpActionResult UploadFile(string stuff, HttpPostedFileBase file)
{
         string fileName = Path.GetFileNameWithoutExtension(file.FileName);
         string extension = Path.GetExtension(file.FileName);
            //save the file
         try
         {
            file.SaveAs("//MyDrive/Folder/" + fileName + extension);
          }
         catch (IOException exc)
         {
            return Json(new { status = "error", message = exc.Message });
         }
          return Json("Uploaded");
}

But went I access the API, "No HTTP resource was found that matches the request URI". I got this as Response body. Can someone Help me fix this?? Thanks


text:
Q: php soap proxy failing in web service action call I am making a webservice call using proxy.
The SoapClient call which uses proxy works fine but the call to webservice function using the same SoapClient object is failing. When i asked the server people, they said they can see the first GET call but not the POST call.
Here is the code:
$context = stream_context_create(
array(
    'ssl' => array( 'SNI_enabled' => false, 'SNI_server_name' => $domain
    ),
    'http' => array(
        'proxy' => 'proxyurl:8080'
    )
)
);

$soapOptions = array(
    'trace' => true,
    'stream_context' => $context
);

try {
    $client = new SoapClient(WSDL_URL, $soapOptions);
}  catch (SoapFault $fault) {
    echo "SOAP Fault: (faultcode: {".$fault->faultcode."}, faultstring: {".$fault->faultstring."})", E_USER_ERROR;
} catch (Exception $e) {
    echo "SOAP Exception: (faultcode: {".$fault->faultcode."}, faultstring: {".$fault->faultstring."})", E_USER_ERROR;
}

echo "Calling Grant Role";
echo "<hr>";

$userName = "username";
$roleIdFromUser = "userrole";

try {
    $result = $client->GrantAffiliateUserRole(array('affiliateId' => AFFILIATEID, 'password' => AFFILIATEPASSWORD, 'username' => $userName, 'roleId' => $roleIdFromUser));
    echo "Success";
}  catch (SoapFault $fault) {
    echo "SOAP Proxy Fault: (faultcode: {".$fault->faultcode."}, faultstring: {".$fault->faultstring."})", E_USER_ERROR;
    echo "Failed Grant Fault";
} catch (Exception $e) {
    echo "SOAP Exception: (faultcode: {".$fault->faultcode."}, faultstring: {".$fault->faultstring."})", E_USER_ERROR;
    echo "Failed Grant Exception";
}

The output is:
object(SoapClient)#1 (4) { ["trace"]=> int(1) ["_stream_context"]=> resource(2) of type (stream-context) ["_soap_version"]=> int(1) ["sdl"]=> resource(4) of type (Unknown) }

Calling Grant Role

SOAP Proxy Fault: (faultcode: {HTTP}, faultstring: {Could not connect to host})256

Failed Grant Fault

Again, the webservice action call is not recognizing proxy that was used to make SoapClient call for WSDL.Any help?

A: I have got this solved. Since the Web service URL is HTTPS, just the SSL needs to be stream context and pass it along with the Proxy array to the WSDL call as below.
$context = stream_context_create(
array(
    'ssl' => array('SNI_enabled' => false)
    )
);

$soapOptions = array('proxy_host' => PROXY_HOST, 'proxy_port' => PROXY_PORT, 'stream_context' => $context);

$client = new SoapClient(WSDL_URL, $soapOptions);


text:
Q: What is army count of commander in Warzone? What is army count of commander in Warzone and how much army strength is needed to kill him?

A: A commander is worth 7 armies.
Thus he kills 4 while attacking in a normal game and needs to be attacked by 11 to be killed. If you commander is killed, You lose, and all of you territories become neutral.


text:
Q: How to implement seek on mp3 I am about to get into a project that involves decoding + playing an mp3 stream.
I have a Java decoder (JLayer), but as far as I can see it has no seek functionality (I don't use the built in player, I need to implement my own player).
Also, the stream is encrypted, so I need to decrypt + decode in real time - can't have an entire decrypted file.
So how do you approach seeking on mp3 stream? I would like to set a time value, and get the appropriate offset in the file to decode from.
Please also consider support for VBR.
Thanks

A: I've been looking in exactly the same thing. The JLayer code is somewhat messy. Just browsing through it convinced me that the mp3 decoding core was written (or taken from somewhere) and then ported to Java, then an extra -fairly unoptimal- layer was added. In any case. To seek have a look at the code in the player (http://code.google.com/p/jesuifoo/source/browse/trunk/src/javazoom/jlgui/basicplayer/BasicPlayer.java?r=23)
    /**
     * Skip bytes in the File inputstream. It will skip N frames matching to
     * bytes, so it will never skip given bytes length exactly.
     *
     * @param bytes
     * @return value>0 for File and value=0 for URL and InputStream
     * @throws BasicPlayerException
     */
    protected long skipBytes(long bytes) throws BasicPlayerException {
            long totalSkipped = 0;
            if (m_dataSource instanceof File) {
                    log.info("Bytes to skip : " + bytes);
                    int previousStatus = m_status;
                    m_status = SEEKING;
                    long skipped = 0;
                    try {
                            synchronized (m_audioInputStream) {
                                    notifyEvent(BasicPlayerEvent.SEEKING,
                                                    getEncodedStreamPosition(), -1, null);
                                    initAudioInputStream();
                                    if (m_audioInputStream != null) {
                                            // Loop until bytes are really skipped.
                                            while (totalSkipped < (bytes - SKIP_INACCURACY_SIZE)) {
                                                    skipped = m_audioInputStream.skip(bytes
                                                                    - totalSkipped);
                                                    if (skipped == 0)
                                                            break;
                                                    totalSkipped = totalSkipped + skipped;
                                                    log.info("Skipped : " + totalSkipped + "/" + bytes);
                                                    if (totalSkipped == -1)
                                                            throw new BasicPlayerException(
                                                                            BasicPlayerException.SKIPNOTSUPPORTED);
                                            }
                                    }
                            }
                            notifyEvent(BasicPlayerEvent.SEEKED,
                                            getEncodedStreamPosition(), -1, null);
                            m_status = OPENED;
                            if (previousStatus == PLAYING)
                                    startPlayback();
                            else if (previousStatus == PAUSED) {
                                    startPlayback();
                                    pausePlayback();
                            }
                    } catch (IOException e) {
                            throw new BasicPlayerException(e);
                    }
            }
            return totalSkipped;
    }

This routine illustrates how the bitstream is advanced without decoding.(m_audioInputStream.skip(...)). I don't know though whether it is skipped from the start (there is after all a initAudioStream call before), or from the current playposition.
VBR is no problem since the frames are skipped individually.
With respect to decryption, it shuoldn't matter since this routine skips individual frames as read from the inputstream. If the inputstream supports decoding it should wokr. How fast is of course another question. In that case it might be better to build an index of the mp3 so that you know to what position to jump and decode, but that is a slightly different topic: how to seek in an encrypted stream.


text:
Q: Stop Task when task run How can i totally stop a task when task running?
private async void button1_Click(object sender, EventArgs e)
{
  await Backup(file);
}

public async Task Backup(string File)
{
   await Task.Run(() =>
     {
       1)do something here

       2)do something here

       3)do something here

      });
}
private async void button2_Click(object sender, EventArgs e)
{
  <stop backup>
}

If say i want to stop task during 2nd thing is processing, and i click a button2 then the task will stop process
How do I cancel or end the task from button2_Click?

A: // Define the cancellation token source & token as global objects
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token;

//when button is clicked, call method to run task & include the cancellation token

private async void button1_Click(object sender, EventArgs e)
{
    token = source.Token;
    await Backup(file, token);
}

public async Task Backup(string File, CancellationToken token)
{
    Task t1 = Task.Run(()  =>
    {
        //do something here
    },
    token);
}

//cancel button click event handler
private async void cancelButton_Click(object sender, EventArgs e)
{
    if(source != null)
    {
        source.Cancel();
    }
}

//tasks
https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx

//CancellationToken
https://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken(v=vs.110).aspx


text:
Q: PHP code works on my localhost, but not on my webserver I have a problem, I am currently programming a small script, everything is working fine so far on my localhost and also on the webserver.
Except one page, this completely blocks the INSERT INTO commands and the SELECT commands in the While loop.
The database is 1:1 like on my localhost.
There are also no error messages displayed, not even with:
error_reporting(E_ALL);
ini_set('display_errors', '1');
I really don't know anymore, on the server all other pages, queries, entries are working.
Only on this page not, where is my error?
session_start();
require_once('assets/include/header.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
function random_string() {
    if(function_exists('random_bytes')) {
        $bytes = random_bytes(16);
        $str = bin2hex($bytes);
    } else if(function_exists('openssl_random_pseudo_bytes')) {
        $bytes = openssl_random_pseudo_bytes(16);
        $str = bin2hex($bytes);
    } else if(function_exists('mcrypt_create_iv')) {
        $bytes = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
        $str = bin2hex($bytes);
    } else {
        //Bitte euer_geheim_string durch einen zufälligen String mit >12 Zeichen austauschen
        $str = md5(uniqid('euer_geheimer_string', true));
    }
    return $str;
}

//Überprüfe auf den 'Angemeldet bleiben'-Cookie
if(!isset($_SESSION['userid']) && isset($_COOKIE['identifier']) && isset($_COOKIE['securitytoken'])) {
    $identifier = $_COOKIE['identifier'];
    $securitytoken = $_COOKIE['securitytoken'];

    $statement = $pdo->prepare("SELECT * FROM securitytokens WHERE identifier = ?");
    $result = $statement->execute(array($identifier));
    $securitytoken_row = $statement->fetch();

    if(sha1($securitytoken) !== $securitytoken_row['securitytoken']) {
        header("Location: login.php");
    } else { //Token war korrekt
        //Setze neuen Token
        $neuer_securitytoken = random_string();
        $insert = $pdo->prepare("UPDATE securitytokens SET securitytoken = :securitytoken WHERE identifier = :identifier");
        $insert->execute(array('securitytoken' => sha1($neuer_securitytoken), 'identifier' => $identifier));
        setcookie("identifier",$identifier,time()+(3600*24*365)); //1 Jahr Gültigkeit
        setcookie("securitytoken",$neuer_securitytoken,time()+(3600*24*365)); //1 Jahr Gültigkeit

        //Logge den Benutzer ein
        $_SESSION['userid'] = $securitytoken_row['user_id'];
    }
}

if(isset($_SESSION['userid'])){
    $userid = $_SESSION['userid'];
    $stmt = $pdo->prepare("SELECT * FROM users WHERE userid = ?");
    $stmt->execute([$userid]);
    $user = $stmt->fetch();
    extract($user);
}

if(isset($userid)){

    $stmt = $pdo->prepare("SELECT vorname FROM users WHERE userid = ?");
    $stmt->execute([$userid]);
    $rowUser = $stmt->fetch();
    $username = $rowUser['vorname'];

        $stmt = $pdo->prepare("SELECT coins FROM users WHERE userid = ?");
        $stmt->execute([$userid]);
        $coins = $stmt->fetch();
        extract($coins);
        $userCoins = $coins;
}

$page = $_GET['page'];

$stmt = $pdo->prepare("SELECT * FROM subthreads WHERE subThreadsID  = ?");
$stmt->execute([$page]);
$row = $stmt->fetch();
extract($row);

$threadName = $row['threadName'];
$threadContent = $row['threadContent'];
$createdComments = $row['created_at'];
$dateNow = date_create($createdComments, timezone_open('Europe/Berlin'));
$timeNow = time();
$seconds = strtotime($createdComments);
$diffSeconds = $timeNow - $seconds;
$date = date_format($dateNow, 'd.m.Y - H:i');

if($diffSeconds < 60){
    $diffSeconds = "Vor 1 Min.";
} elseif($diffSeconds <= 300){
    $diffSeconds = "Vor 5 Min.";
} elseif($diffSeconds <= 600){
    $diffSeconds = "Vor 10 Min.";
} elseif($diffSeconds <= 900){
    $diffSeconds = "Vor 15 Min.";
} elseif($diffSeconds <= 1200){
    $diffSeconds = "Vor 20 Min.";
} elseif($diffSeconds <= 1500){
    $diffSeconds = "Vor 25 Min.";
} elseif($diffSeconds <= 1800){
    $diffSeconds = "Vor 30 Min.";
} elseif($diffSeconds <= 2100){
    $diffSeconds = "Vor 35 Min.";
} elseif($diffSeconds <= 2400){
    $diffSeconds = "Vor 40 Min.";
} elseif($diffSeconds <= 2700){
    $diffSeconds = "Vor 45 Min.";
} elseif($diffSeconds <= 3000){
    $diffSeconds = "Vor 50 Min.";
} elseif($diffSeconds <= 3300){
    $diffSeconds = "Vor 55 Min.";
} elseif($diffSeconds <= 3600){
    $diffSeconds = "Vor 1 Std.";
} elseif($diffSeconds <= 7200){
    $diffSeconds = "Vor 2 Std.";
} elseif($diffSeconds <= 10800){
    $diffSeconds = "Vor 3 Std.";
} elseif($diffSeconds <= 14400){
    $diffSeconds = "Vor 4 Std.";
} elseif($diffSeconds <= 18000){
    $diffSeconds = "Vor 5 Std.";
} elseif($diffSeconds <= 21600){
    $diffSeconds = "Vor 6 Std.";
} elseif($diffSeconds <= 25200){
    $diffSeconds = "Vor 7 Std.";
} elseif($diffSeconds <= 28800){
    $diffSeconds = "Vor 8 Std.";
} elseif($diffSeconds <= 32400){
    $diffSeconds = "Vor 9 Std.";
} elseif($diffSeconds <= 36000){
    $diffSeconds = "Vor 10 Std.";
} elseif($diffSeconds <= 39600){
    $diffSeconds = "Vor 11 Std.";
} elseif($diffSeconds <= 43200){
    $diffSeconds = "Vor 12 Std.";
} elseif($diffSeconds <= 86400){
    $diffSeconds = date_format($dateNow, 'H:i');
} elseif($diffSeconds > 86400){
    $diffSeconds = "Vor 1 Tag";
} elseif($diffSeconds > 172800){
    $diffSeconds = "Vor 2 Tage";
} elseif($diffSeconds > 259200){
    $diffSeconds = "Vor 3 Tage";
} elseif($diffSeconds > 345600){
    $diffSeconds = "Vor 4 Tage";
} elseif($diffSeconds > 432000){
    $diffSeconds = "Vor 5 Tage";
}  elseif($diffSeconds > 518400){
    $diffSeconds = "Vor 5 Tage";
} else {
    $diffSeconds = date_format($dateNow, 'd.m.Y');
}

$stmt = $pdo->prepare("SELECT subThreadsID, threadsID FROM subthreads WHERE subThreadsID = ?");
$stmt->execute([$page]);
$rowName = $stmt->fetch();
$threadID = $rowName['threadsID'];

$stmt = $pdo->prepare("SELECT id, threadName FROM threads WHERE id = ?");
$stmt->execute([$threadID]);
$rowThreadName = $stmt->fetch();
$threadNameIndex = $rowThreadName['threadName'];

if(isset($_POST['addComment'])){
    $error = false;
    $comment = htmlentities($_POST['comment']);

    if(strlen($comment) == 0){
        $error = true;
    }

    if($comment == ""){
        $error = true;
    }

    if($error == false){
        $stmt = $pdo->prepare("INSERT INTO subComments (subThreadsID, username, userid, threadContent) VALUES (?,?,?,?)");
        $stmt->execute([$page, $username, $userid, $comment]);

    }

}

function random_chars($charNbr)
{
    $chars = array('default','primary','success','danger','warning');
    $randomchar = '';
    for($i=0;$i<$charNbr;++$i)
    {
        $randomchar .= $chars[rand(0,4)];
    }
    echo $randomchar;
}

?>

        <?php if(isset($msg)){echo $msg;} ?>

             <?php echo"{$threadNameIndex} /  gepostet von {$row['username']} · {$diffSeconds}"; ?>

<?php echo $threadName; ?>

<?php echo $threadContent; ?>

    <form method="POST">

    <textarea name="comment" class="form-control" row="3" style="font-size: 14px; height: 150px" placeholder="Was ist deine Meinung dazu...?" required></textarea>

    <button type="submit" name="addComment" class="btn btn-primary w-100" style="font-size: 14px">Senf abgeben!</button>
    </form>

        <?php
    $stmt = $pdo->prepare("SELECT * FROM subComments WHERE subThreadsID = ? ORDER BY created_at DESC");
    $stmt->execute([$page]);
    while($row = $stmt->fetch()){
    $createdComments = $row['created_at'];
    $dateNow = date_create($createdComments, timezone_open('Europe/Berlin'));
    $timeNow = time();
    $seconds = strtotime($createdComments);
    $diffSeconds = $timeNow - $seconds;
    $date = date_format($dateNow, 'd.m.Y - H:i');

    if($diffSeconds < 60){
        $diffSeconds = "Vor 1 Min.";
    } elseif($diffSeconds <= 300){
        $diffSeconds = "Vor 5 Min.";
    } elseif($diffSeconds <= 600){
        $diffSeconds = "Vor 10 Min.";
    } elseif($diffSeconds <= 900){
        $diffSeconds = "Vor 15 Min.";
    } elseif($diffSeconds <= 1200){
        $diffSeconds = "Vor 20 Min.";
    } elseif($diffSeconds <= 1500){
        $diffSeconds = "Vor 25 Min.";
    } elseif($diffSeconds <= 1800){
        $diffSeconds = "Vor 30 Min.";
    } elseif($diffSeconds <= 2100){
        $diffSeconds = "Vor 35 Min.";
    } elseif($diffSeconds <= 2400){
        $diffSeconds = "Vor 40 Min.";
    } elseif($diffSeconds <= 2700){
        $diffSeconds = "Vor 45 Min.";
    } elseif($diffSeconds <= 3000){
        $diffSeconds = "Vor 50 Min.";
    } elseif($diffSeconds <= 3300){
        $diffSeconds = "Vor 55 Min.";
    } elseif($diffSeconds <= 3600){
        $diffSeconds = "Vor 1 Std.";
    } elseif($diffSeconds <= 7200){
        $diffSeconds = "Vor 2 Std.";
    } elseif($diffSeconds <= 10800){
        $diffSeconds = "Vor 3 Std.";
    } elseif($diffSeconds <= 14400){
        $diffSeconds = "Vor 4 Std.";
    } elseif($diffSeconds <= 18000){
        $diffSeconds = "Vor 5 Std.";
    } elseif($diffSeconds <= 21600){
        $diffSeconds = "Vor 6 Std.";
    } elseif($diffSeconds <= 25200){
        $diffSeconds = "Vor 7 Std.";
    } elseif($diffSeconds <= 28800){
        $diffSeconds = "Vor 8 Std.";
    } elseif($diffSeconds <= 32400){
        $diffSeconds = "Vor 9 Std.";
    } elseif($diffSeconds <= 36000){
        $diffSeconds = "Vor 10 Std.";
    } elseif($diffSeconds <= 39600){
        $diffSeconds = "Vor 11 Std.";
    } elseif($diffSeconds <= 43200){
        $diffSeconds = "Vor 12 Std.";
    } elseif($diffSeconds >= 46800){
        $diffSeconds = date_format($dateNow, 'H:i');
    } elseif($diffSeconds > 86400){
        $diffSeconds = "Vor 1 Tag";
    } elseif($diffSeconds > 172800){
        $diffSeconds = "Vor 2 Tage";
    } elseif($diffSeconds > 259200){
        $diffSeconds = "Vor 3 Tage";
    } elseif($diffSeconds > 345600){
        $diffSeconds = "Vor 4 Tage";
    } elseif($diffSeconds > 432000){
        $diffSeconds = "Vor 5 Tage";
    }  elseif($diffSeconds > 518400){
        $diffSeconds = "Vor 5 Tage";
    } else {
        $diffSeconds = date_format($dateNow, 'd.m.Y');
    }

    echo'
';
    echo'
';
    echo'
'; ?>
            <div class="bd-callout bd-callout-<?php random_chars(1); ?>" style="font-size: 14px">
        <?php
        if(isset($userid)){
            echo"
{$row['username']} · {$diffSeconds}
";
        } else {
            echo"
{$row['username']} · {$diffSeconds}
";
        }
        echo"{$row['threadContent']}";
        ?>
        <?php
        echo'
';
        echo'
';
        echo'
';
        }
        ?>

<?php
require_once('assets/include/footer.php');
?>


text:
Q: systemd timer to start .sh script daily at 2 different hours I have a bourne shell script (at my NAS) that handles the ffmpeg recording of all my ipcams. For switching the record time (etc) of some cams, that sh script should be restarted daily at 2 different hours (07:00am and 10:00pm), which is configured in the bash script and works well.

*

*To start the sh script, I make use of systemd with the following .service file:
[Unit]
Description=record ipcams
After=tmp.mount network.target
Requires=network.target
RequiresMountsFor=/media/USB2
[Service]
Type=forking
PIDFile=/var/run/cams_record.pid
ExecStart=/bin/bash -c '/media/USB2/movie/cams/cams_record.sh'
TimeoutStopSec=1
Restart=always
[Install]
WantedBy=multi-user.target
So far so good. Now what I actually want, is to restart that script file daily at 07:00am and 10:00pm (or restart the previous mentioned .service at those two times) thus I thought to make use of a systemd timer. I created such a timer for 07:00 am (with the option: OnCalender=07:00)
Question is: having a (permanently running) service, how do I restart that service (and thus the script file) at 07:00am and 22:00pm. I can of course make use of 2 systemd timers (1 for 07:00am and 1 for 10:00pm), but is there a possibility to combine these; i.e. using 1 systemd timer for both times.

A: With a templates timers, you can do something like this
cat test@.timer
[Unit]
Description=test

[Timer]
OnCalendar=%i:00
Unit=test.service

[Install]
WantedBy=timers.target

Then :
systemctl daemon-reload

and
systemctl start test@07.service
systemctl start test@22.service

Source : https://fedoramagazine.org/systemd-template-unit-files/ and https://jason.the-graham.com/2013/03/06/how-to-use-systemd-timers/

A: You can use several OnCalendar in one timer, see documentation https://www.freedesktop.org/software/systemd/man/systemd.timer.html#OnCalendar=
[Unit]
Description=test

[Timer]
OnCalendar=07:00
OnCalendar=10:00
Unit=test.service

[Install]
WantedBy=timers.target


text:
Q: Monodevelop broken on Fedora? I have a little project that uses mono gtk-sharp, that I build under monodevelop on Fedora and Xamarin on Windows. I wanted to try a clean build, but now I get the following error in Fedora if i try an debug build:
System.TypeLoadException: Could not load type 'GLib.IgnoreClassInitializersAttribute' from assembly 'gtk-sharp'.
at AudioCuesheetEditor.MainClass.Main (System.String[] args) [0x003e1] in /media/Auslagerung/Projekte/AudioCuesheetEditor/src/AudioCuesheetEditor/MainClass.cs:120

If I build a "Release" build, everything works fine. But why does the debug build fail? I have installed all needed libraries. The project src is here:
http://sourceforge.net/p/audiocuesheet/code/HEAD/tree/

Can anybody help?
Thanks in advance ;).


text:
Q: How do I access the settings in first time wizard in E17? ... and other settings in general. I want to change the behavior of the mouse when hover on an icon, it will highlight instead of click (which is available from firs time setup). Also, I enable the effects, which is quite heavy for my machine and I want to turn it off. Where to adjust it?
I've just installed E17, so I'm still new to it.

A: E17/Enlightenment settings are accessed by clicking on the desktop and choosing 'Settings/Settings Panel' from the menu. The help page describing this is on their wiki page here: http://trac.enlightenment.org/e/wiki/Configuration


text:
Q: php geo ip loc does not work http://chir.ag/projects/geoiploc/
Hello, I am trying to set this up, but whenever I use include("geoiploc.php"); the page is blank and whenever I remove include("geoiploc.php"); I only see my IP address. I've uploaded geoiploc.php and index.php to a webhost that can run PHP.
If there is ANY other easier way to show country name by IP or any other way, which is it? Please I need this fast
So as I said, it only shows my IP whenever I remove include("geoiploc.php"); why?
You need this library: http://chir.ag/projects/geoiploc/autogen/geoiploc.tar.gz and this is the code to run the script:
include("geoiploc.php"); // Must include this

  // ip must be of the form "192.168.1.100"
  // you may load this from a database
  $ip = $_SERVER["REMOTE_ADDR"];
  echo "Your IP Address is: " . $ip . "
";

  echo "Your Country is: ";
  // returns country code by default
  echo getCountryFromIP($ip);
  echo "
\n";

  // optionally, you can specify the return type
  // type can be "code" (default), "abbr", "name"

  echo "Your Country Code is: ";
  echo getCountryFromIP($ip, "code");
  echo "
\n";

  // print country abbreviation - case insensitive
  echo "Your Country Abbreviation is: ";
  echo getCountryFromIP($ip, "AbBr");
  echo "
\n";

  // full name of country - spaces are trimmed
  echo "Your Country Name is: ";
  echo getCountryFromIP($ip, " NamE ");
  echo "
\n";

A: You can use the free MaxMind Geo Lite. Download the files here: http://www.maxmind.com/download/geoip/api/php/php-latest.tar.gz
Then download the Geo Country database from here: http://dev.maxmind.com/geoip/legacy/geolite
You can now use it like this:
<?php

    include("geoip.inc");

    function ipAddress(){
        if (!empty($_SERVER['HTTP_CLIENT_IP'])){ //check ip from share internet
            $ip=$_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ // proxy pass ip
            $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

    $gi = geoip_open("path/to/GeoIP.dat",GEOIP_STANDARD);

    echo geoip_country_name_by_addr($gi, ipAddress());
    // echo geoip_country_code_by_addr($gi, ipAddress()); <-- country code

    geoip_close($gi);

?>

UPDATE: to get the user's city you should download the top link and look for the file called sample_city.php to see some example code. You'll need to download this file: http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz and place it in the same directory as your php file. A quick example would be:
<?php

    include("geoipcity.inc");
    function ipAddress(){
        if (!empty($_SERVER['HTTP_CLIENT_IP'])){ //check ip from share internet
            $ip=$_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ // proxy pass ip
            $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
    $gi = geoip_open("GeoIPCity.dat",GEOIP_STANDARD);
    $record = geoip_record_by_addr($gi,ipAddress());
    print $record->country_code . " " . $record->country_code3 . " " . $record->country_name . "\n";
    geoip_close($gi);

?>


text:
Q: Remove single quote from just end of array element (String) in PHP I have array of 3000 elements which are like this
   Array[0]= 405adc92-cfad-4be6-9ad2-ca363eda4933
   Array[1]= 405adc92-cfad-4be6-9ad2-ca363eda4933

And I need to pass a variable in a function which require only a single quote at the beginning. I tried a solution on web which is pasting single quote on beginning and end aswell .like this
function add_quotes($str) {
   return sprintf("'%s'", $str);
}
$csv =  implode(',', array_map('add_quotes', $a));
 $myArray = explode(',', $csv);
echo gettype($myArray[1]);

so answer is like this
myArray[1]='405adc92-cfad-4be6-9ad2-ca363eda4933'

So what Could I do to get rid ?

A: could you not just add the ' at the beginning of each string, rather than first add too many of them and afterwards remove the wrongly placed?
foreach($myArray as $key => &$value) {
  $value = "'" . $value;
}

or (may be more readable as not by-reference)
foreach($myArray as $key => $value) {
  $myArray[$key] = "'" . $value;
}

A: You can use rtrim - http://uk1.php.net/manual/en/function.rtrim.php to achieve. The generic syntax is:
<?php
    $foo = 'my string\'';
    $bar = rtrim($foo, '\'');

    var_dump($foo); //shows my string'
    var_dump($bar); //shows my string

so in your case take the array values, then use rtrim($myArray['myKey'], '\'') - this should do it for you :)


text:
Q: How to access string object in array of JSON-array via PHP? I have searched for almost 30 minutes and still can't find the answer for my problem.
So, here is it:
I have an JSON-file called "localeDE.l", now I'm trying to print the objects to the website, "locale_name"(type: string) works, but "translations"(type: array) won't work.
My JSON file:
"locale_name": "DE",
"translations": [
    {"Welcome": "Willkommen",
     "Goodbye": "Auf Wiedersehen"}
]

Here my PHP file:
$file = file_get_contents('localeDE.l');
$locale = json_decode($file);
print_r($locale);
echo "Locale=" . $locale->{'locale_name'};
echo "Translations:";
echo "  Welcome:" . $locale->{'translations'}->{'Welcome'};
echo "  Goodbye:" . $locale->{'translations'}->{'Goodbye'};

I also tried something like (...) $locale->{'translations.Welcome'}; etc.
Can You help me?
- Felipe Kaiser

A: First the JSON like you typed it here is incomplete. It's missing both opening and closing curly braces.
It should be
{"locale_name": "DE",
 "translations": [
     {"Welcome": "Willkommen",
     "Goodbye": "Auf Wiedersehen"}
]}

The php to read it
$obj = json_decode($json, true);
//to read the locale name
echo $obj['locale_name'];
//to read the translation of welcome
echo $obj['tranlations'][0]['Welcome'];
//to read the tranlation of goodbye
echo $obj['translations'][0]['Goodbye'];

Cheers.

A: Figured it out!
Now I figured it out how it works! Thanks alot to you!
Additionals
Here are my code pieces:
$json = file_get_contents('localeDE.l');
$obj = json_decode($json, true);
echo $obj['locale_name'];
echo $obj['translations'][0]['Welcome'];
echo $obj['translations'][0]['Goodbye'];

And my JSON file is unrelevant, for those who are interested, see the answer of Makville above.
Thanks alot! :)


text:
Q: Ruby - Can Shoes GUI catch the wheel mouse? I'm trying to build a very simple vector drawing program. (In fact it's meant to be the base for others).
I've already implemented zooming and panning, but I'd like to do as it works in autocad for example, or sketchup.
That is, when you roll the wheel mouse, you zoom, and when you push it, you pan. (Actually this last feature is already working).
Problem is, how can I catch the wheel mouse with Shoes GUI for ruby?

A: For the very best of my knowledge, there is no such method. Tried searching the source etc.
However I took it as a proposal for shoes4 - please feel free to comment on the proposed DSL or just think of your own DSL - basically the way you'd want to use it because that's most likely the shoes way :-)
If I'm wrong and there is such a method, one of the guys in the shoes4 repo will know and I'll report back here.


text:
Q: many of the nltk package methods / tools are not working 1)I tried the code from the official book on nltk package named /Natural Language Processing' but it gives error
dt = nltk.DiscourseTester(['A student dances', 'Every student is a person'])
print(dt.readings())

I get the error

NLTK was unable to find the mace4 file!
  Use software specific configuration paramaters or set the PROVER9 environment variable.

2)I tried to use another code from the book:
from nltk import load_parser
parser = load_parser('drt.fcfg', logic_parser=nltk.DrtParser())
trees = parser.parse('Angus owns a dog'.split())
print(trees[0].node['sem'].simplify())

I got the error

AttributeError: module 'nltk' has no attribute 'DrtParser'

3)I tried the below code:
    from nltk.sem import cooper_storage as cs
sentence = 'every girl chases a dog'
trees = cs.parse_with_bindops(sentence, grammar='storage.fcfg')
semrep = trees[0].label()
cs_semrep = cs.CooperStore(semrep)
print(cs_semrep.core)

for bo in cs_semrep.store:
    print(bo)
cs_semrep.s_retrieve(trace=True)
for reading in cs_semrep.readings:
    print(reading)

It worked but still it gave the below error:

AttributeError: 'CooperStore' object has no attribute 'core'

4) I tried another code from book:
from nltk import load_parser
parser = load_parser('simple-sem.fcfg', trace=0)
sentence = 'Angus gives a bone to every dog'
tokens = sentence.split()
trees = parser.parse(tokens)
for tree in trees:
    print(tree.node['SEM'])

I got the below error:

NotImplementedError: Use label() to access a node label.

Please let me know what to do? Are these features deprecated because I heard that many of the features of nltk are. Please suggest a way out for all those features mentioned.

A: I found the answer, actually I was following the code from the book instead of NLTK's online version of book which is updated. So following the updated version solved the problems.


text:
Q: Magento 2 is adding tax value twice in AMT sent to Paypal While placing an order using Paypal as payment, Magento 2 is adding the total tax twice to the AMT (amount) sent to PayPal.
Here is what is sent to paypal :
'AMT' => 134.10,  // should be 114.10
'SHIPPINGAMT' => 5.00,
'ITEMAMT' => 89.10,
'TAXAMT' => 20.00,

Here is Paypal's error:
PayPal gateway has rejected request. The totals of the cart item amounts do not match order amounts (#10413: Transaction refused because of an invalid argument. See additional error messages for details).

The quote tax is set via a plugin :
<preference for="Magento\Tax\Model\Sales\Total\Quote\Tax" type="Vendor\Module\Model\Sales\Total\Quote\Tax"/>

Class :
class Tax extends \Magento\Tax\Model\Sales\Total\Quote\Tax{
    public function __construct(
        \Magento\Tax\Model\Config $taxConfig,
        \Magento\Tax\Api\TaxCalculationInterface $taxCalculationService,
        \Magento\Tax\Api\Data\QuoteDetailsInterfaceFactory $quoteDetailsDataObjectFactory,
        \Magento\Tax\Api\Data\QuoteDetailsItemInterfaceFactory $quoteDetailsItemDataObjectFactory,
        \Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory $taxClassKeyDataObjectFactory,
        CustomerAddressFactory $customerAddressFactory,
        CustomerAddressRegionFactory $customerAddressRegionFactory,
        \Magento\Tax\Helper\Data $taxData ) {
        $this->setCode('tax');
        parent::__construct($taxConfig, $taxCalculationService, $quoteDetailsDataObjectFactory, $quoteDetailsItemDataObjectFactory, $taxClassKeyDataObjectFactory, $customerAddressFactory, $customerAddressRegionFactory, $taxData
        );
    }

    public function collect(
        \Magento\Quote\Model\Quote $quote,
        \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment,
        \Magento\Quote\Model\Quote\Address\Total $total ) {
        $total->setTotalAmount('tax', 20);     //set fixed value for testing
        $total->setBaseTotalAmount('tax', 20); //set fixed value for testing
        return $this;
    }

}

When the payment is "Check / Money order" the Order's totals and tax are correct.

I have been trying to solve this issue over the last week but without any success.
Our Magento 2.3 instance doesn't have any other module and this is the only place the quote has been modified or even used.
Thanks

A: login in Magento admin section and navigate to
store -> configration -> sales -> Tax
Click on shopping cart display settings and make sure you have No for Display Full Tax Summary. If it is yes make it No.
After change configuration Clear cache.
Please find attachment


text:
Q: How do you access filesDir from non activity class in Kotlin I am trying to access filesDir from a class that is called by an activity. I always get null when I try to use applicationContext
What is the best way to access filesDir in this method? (Without passing through a parameter from the activity)
I have included the code below (minus imports)
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
        val viewPager: ViewPager = findViewById(R.id.view_pager)
        viewPager.adapter = sectionsPagerAdapter
        val tabs: TabLayout = findViewById(R.id.tabs)
        tabs.setupWithViewPager(viewPager)

        val kin = Kin()
        kin.init() //<--Here is the call from Main Activity

    }
}

The class below needs to be able to access filesDir
class Kin : Application() {

    init {
        instance = this
    }

    companion object {
        private var instance: Kin? = null
    }

    override fun onCreate() {
        super.onCreate()
    }

    fun init() { //<-- this function needs filesDir
        Log.d("test", applicationContext.filesDir.toString())
    }
}


text:
Q: Announce invisible alert Is there a way to announce a Successful message using an alert/status role without showing anything visible on the screen for the user?
I tried creating an alert div dynamically but the user could see the success text displaying on the screen. I need it to just be announced and don't give any visual feedback to the user.
   var newAlert = document.createElement("div");
   newAlert.setAttribute("role", "alert");
   newAlert.setAttribute("id", "alert");
   var msg = document.createTextNode('You have Successfully updated your phone number');
   newAlert.appendChild(msg);
   document.body.appendChild(newAlert);

A: You can hide it from the screen using CSS, with the off-screen technique.
If you are using bootstrap, there's a .sr_only class doing that. Otherwise, you can easily find the corresponding CSS code.
Basically it looks something like this:
.sr_only {
  width: 1px;
  height: 1px;
  overflow: hidden;
  position: absolute;
  left: -2px;
  top: -2px;
}

Don't use display:none, visibility:hidden or width/height:0, as those are also going to hide the message for screen readers, and as a consequence, the alert won't be spoken.
Note that you can't hide the message from the screen reader's display as known as virtual buffer. If you want to do so, the best you can do is removing the element from the DOM after a few seconds.
You must wait long enough for the message to be spoken entirely, as with some screen readers, speech is cut when the element is removed.

A: use css
.alert{
 display: none;
}

or
.alert{
 z-index: -100;
}


text:
Q: Reading colors of a rubik's cube using Opencv I have written a C++ program using OpenCV that can detect and highlight the edges of any object from a live video. But now I don't know how to extract the four corners of the cube from the many edges that are being detected in the video. So I am looking for some help here.
Here is the link of the paper that I am using as a guide for my this project.
http://www.cs.ubc.ca/~andrejk/525project/525report.pdf
You can find the program code for this paper in the link below. It's written in Python. (I am using C++ and I don't know Python)
http://www.cs.ubc.ca/~andrejk/525project/cubefinder.py
According to the paper the next step would be, 'edge segmentation with adaptive threshold.'
Which I don't really understand. And also I don't know how to extract the corners of the cube then.
The short summary of the method that I have used is as following.
1. Input from webcam
2. Apply Laplacian filter
3. Apply Hough Line Transform.
I get the following result.

Code
using namespace std;
using namespace cv;

Mat laplacianFilter(Mat image)
{
Mat hImage;

GaussianBlur(image,hImage,Size(3,3),0,0,BORDER_DEFAULT);
cvtColor(hImage,hImage,CV_RGB2GRAY);
Laplacian(hImage,hImage,CV_16SC1,3,1,0,BORDER_DEFAULT);
convertScaleAbs(hImage,hImage,1,0);

return hImage;
}

Mat hghTransform(Mat image, Mat &image2)
{
Mat lImage;

Canny(image,image,50,200,3);
cvtColor(image,lImage,CV_GRAY2BGR);

    vector<Vec4i> lines;
    HoughLinesP(image, lines, 1, CV_PI/180, 50, 50, 10 );
    for( size_t i = 0; i < lines.size(); i++ )
    {
        Vec4i l = lines[i];
        line( image2, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,255,0), 3, CV_AA);
    }

return lImage;
}

int main()
{
int c;

VideoCapture cap(0);

Mat image;
Mat image2;

namedWindow("hghtransform");
namedWindow("laplacianfilter");
namedWindow("cannyOutput");

while(1)
{
    cap>>image;
    cap>>image2;

    //Output
    imshow("laplacianfilter",laplacianFilter(image));
    imshow("cannyOutput",hghTransform(laplacianFilter(image),image2));
    imshow("hghtransform",image2);

    c=waitKey(33);

    if(c==27)
        return 0;

}

return 0;
}

A: Adaptive threshold will give you a clear line of edges which enables you to get 9 squares of a rubik side properly.
You can see a decent comparison of global and adaptive threshold here:
here: https://sites.google.com/site/qingzongtseng/adaptivethreshold
original image:

global threshold:

adaptive threshold:

For the corner, I am not sure whether it's stated in the paper, but I would do something like:
==> finding area like 1, 2, 3, 4 for upper-left, upper-right, lower-left, and lower-right corner respectively
==> with a template matching algorithm.

hope it helps.
note: you might want to have a background with less noise there. =)


text:
Q: Managing multiple NPM modules browser-side Okay, I've looked and looked and don't quite see a question that looks like mine, nor a project that quite addresses my need. This is probably because I'm doing something insane, and I am also asking for something difficult. But I wanted to see what others think.
I'm building my first large-scale single-page application. The way I've set it up is by breaking it up into a number of NPM modules. I like this because NPM provides a nice environment to build purely node-run unit tests in, a way to reuse some of my code for other projects we do at my company, and a forced separation of concerns. Here's the general idea:

*

*A core data model library

*A core UI library

*A psuedo-library that provides individual UI components based on the above two…

*…another of those…

*…etc for each sub-application of my application

*A very small central project that pulls all the components provided by the above together into an interface as necessary

This means a lot of libraries, and a number of dependencies that are common (Underscore, moment, EventEmitter2, etc).
Now I need to figure out how to get all that code into a browser. Ideally, I'd want something with some browserify characteristics (rolls modules and dependencies together into single files to cut down on resource callbacks), but has some of requirejs's asynchronous loading DNA (I'd rather not have to load my entire application up front; being able to call down chunks when the user navigates is useful).
I'm having trouble reconciling the above, though. I get what Require is trying to do, but every time I try to use it for already-built NPM modules (not AMD modules, though I'm happy to write that central project in an AMD-ish way) I get really confused and the sense that it's not really meant for me. For a single page application it seems like it's just going to resolve everything into one file anyway, since my dynamic resources are whole dependencies rather than individual files? And of course, Browserify is made with the sole intent of Hulk Smashing all your code into a single file. I could bundle each NPM module separately with Browserify, but then I'm duplicating the common dependencies for each.
I've looked at a bunch of other projects and they all seem to be addressing the client side more than the bundling side. What am I missing here?
[In pipe dream mode, I also like inject, partly because it's written by LinkedIn (who have a good reputation in my mind), but also for its localStorage caching.]


text:
Q: When playing tours authored in KML, is it possible to dynamically to control the camera? Using the Google Earth plugin AI, I want to play a tour authored in KML with the touring capability, but let the user modify the camera controls during the play.
Is it possible?

A: It depends on how much modification you want to allow.
Tour playback is designed to work with the user changing the orientation of the view (via dragging or the camera controls), but not the position. If the user stops changing the view for long enough, the camera will smoothly snap back to the default orientation for that point in the tour. The zoom and panning controls disappear during the tour, but if the user tries to change the camera position via other methods (like the keyboard), the tour will typically be paused.
The Earth API, however, allows you to absorb or change any of those event behaviors, since you can add a listener for mouse and keyboard events and prevent them from processing as usual or act on them in a completely different way.
If you haven't tried it, there's a tour example in the Google Code Playground where you can see what happens with different interactions based on the default event responses.
Finally, if you want really custom tour behavior -- like allowing certain kinds of movement of the camera away from the tour path even as the tour continues -- you will most likely need to write your own camera movement code. Getting the basics of this working isn't too difficult, but getting the right intuitive feel for that kind of interaction is difficult, and probably dataset-dependent. To get started, you can parse the KML directly, find the tour and the tour primitives it contains, and then use the regular camera controls you cited to move between those primitives, adding offsets for any user-supplied movements.
edit: the Earth API tour page cited in the question has an example of getting started with parsing the KML file by getting the plugin to do it for you. You can use this to implement the above suggestion by using the KML DOM walking code to find all the tour primitives (instead of halting as soon as a Tour element is found).
This isn't always the most efficient approach (plugin function calls have overhead, and meanwhile browsers have built-in XML parsing capabilities), but it may be the most straightforward way to start. For many tours, this approach would be perfectly sufficient.

A: It is possible, but pretty hard to implement and even harder to control well. I have been playing around with trying to do this for quite a while now. I have not had much success myself, but here are two example by others who have made some progress.
Firstly, the underlying principle they are using is based upon the TICK - a simple example of it is here
http://earth-api-samples.googlecode.com/svn/trunk/examples/event-frameend.html
The two example are :
http://maps.myosotissp.com/
and
http://racemyrace.com/race.php
Also, here is an example that used to work up until recently, I am not sure why it has stopped but it appears you can still read the JS being used. It is made by the same person who created the racemyrace website
http://www.thekmz.co.uk/GEPlugin/pathtour/v3/path_tour_v3.htm
If you happen to work something out, I would appreciate you creating a simple example page and sharing the link. It will probably take a while so if you could look up my email via profile and notify me that would be even better.
Good Luck!


text:
Q: SIGSEGV when reading config with libconfig I can't retrieve the user value from my config file using C and libconfig.
configreader.h
#include <stdio.h>
#include <string.h>
#include <libconfig.h>
#ifndef CONFIGREADER_H_INCLUDED
#define CONFIGREADER_H_INCLUDED

char *userreader(){
    static const char *inputfile = "/opt/plaininc/config/handler.conf";
    config_t configreader;
    const char *userconfig;
    if(! config_read_file(&configreader, inputfile)){
        config_destroy(&configreader);
        exit(EXIT_FAILURE);

    }
    if (config_lookup_string(&configreader, "handler.user", &userconfig)){
        config_destroy(&configreader);
        return userconfig;

    } else {
        config_destroy(&configreader);
        exit(EXIT_FAILURE);

    }
}

#endif

CONFIG.c
    #include <stdio.h>
#include <stdlib.h>
#include "configreader.h"

int main(){
    const char *user = userreader();
    printf("%s", user);
}

GDB:

Program received signal SIGSEGV, Segmentation fault. 0xb7e63496 in
  free () from /lib/i386-linux-gnu/libc.so.6

A: You need to initialize configreader using config_init(). Do:
config_t configreader;
const char *userconfig;
config_init(&configreader);
....


text: Q: Как вписать один SKShapeNode в границы другого SKShapeNode? Есть 2 SKShapeNode. 1 больше другого по размерам. Нужно вписать меньший по размеру в границы большего и передать ему координаты большего (что-бы позиция второго нода уже определялась координатами не сцены, а именно первого большого нода).


text:
Q: Why does a USB drive has a "Mac_OSX" folder when I use it on a Mac and then open it on a PC? Just curious as to why a folder named "Mac OSX" shows up on a USB drive / Folder after being used on a mac?

A: This question is answered quite thoroughly in this thread:-
Link to "What-is-macosxfolder" discussion on superuser.com
To summarise, it is a folder that the Mac uses to hold meta data/resource fork information.  It is hidden on the Mac but Windows displays it as a normal folder, much like the DS_Store files that can be left on Windows Network shares for Windows users to see if you browse the shares using a Mac.


text:
Q: How can I make a Wicket form save radio button state? I want to have a repeater like DataView or ListView. The first column of each row (named User ID) should be read from a List, and for each user ID, the program should dynamically create three radio buttons like these:

Requirements:

*

*The user must able to change selection of radio buttons.

*When the user clicks the submit button, radio values be displayed using the info("") method.

I've already done this by using this example, but when I click the submit button, old selections are shown, and the form gets reset to those old selections.

A: This example code might be helpful.

A: ListView doesn't play very well with form components, but it may work if you call ListView.setReuseItems(true);.


text:
Q: Display images in textview and make downloadable I get a html content from json with retrofit2.
json:
"content": " hello word! <img src="test.jpg">"

I want when the content is shown,images in content display like this :
enter image description here
there is button on center of image that after click on it , image downloaded and show like this :
enter image description here
what is the code for this purpose?

A: This is a snap of code that saves an image in internal storage of the device:
 public boolean saveImageToInternalStorage(Bitmap image) {
        try {
   // Use the compress method on the Bitmap object to write image to
   // the OutputStream
   FileOutputStream fos = context.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);

   // Writing the bitmap to the output stream
   image.compress(Bitmap.CompressFormat.PNG, 100, fos);
   fos.close();

   return true;
   } catch (Exception e) {
     Log.e("saveToInternalStorage()", e.getMessage());
     return false;
   }
}

Call this method in button's onClick i suppose.


text:
Q: Share instance between AutoFac containers I have an issue where I have a stateless service which has 2 AutoFac containers
I have a PriceService instance inside my container that is created the Main method of Program.cs
A second container is created inside my Startup.cs (unavoidable because different logic is required for setting up AutoFac for Web API)
This causes me an issue because when I go to resolve IPriceService I get a service that contains no data because a new instance is created by Startup
I have seen how to merge 2 containers together but how do I get hold of the Container that is created in my Program.cs Main method?
If I can get it I plan to create a new container that doesn't include IPriceService, then add my PriceService from the ServiceFabric container into my container that will be used by the Web API side
Has anyone ever tried anything like this?
Extra Info
My container has always been created in the Main method of Program.cs
I cant have 1 container because in order for AutoFac to be used for MVC/Controllers you need to integrate services that are only available in Startup classes
The startup class is not invoked at the right time so there is no way to get this extra information into my main container
Additional Note
I think the actual issue here may be a bit different, I am calling InstancePerCall when registering controllers.  This in turn seems to create a new instance of my service rather than using the existing one.  So maybe my question should be how can I avoid this?  I cant use a SingleInstance for controllers can I?

A: If you register your service in Program.cs Main, you can inject it to Service Fabric Service constructor:
public MySFService(IMyRegistredService myRegistredService, StatelessServiceContext context) : base(context)
{
    this.myRegistredService = myRegistredService;
}

Then on WebHost creation you can register this service in WebAPI:
new WebHostBuilder().UseKestrel()
    .ConfigureServices(services =>
    {
        services.AddSingleton(myRegistredService);
    })
    ...


text:
Q: OAuth2 with Hash query string, Imgur API I'm updating my desktop app, an Imgur client, for the upcoming deprecation of code/pin auth methods, by using a local web server to catch the redirect_url from the browser after the user authorizes access to the app. So I launch the URL in the browser, the user accepts, then Imgur redirects to

http://localhost:7710/myapp?state=auth#access_token=....&expires_in=
  etc

but the browser cuts the URL at # so all the variables are missing, and my app only receives "state=auth"
from Imgur's API docs:

The response_type Parameter token: This authorization flow will
  directly return the access_token and refresh_token via the redirect
  URL you specified during registration, in the form of hash query
  string parameters. Example:
  http://example.com#access_token=ACCESS_TOKEN&token_type=Bearer&expires_in=3600
The code and pin response types have been deprecated and will soon no
  longer be supported.
Imgur returns an access token to your application if the user grants
  your application the permissions it requested. The access token is
  returned to your application in the fragment as part of the
  access_token parameter. Since a fragment (the part of the URL after
  the #) is not sent to the server, client side javascript must parse
  the fragment and extract the value of the access_token parameter.

Clearly they haven't thought this through for desktop applications, or am I missing something?

A: Imgur stuff looks non standard, since response_type=token is a basic version of the implicit flow, which used to be the solution for single page pps.
These days all UI based flows should use Authorization Code Flow (PKCE) and response_type=code.
Since your app is acting as a (loopback) web server it will not receive the hash fragment parameters, which are only available to JavaScript code running in a browser.
One option that would enable you to get the full URL would be to login via the system browser and to use a Private URI Scheme to call back to the app.
The above link is a visual blog post to explain how this works, in case it is of interest.


text:
Q: Relation between Frobenius norm and L2 norm? Is there any relation between the Frobenius norm of a matrix and L2 norm of the vectors contained in this matrix.
Simply put, is there any difference between minimizing the Frobenius norm of a matrix and minimizing the L2 norm of the individual vectors contained in this matrix ?
Please help me understand this.

A: Let $A$ be an $m\times n$ matrix with rows $\boldsymbol{a}_1^T,\dots,\boldsymbol{a}_m^T$. That is
$$A=
\begin{bmatrix}
\rule[.5ex]{1.5em}{0.4pt} & \boldsymbol{a}_1^T &\rule[.5ex]{1.5em}{0.4pt} \\
\rule[.5ex]{1.5em}{0.4pt} &\boldsymbol{a}_2^T& \rule[.5ex]{1.5em}{0.4pt} \\
&\vdots& \\
\rule[.5ex]{1.5em}{0.4pt} & \boldsymbol{a}_m^T &\rule[.5ex]{1.5em}{0.4pt}
\end{bmatrix}$$
The squared Frobenius norm is
$$\|A\|_F^2=Tr(AA^T)=Tr\left(
\begin{bmatrix}
\boldsymbol{a}_1^T\boldsymbol{a}_1 & \boldsymbol{a}_1^T\boldsymbol{a}_2& \dots & \boldsymbol{a}_1^T \boldsymbol{a}_m \\
\vdots & \vdots & \ddots & \vdots\\
\boldsymbol{a}_m^T\boldsymbol{a}_1 & \boldsymbol{a}_m^T\boldsymbol{a}_2& \dots & \boldsymbol{a}_m^T \boldsymbol{a}_m
\end{bmatrix}
\right)=\sum_{i=1}^m\boldsymbol{a}_i^T\boldsymbol{a}_i=\sum_{i=1}^m\|\boldsymbol{a}_i\|_2^2$$

A: Consider the following matrix:
$$A=\begin{bmatrix}1 &0\\0&1\end{bmatrix}$$
The Frobenius norm is:
$$||A||_F=\sqrt{1^2+0^2+0^2+1^2}=\sqrt 2$$
But, if you take the individual column vectors' L2 norms and sum them, you'll have:
$$n=\sqrt{1^2+0^2}+\sqrt{1^2+0^2}=2$$
But, if you minimize the squared-norm, then you've equivalence. It's explained in the @OriolB answer.

A: Given a matrix $A \in \mathbb{K}^{n \times m}$, the squared Forbenius norm is defined as:
$||A||_F^2 := \sum_i^n \sum_j^m(a_{ij})^2 = Tr(A^TA)$,
observe the similarity to the squared $l_2$ norm for a vector $a \in \mathbb{K}^n$:
$||a||_2^2 := \sum_i^n(a_i)^2 = a^Ta$,
so we can rewrite the Frobenius norm as sum of squared $l_2$ norms of the vectors:
$||A||_F^2 = \sum_j^M ||a_j||_2^2 = \sum_j^M a_j^Ta_j$,
where $a_j \in \mathbb{K}^n$ are the column vectors of $A$. Thus if you minimize the squared norm it is equivalent.


text:
Q: Java script: Recursively walk the Dom for an associated HTML file and print the type of elements encountered I want to write a simple JavaScript program that will recursively walk the
DOM for an associated HTML file and print the types of the elements encountered
(embedded data need not be printed), indented to reflect the hierarchical nature of the HTML document.
I don't know what's wrong with my code but the recursive part does not give the right output.
Any help would be greatly appreciated. Thanks.
Output
Top 3 Channel 3 Thai actresses:

    1.Yaya Urassaya
    2.Kimberly Ann Voltemas
    3.Margie Rasri Balenciaga

[object Text], nodeName: #text, nodeType: 3, innerHTML: undefined
[object Text], nodeName: #text, nodeType: 3, innerHTML: undefined
[object HTMLLIElement], nodeName: LI, nodeType: 1, innerHTML: Yaya Urassaya
[object Text], nodeName: #text, nodeType: 3, innerHTML: undefined
[object Text], nodeName: #text, nodeType: 3, innerHTML: undefined
[object HTMLLIElement], nodeName: LI, nodeType: 1, innerHTML: Kimberly Ann Voltemas
[object Text], nodeName: #text, nodeType: 3, innerHTML: undefined
[object Text], nodeName: #text, nodeType: 3, innerHTML: undefined
[object HTMLLIElement], nodeName: LI, nodeType: 1, innerHTML: Margie Rasri Balenciaga
[object Text], nodeName: #text, nodeType: 3, innerHTML: undefined

Correct Output
Top 3 Channel 3 Thai actresses:

    1.Yaya Urassaya
    2.Kimberly Ann Voltemas
    3.Margie Rasri Balenciaga

[object Text], nodeName: #text, nodeType: 3, innerHTML: undefined
[object HTMLLIElement], nodeName: LI, nodeType: 1, innerHTML: Yaya Urassaya
[object Text], nodeName: #text, nodeType: 3, innerHTML: undefined
[object HTMLLIElement], nodeName: LI, nodeType: 1, innerHTML: Kimberly Ann Voltemas
[object Text], nodeName: #text, nodeType: 3, innerHTML: undefined
[object HTMLLIElement], nodeName: LI, nodeType: 1, innerHTML: Margie Rasri Balenciaga
[object Text], nodeName: #text, nodeType: 3, innerHTML: undefined

My HTML file
    <!doctype html>

 Top 3 Channel 3 Thai actresses:

Yaya Urassaya

Kimberly Ann Voltemas

Margie Rasri Balenciaga

My Javascript file
 var element = document.getElementById("idDiv");

 function printNodeInfo(node)
 {
   element.innerHTML += node;
   element.innerHTML += ", nodeName: " + node.nodeName;
   element.innerHTML += ", nodeType: " + node.nodeType;
   element.innerHTML += ", innerHTML: " + node.innerHTML;
   element.innerHTML += "
";
 }

 // Get a handle of the ordered-list node.
 var orderedlistNode = document.getElementsByTagName("ol")[0];
 theDOMElementWalker(orderedlistNode);

 function theDOMElementWalker(node)
 {
   if (node.nodeType == 1)
   {
      node = node.firstChild;

      while (node)
      {
        theDOMElementWalker(node);
        printNodeInfo(node);
        node = node.nextSibling;
      }
   }
 }
 element.innerHTML += "
";

A: The problem is, even though it is not visible, there could be empty text nodes between elements in the dom tree, take a markup like
 content
, now between the div and span opening there is a space, which will create a text node in the dom tree, so you can to exclude the text node if it is empty to get your expected result.

var element = document.getElementById("idDiv");

function printNodeInfo(node) {
  if (node.nodeType == Node.TEXT_NODE && !node.nodeValue.trim()) {
    return;
  }
  element.innerHTML += node;
  element.innerHTML += ", nodeName: " + node.nodeName;
  element.innerHTML += ", nodeType: " + node.nodeType;
  element.innerHTML += ", innerHTML: " + node.innerHTML;
  element.innerHTML += "
";
}

// Get a handle of the ordered-list node.
var orderedlistNode = document.getElementsByTagName("ol")[0];
theDOMElementWalker(orderedlistNode);

function theDOMElementWalker(node) {
  if (node.nodeType == 1) {
    node = node.firstChild;

    while (node) {
      theDOMElementWalker(node);
      printNodeInfo(node);
      node = node.nextSibling;
    }
  }
}
element.innerHTML += "
";

Top 3 Channel 3 Thai actresses:

Yaya Urassaya

Kimberly Ann Voltemas

Margie Rasri Balenciaga


text:
Q: How to convert ArrayList to JSON object public ArrayList<String> convertJsonToJsonObject(){

    ArrayList<String> mylist = new ArrayList<String> ();

    mylist.add("abc");
    mylist.add("cfd");
    mylist.add("ert");
    mylist.add("fg");
    mylist.add("ujk");
    mylist.add("wer");

    mylist.add("dvb");
    mylist.add("ert");

    System.out.println("JSONObject :: "+(JSONObject)JSONSerializer.toJson(mylist));
}

I am having error at .toJson() method, I am not sure what is the mistake I am making.

A: JSONArray jsArray = new JSONArray(mylist);

Or
Gson gson = new Gson();
String jsonArray = gson.toJson(mylist);

Get java-json.jar and Gson.jar here

A: gson.toJson(object);

Gson Google Group

A: ArrayList<Domain> list = new ArrayList<Domain>();
list.add(new Domain());
list.add(new Domain());
list.add(new Domain());
String json = new Gson().toJson(list);

A: You can use the GSON library to accomplish this.
 ArrayList<String> mylist = new ArrayList<String> ();
 mylist.add("abc");
 mylist.add("cfd");
 mylist.add("ert");
 mylist.add("fg");
 mylist.add("ujk");
 String json = new Gson().toJson(mylist);

You can refer to the GSON User Guide for more support.

A: List<String> bibo = new ArrayList<String>();
bibo.add("obj1");
bibo.add("obj2");
bibo.add("obj3");
String json = new Gson().toJson(bibo);


text:
Q: Firebase App Hangs At Test Phase In Google Cloud Build Cross-posting from Reddit, but in summary- I'm trying to setup a React app using Firestore for data storage and GCB for CI/CD. However, GCB hangs in the testing phase when I push new code using Firestore.
I've done some basic debugging-

*

*It hangs when I try reading from Firestore, but in this commit, where I only write data, it built just fine.

*In the tests I added to check my interaction with Firestore, they all passed and the build log showed that it was able to read from Firestore just fine. It just, y'know, doesn't go anywhere after that.
Step #1: > react-scripts test --watchAll=false --detectOpenHandles
Step #1:
Step #1: PASS src/IdeaTable/IdeaTable.test.tsx
Step #1: PASS src/models/IdeasService.test.ts
Step #1:   â— Console
Step #1:
Step #1:     console.log src/models/IdeasService.test.ts:6
Step #1:       [ { description: 'Set up personal website, mostly for this but also for hosting Calibre',
Step #1:           slug: 'setup-portfolio',
Step #1:           summary: 'Set up portfolio',
Step #1:           id: 'wvQOj2m3zFNpwvdZVAnr' }]
Step #1:
Step #1: PASS src/App.test.tsx
Step #1:
Step #1: Test Suites: 3 passed, 3 total
Step #1: Tests:       5 passed, 5 total
Step #1: Snapshots:   1 passed, 1 total
Step #1: Time:        5.115s
Step #1: Ran all test suites.

As noted in that Reddit post, my current best hypothesis is that this issue is caused by the connection to Firebase staying open and keeping things from finishing, but I don't know how to fix that.


text:
Q: Facing error while setting the ringtone permanently I want to change my call ringtone permanently which will be invoked
from SD card and that ringtone should work more then one time.
I am using the following code:
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE, Note);

A: Add android.permission.WRITE.SETTINGS permission to your manifest file as your exception specifies that


text:
Q: ISODate in --queryFile I use the below mongodump code to dump records based on a date, in an .sh file:
$MONGODUMP_PATH -h $MONGO_HOST:$MONGO_PORT
-d $MONGO_DATABASE  -c $MONGO_COLLECTION
--queryFile subset.json

subset.json:
{ "TheDate": { "$gte": new Date(new Date().setDate(new Date().getDate() - 1)) } }

That does not work, and produces an error:
Failed: error parsing query as json: invalid character '.' after constructor argument

But if I change subset.json to include a static date value, it works:
{ "TheDate": { "$gte": ISODate("2016-06-14T07:12:23.051Z") } }

Where ISODate("2016-06-14T07:12:23.051Z") equals new Date(new Date().setDate(new Date().getDate() - 1)) as previously.
But I would need a dynamic value for date, as in the first case.
Have been looking for a solution online but cant find any...
Any ideas?
Best Regards

A: Hope it working for me !!!
The problem is your query is not valid JSON as it contains JS expressions to be evaluated (your calculations with the date).
In addition I did (quick & dirty) something similar with node, i.e. created a file query.js with this content which essentially creates your query JSON and writes it to the console
var oid = Math.floor(new Date(new Date().getTime() - 1000 * 60 * 60 * 24) / 1000).toString(16) + "0000000000000000";
console.log('{ "_id": { "$gte": new ObjectId("' + oid + '") } }');
so that you now can use it in your shell like so
mongoexport ... --query "$(node query.js)" ...
Please refer below link,
Find 15 mins data with ObjectID field


text:
Q: Improving Performance of an XY Monte Carlo I normally write my Monte Carlo codes in Fortran for speed, but I was doing some quick and dirty work and wrote one in Mathematica for the XY model on a square lattice (see Kosterlitz-Thouless Transition).
Monte Carlo is normally all about speed, since we are usually interested in very large systems (i.e. the "thermodynamic limit"). I usually use Mathematica for quick and dirty calculations and for its graphical capabilities, and rarely have considered too carefully the performance of my code. I'm curious if anyone can point out any major shortfalls in this code.
(*parameters*)
L = 20;
T = 1.0;
\[Alpha] = 1.;
pi = N@\[Pi];

(*acceptance rate array*)
accepts = ConstantArray[1, L^2];

(*mod for periodic boundaries*)
mod[n_] := 1 + Mod[n - 1, L]

(*lists of all lattice indexes *)
pos = Flatten[Table[{i, j}, {i, L}, {j, L}], 1];

(*list of neighbors of site (i,j)*)
neighbors = Table[{{i, mod[j + 1]}, {mod[i + 1], j}, {i, mod[j - 1]}, {mod[i - 1], j}}, {i, 1, L}, {j, 1, L}];

(*initialized lattice of 2d spins*)
XY = Map[Normalize, RandomReal[{-1., 1.}, {L, L, 2}], {-2}];

(*metropolis update for site (i,j)*)
MCUpdate[{i_, j_}] := (
  v = XY[[i, j]]; (*current vector*)
  u = RotationMatrix[\[Alpha] RandomReal[{-pi,pi}]].v; (*new proposed vector*)
  dE = (Total@Extract[XY, neighbors[[i, j]]]).(u - v); (*change in energy by changing to new vector*)
  n = j + (i - 1) L;
  If[RandomReal[] < Min[1, Quiet@Exp[-dE/T]],
   (*update vector if Metropolis condition is satisfied*)
   XY[[i, j]] = u;
   accepts[[n]] = 1
   ,
   (*reject update*)
   accepts[[n]] = 0
   ]
  )

(*performs n sweeps of the lattice*)
Sweep[n_] := Do[
  MCUpdate /@ pos;
  (*make sure everything is normalized*)
  Map[Normalize, XY, {-2}];
  If[Mean[accepts] < 0.45, \[Alpha] *= .95,
   If[Mean[accepts] > 0.55, \[Alpha] *= 1.05]];
  , n]

Some basic explanations:

*

*accepts tracks the last L^2 attempts to update one of the variables, so that the magnitude of the proposed changes, \[Alpha], can be adjusted such that the acceptance rate stays around 0.5.

*MCUpdate proposes a rotation to the vector at site (i,j), computes the change in energy dE due to this change, and then applies the Metropolis condition to determine whether to accept or reject with probability min(1,exp(-dE/T)) where T is the temperature

If you'd like to play with this, the following function will find all the vortices and color them:
(* list of indexes for each plaquette*)
plaq = Flatten[Table[{{i, j}, {i, mod[j + 1]}, {mod[i + 1], mod[j + 1]}, {mod[i + 1], j}}, {i, L}, {j, L}], 1]; (*find vortices and color them*)
vortexcolors = {Blue, Transparent, Red};
vortex := Table[
  p = plaq[[i]];
  spins = Extract[XY, plaq[[i]]];
  \[CapitalDelta] = Round@Sum[
     s1 = spins[[j]]~Append~0; s2 = spins[[1 + Mod[j, 4]]]~Append~0;
     Sign[Cross[s1, s2].{0, 0, 1}] ArcCos[s1.s2]/(2 \[Pi])
     ,
     {j, 4}];
  Graphics[{vortexcolors[[\[CapitalDelta] + 2]], Disk[p[[1]] - {.5, .5}, 0.25]}], {i, L^2}]

and this will allow you to plot all the spins, starting from a random configuration and "sweeping" the lattice some times to come to thermal equilibrium:
(*random starting configuration*)
XY = Map[Normalize, RandomReal[{-1., 1.}, {L, L, 2}], {-2}];
(*arrows to represent vectors*)
plotXY[col_] := (
  Map[(p = First@Position[XY, #] - {1, 1}; Graphics[{col, Arrow[{p, p + #/1.5}]}]) &, XY, {-2}]
  )
(*100 monte carlo sweeps*)
Sweep[100];
(*plot the configuration with vortices and square lattice grid*)
p1 = {plotXY[Black], vortex};
grid = Graphics[{Lighter@Red, Line[#]}] & /@ (Table[{{i, 0}, {i, L}}, {i, 0, L - 1}]~Join~Table[{{0, i}, {L, i}}, {i, 0, L - 1}]);
Show[{grid, p1}, PlotRange -> {{-1, L}, {-1, L}}]

Edit: As a bonus, is there a better way than Quiet@Exp[-dE/T] to deal with the error that Exp[-large number] cannot be represented by machine precision numbers? I would expect it to simply output zero.

A: You can use the RuntimeTools`Profile function, shown here, to figure out which parts need optimization the most. It's better to compile everything, if possible, but it is also possible to compile just the functions that need it the most.
Applying this function to 100 iterations of your code, we get

RotationMatrix really stands out here, so we can replace it by
rotationMatrix = Compile[{th}, {
    {Cos[th], -Sin[th]},
    {Sin[th], Cos[th]}
    },
   CompilationTarget -> "C",
   RuntimeOptions -> "Speed"
   ];

This simple change brings the total time down from 9.3 seconds to 5.8 seconds.
Predefining those matrices outside the loop using
rotmats = Map[rotationMatrix, α RandomReal[{-pi, pi}, {L, L}], {2}];

and inside the loop u = rotmats[[i, j]].v brings the time down to 5.0.
Proceeding down the list of things that take time, we find that the condition in the If statement takes some time.
accept = Compile[{dE, T},
   RandomReal[] < Min[1, Exp[-dE/T]],
   CompilationTarget -> "C",
   RuntimeOptions -> "Speed"
   ];

brings the time down to 4.3.
Keep in mind that not all functions are compilable, a list of functions that are compilable is available here. When in doubt whether the code is entirely compilable, use CompiledFunctionTools`CompilePrint and check for calls to the main evaluator. Sometimes it's worth it to rewrite some code just to make it compilable.
Others will show you more optimizations, I'm sure, I just wanted to share this way of finding opportunities for optimizations.

A: Here is a compiled version of Sweep that employs complex numbers instead of 2-vectors and rotation.
cSweep = Compile[{{XY0, _Complex, 1}, {\[Alpha]0, _Real}, {T, _Real}, {n, _Integer},
    {top, _Integer, 1}, {bottom, _Integer, 1}, {left, _Integer, 1}, {right, _Integer, 1}
    },
   Block[{XY, accepts, rand, \[Phi], u, v, z, dE, m, lo, hi, \[Alpha]},
    m = Length[XY0];
    lo = 0.45 m;
    hi = 0.55 m;
    XY = XY0;
    \[Alpha] = \[Alpha]0;
    Do[
     accepts = 0.;
     rand = RandomReal[{0., 1.}, m];
     \[Phi] = RandomReal[\[Alpha] {-Pi, Pi}, m];
     Do[
      v = Compile`GetElement[XY, i];
      u = v Exp[I Compile`GetElement[\[Phi], i]];
      z = Plus[
        Compile`GetElement[XY, Compile`GetElement[top, i]],
        Compile`GetElement[XY, Compile`GetElement[bottom, i]],
        Compile`GetElement[XY, Compile`GetElement[left, i]],
        Compile`GetElement[XY, Compile`GetElement[right, i]]
        ];
      dE = Re[Conjugate[z] (u - v)];
      If[Compile`GetElement[rand, i] < Exp[Min[Max[-700., -dE/T], 0.]],
       XY[[i]] = u;
       accepts++;
       ];
      , {i, 1, m}];
     If[accepts < lo,
      \[Alpha] *= .95;
      ,
      If[accepts > hi, \[Alpha] *= 1.05];
      ];
     , {n}];
    XY
    ],
   CompilationTarget -> "C",
   RuntimeOptions -> "Speed"
   ];

Usage example:
L = 20;
T = 1.0;
\[Alpha] = 1.;
With[{idx = Partition[Range[L^2], L]},
  bottom = Flatten[RotateLeft[idx]];
  top = Flatten[RotateRight[idx]];
  right = Flatten[idx[[All, RotateLeft[Range[L]]]]];
  left = Flatten[idx[[All, RotateRight[Range[L]]]]];
  ];
XY0 = Exp[I RandomReal[{-Pi, Pi}, L^2]];

XY = cSweep[XY0, \[Alpha], T, 100000, top, bottom, left, right]; // AbsoluteTiming // First

3.3154

Please double-check whether the implementation is correct.
Probably it would be more efficient to adjust the algorithm such that all entries of XY are modified at once. But of course, the rejection step has to be adjusted accordingly in order to guarantee the same equilibrium probability distribution for the stochastic process.


text:
Q: Access Requests I have recently been made aware of a gaping security flaw within access requests on sharepoint online. Some of the data on our site is used for reference material and not allowed for download. The users that require access to these files are granted View-Only access. Several users have found a way to bypass the View-Only permissions. They click share the doc, attempt to share it with themselves, sharepoint auto generates an email.(sends one to admin and one to user who made access request) The user then just needs to open the email and click the url within the message. They can then view and save the file. All with View-Only permissions. I had one guy suggest I disable access requests.. I don't want to disable sharing on sharepoint, I just want the permission levels to work correctly. Hopefully I am just configuring them wrong.

A: As far as I know you don't have the option to disable downloading documents. You can make it inconvenient at most.
I do agree that the documentation states it differently for view permissions:

View pages, items, and documents. Any document that has a server-side
  file handler can be viewed in the browser but not downloaded. File
  types that do not have a server-side file handler (cannot be opened in
  the browser), such as video files, .pdf files, and .png files, can
  still be downloaded.

If you really want to be secure, check out Information Rights Management. That gives you far more control on the content.


text:
Q: java.net.MalformedURLException: Unsupported protocol: remoting-jmx I want to use Java client with JBoss 6.4.0 EAP. I tested this code:
public void testConnection() throws Exception
    {

        System.out.println("Starting lookup ...");

        ObjectName mBeanName = new ObjectName("java.lang:type=Runtime");
        String attributeName = "StartTime";

        String host = "104.233.103.41";
        int port = 9999;  // management-native port

        String urlString = System.getProperty("jmx.service.url", "service:jmx:remoting-jmx://" + host + ":" + port);
        JMXServiceURL serviceURL = new JMXServiceURL(urlString);
        JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
        MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();

        Object attrVal = connection.getAttribute(mBeanName, attributeName);
        System.out.println("Value via JMX: " + new Date((Long) attrVal));

    }

My project is Maven based so I added these dependencies:
   <dependencies>
        <dependency>
            <groupId>org.jboss.as</groupId>
            <artifactId>jboss-as-ejb-client-bom</artifactId>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.jboss.as</groupId>
            <artifactId>jboss-as-jms-client-bom</artifactId>
            <type>pom</type>
        </dependency>
    </dependencies>

But I get this error when I run the code:
java.net.MalformedURLException: Unsupported protocol: remoting-jmx
    at javax.management.remote.JMXConnectorFactory.newJMXConnector(JMXConnectorFactory.java:359)
    at javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:269)

Into EAP-6.4.0/bin/client I found this description:
jboss-client.jar is a combined client jar for JBoss EAP 6, for use in non-maven environments. This jar should be used
with standalone clients only, not with deployments are that deployed to an JBoss EAP 6 instance.
This jar contains the classes required for remote JMS and EJB usage, and consists of the following shaded artifacts:
org.jboss.spec.javax.jms:jboss-jms-api_1.1_spec
org.jboss.spec.javax.transaction:jboss-transaction-api_1.1_spec
org.jboss.spec.javax.ejb:jboss-ejb-api_3.1_spec

org.jboss:jboss-ejb-client
org.jboss:jboss-remote-naming
org.jboss.logging:jboss-logging
org.jboss.marshalling:jboss-marshalling
org.jboss.marshalling:jboss-marshalling-river
org.jboss.remoting3:jboss-remoting
org.jboss.remoting3:remoting-jmx
org.jboss.sasl:jboss-sasl
org.jboss.xnio:xnio-api
org.jboss.xnio:xnio-nio
org.jboss.netty:netty
org.hornetq:hornetq-core-client
org.hornetq:hornetq-jms-client

Maven users should not use this jar, but should use the following BOM dependencies instead
<dependencies>
    <dependency>
        <groupId>org.jboss.as</groupId>
        <artifactId>jboss-as-ejb-client-bom</artifactId>
        <type>pom</type>
    </dependency>
    <dependency>
        <groupId>org.jboss.as</groupId>
        <artifactId>jboss-as-jms-client-bom</artifactId>
        <type>pom</type>
    </dependency>
</dependencies>

This is because using maven with a shaded jar has a very high chance of causing class version conflicts, which is why
we do not publish this jar to the maven repository.
But again i get this error. Can you propose some solution?

A: Add a dependency to the remoting-jmx protocol, i.e. org.jboss.remoting3:remoting-jmx as per https://developer.jboss.org/thread/199914?tstart=0
<dependency>
    <groupId>org.jboss.remoting3</groupId>
    <artifactId>remoting-jmx</artifactId>
    <version>1.0.1.Final</version>
</dependency>

A complete and working POM :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.jboss.as</groupId>
            <artifactId>jboss-as-ejb-client-bom</artifactId>
            <type>pom</type>
            <version>7.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.as</groupId>
            <artifactId>jboss-as-jms-client-bom</artifactId>
            <type>pom</type>
            <version>7.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.remoting3</groupId>
            <artifactId>remoting-jmx</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

Running the maven build with a JBoss server running on local host:
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running test.ATest
Starting lookup ...
Dec 16, 2015 6:25:50 PM org.xnio.Xnio <clinit>
INFO: XNIO Version 3.0.7.GA
Dec 16, 2015 6:25:50 PM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.0.7.GA
Dec 16, 2015 6:25:50 PM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 3.2.14.GA
Value via JMX: Wed Dec 16 18:14:05 CST 2015
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.89 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0


text:
Q: Add SQL Analysis Services to a existing SharePoint Farm Our SharePoint Farm is based on a failover SQL cluster (MS SQL 2012 Standard). The problem is, that the Analysis Services were not installed with the database engine.
If I'm understanding right, it's not supported to add/remove any features to an existing failover cluster at all?
I need some ideas/options to get the Analysis Service available to the farm.

A: Analysis services is a Completely different application than your clustered DB engine.  you can have clustered and non-clustered apps on the same server.  I don't recommend that, but its possible.  With PowerPivot you point at discrete installations tbat are neither load balanced nor clustered.
I personally would stand up a dedicated server/instance for analysis services if resources are available to support it.


text:
Q: How to get IP address through www.ipaddresslocation.org in Blackberry I'm a newbie in Blackberry programming.
I'm trying get IP address, County, city, state/province through www.ipaddressslocation.org
My source :
String url = "http://www.ipaddresslocation.org/my-ip-address.php";
    // HTTP connection
    HttpConnection httpConnection = null;
    // Stream connection
    StreamConnection streamConnection = (StreamConnection) Connector
            .open(url);
    httpConnection = (HttpConnection) streamConnection;
    int code = httpConnection.getResponseCode();
    String strContent = "";
    // Check response code
    if (code == HttpConnection.HTTP_OK) {
        InputStream is = httpConnection.openInputStream();
        int length = (int) httpConnection.getLength();
        // Content is empty
        if (length != -1) {
            byte incomingData[] = new byte[length];
            is.read(incomingData);
            strContent = new String(incomingData);
            // Write content
        } else {
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            int ch;
            while ((ch = is.read()) != -1) {
                bytestream.write(ch);
            }
            strContent = new String(bytestream.toByteArray());
            bytestream.close();
        }
    }

When was finished this method, I have got the strContent return .
Detail content:
\ndocument.write('

Hello, visitor from:  Takatsuki, Japan');document.write('
');document.write('
Your Country Code: JP
');document.write('
Your IP State: Osaka
');document.write('
Your IP Address: 202.213.220.66
');document.write('
Your Hostname: ns.isb.co.jp
');document.write('
Your ISP: So-net Entertainment Corporation
');document.write('
Your Organization: ISB CORP.

');

How can I get the IP , country, state, city from above content?
Thanks and best regards !

A: As there is no standard format i.e. JSON or XML you have to parse the response by yourself. To write your scraper just check the response format carefully and design your algorithm.
For example, the response look like the following if we split the response by ";"..
document.write('

Hello, visitor from:  Dhaka, Bangladesh')
document.write('
')
document.write('
Your Country Code: BD
')
document.write('
Your IP State: Dhaka
')
document.write('
Your IP Address: 116.212.105.42
')
document.write('
Your Hostname: ws9-tetrasoft-dm-ac1-p16.telnet.com.bd
')
document.write('
Your ISP: Telnet Communication Limited
')
document.write('
Your Organization: Telnet Communication Limited

')

Then you can remove "document.write('" and "')" from each line..
then the response will become

Hello, visitor from:  Dhaka, Bangladesh

Your Country Code: BD

Your IP State: Dhaka

Your IP Address: 116.212.105.42

Your Hostname: ws9-tetrasoft-dm-ac1-p16.telnet.com.bd

Your ISP: Telnet Communication Limited

Your Organization: Telnet Communication Limited

Now you can use any HTML parser or parse the remaining by yourself...
just break the problem...
for example to get the IP address, you need to parse the 5th line..
remove all the characters from index 0 to the index of  + 3.... this will remove the portion "
Your IP Address: " from that line.....
then remove the characters from the index of  to the last... this will remove the "" from that line.. and you will get "116.212.105.42" as the remaining...

A: I think it is not possible to parse it but we can use logic to get data from that string
but format should same for ever
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;

public class StartUp extends UiApplication{
    public static void main(String[] args) {
        StartUp start=new StartUp();
        start.enterEventDispatcher();
    }
    public StartUp() {
        pushScreen(new simple());
    }
}
class simple extends MainScreen
{
    LabelField labl;
    public simple() {
        String str="\ndocument.write('

Hello, visitor from:  Takatsuki, Japan');document.write('
');document.write('
Your Country Code: JP
');document.write('
Your IP State: Osaka
');document.write('
Your IP Address: 202.213.220.66
');document.write('
Your Hostname: ns.isb.co.jp
');document.write('
Your ISP: So-net Entertainment Corporation
');document.write('
Your Organization: ISB CORP.

');";
        str=str.substring(str.indexOf("document.write"));
        String arr[]=split(str, "document.write('");
        String s="";
        int len=arr.length;

        for(int i=0;i<len;i++){
                if(i==0){

                    s=arr[i];
                    if(s.indexOf("")!=-1 && s.indexOf("")!=-1 ){
                        int sx=s.indexOf("")+8;
                        int dx=s.indexOf("");
                        System.out.println(s.substring(sx,dx));
                        labl=new LabelField(s.substring(sx,dx));
                        add(labl);
                    }

                }else if(i==1){
                    s=arr[i];
                    if(s.indexOf("img src='")!=-1 && s.indexOf("'>")!=-1 ){
                    int sx=s.indexOf("'")+1;
                    int dx=s.indexOf("'>");
                    System.out.println(s.substring(sx,dx));
                    labl=new LabelField(s.substring(sx,dx));
                    add(labl);
                    }
                }
            else{
                if(arr[i].indexOf("")!=-1 && arr[i].indexOf("")!=-1 ){
                int sx=arr[i].indexOf("")+3;
                int dx=arr[i].indexOf("");
                System.out.println(arr[i].substring(sx,dx));
                labl=new LabelField(arr[i].substring(sx,dx));
                add(labl);

                }
            }
        }
    }
     public static String[] split(String strString, String strDelimiter)
        {
            int iOccurrences = 0;
            int iIndexOfInnerString = 0;
            int iIndexOfDelimiter = 0;
            int iCounter = 0;

            // Check for null input strings.
            if (strString == null)
            {
                throw new NullPointerException("Input string cannot be null.");
            }
            // Check for null or empty delimiter
            // strings.
            if (strDelimiter.length() <= 0 || strDelimiter == null)
            {
                throw new NullPointerException("Delimeter cannot be null or empty.");
            }

            // If strString begins with delimiter
            // then remove it in
            // order
            // to comply with the desired format.

            if (strString.startsWith(strDelimiter))
            {
                strString = strString.substring(strDelimiter.length());
            }

            // If strString does not end with the
            // delimiter then add it
            // to the string in order to comply with
            // the desired format.
            if (!strString.endsWith(strDelimiter))
            {
                strString += strDelimiter;
            }

            // Count occurrences of the delimiter in
            // the string.
            // Occurrences should be the same amount
            // of inner strings.
            while((iIndexOfDelimiter= strString.indexOf(strDelimiter,iIndexOfInnerString))!=-1)
            {
                iOccurrences += 1;
                iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();
            }

            // Declare the array with the correct
            // size.
            String[] strArray = new String[iOccurrences];

            // Reset the indices.
            iIndexOfInnerString = 0;
            iIndexOfDelimiter = 0;

            // Walk across the string again and this
            // time add the
            // strings to the array.
            while((iIndexOfDelimiter= strString.indexOf(strDelimiter,iIndexOfInnerString))!=-1)
            {

                // Add string to
                // array.
                strArray[iCounter] = strString.substring(iIndexOfInnerString, iIndexOfDelimiter);

                // Increment the
                // index to the next
                // character after
                // the next
                // delimiter.
                iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();

                // Inc the counter.
                iCounter += 1;
            }
                return strArray;
        }
}

you will get output as following image


text:
Q: Is there any time where we should avoid cascading delete? In SQL Server 2008, there is a Primary table which is linked to three other child tables by 1 to many relationship. So, we are thinking of using Cascading delete in the primary table, so that all the records on the child table will be removed when record from primary table is deleted.

*

*So, is cascading delete a correct choice here?

*When cascading detele should not be used?

A: I guess the answer boils down to whether or not makes sense for your situation, it depends. For your situation, does it make sense for the rows in the 'child' table to remain if their corresponding 'primary' rows go?  Would the data in the child table be meaningless without the parent? If so, then cascading delete would enforce referential integrity. You might want to keep child rows as a record, an archive of past activity (though potentially you could write these rows to another table specially for this purpose).
An example I use to illustrate this point is the doctor/patient relation. One doc can have many patients. A patient can only be a patient if they have a doctor. If the doc goes (leaves the practice) then something has to happen to the remaining patients. One possibility is that they get purged. Another is that a default value replaces the doc reference or they could be removed from the main table and placed somewhere else. Alternatively no activity occurs and the patients remain as they were, untouched, as though the doc was still present. It depends what you want to do.
From personal experience think carefully about the design of the database. This week I had to run a purge of orphaned records in a table which pointed to nowhere and was literally taking up space.

A: Using cascading delete is a matter of personal preference, like whether to name tables with plural names or not (Customer vs Customers).
I would prefer to never use cascading delete. Some database designs avoid deleting at all. There are few justifications to delete data from a database when disk space is so cheap. Some database designs set an additional field "IsDeleted" rather than physically delete data.
If you have to delete data then using stored procedures to manage this gives you more transparency and control. Your application can execute a stored procedure which deletes from the child then parent. You don't know how the business requirements will change over time so sp's will give you more versatility. That's my 2c.

A: I am generally wary of cascaded deletes (and other automatic actions that could drop/damage data), either via triggers or ON <something> CASCADE. Such facilities are very powerful, but also potentially dangerous.

*

*So, is cascading delete a correct choice here?

It would certainly do what you are looking for it to do: remove related records when a parent record is removed, without you needing to implement any other logic to ensure that children get removed first therefore making your code more concise. All the actions will be wrapped in an implicit transaction so if something blocks the child deletes the whole operation is blocked, maintaining referential integrity with little or no extra coding effort.
Make sure that your use of cascaded deletes and other "behind the scenes" actions are well documented so future maintainers of the system are fully aware of it.

*

*When cascading detele should not be used?

It should not be used if you are paranoid like me! One key point to consider is the other developers who currently, or may in future, work on your code/database (hence the comment above about documenting any "hidden" behaviours).
It is quite common in my experience for inexperienced people to use DELETE then re-INSERT in order to update rows, especially when what they really want is a MERGE/UPSERT operation (update existing rows and create new ones where a row with a given key does not exist) and the DBMS doesn't support merge/upsert (or they are unaware of its support). Without cascaded actions this is perfectly safe (or will error when it threatens data integrity) but if someone does this for rows in a parent table where referring FKs have ON DELETE CASCADE set then related data will be deleted as a result of the initial delete and not replaced - so data is lost (not that even if the delete and subsequent insert are wrapped in explicit transactions, the cascade happens with the delete operation - it won't wait to see if the transaction replaces rows in the parent table in subsequent statements) and the cascade could continue through other relation ships (for instance: delete a senior supervisor, his team get deleted by cascade, his teams' teams get deleted by cascade, all the tracked records for all those people get deleted by cascade, ...). Without cascading enabled, you would just get an error here instead of the data being silently lost.