Q: Get list item count from all lists on all webs of site I found the following post that returns lists items from all lists on all webs within a site. I am trying to figure out how to return the list item count instead of the list items. Any assistance would be appreciated.
JSOM dynamicly get two announcements from all lists in all webs
UPDATE:
I am able to return details of all document libraries on a site using this:
function retrieveAllListProperties() {
    var clientContext = new SP.ClientContext.get_current();
    var oWebsite = clientContext.get_web();
    this.collList = oWebsite.get_lists();
    clientContext.load(collList);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    var tCount = 0;
    var listInfo = 'Lists on the current site:' + '\n\n';
    var listEnumerator = collList.getEnumerator();
    while (listEnumerator.moveNext()) {
        var oList = listEnumerator.get_current();
        if (oList.get_baseTemplate() === 101) {
            listInfo += 'URL: ' + oList.get_parentWebUrl() + '  |  Title: ' + oList.get_title() + '  |  BaseType: ' + oList.get_baseTemplate() + '  |  Count: ' + oList.get_itemCount() + '\n';
            tCount += + oList.get_itemCount();
        }
    }
    listInfo += '\nTotal Documents: ' + tCount;
    console.log(listInfo);
}

function onQueryFailed(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

I am able to return all sites and sub sites of a site collection using this:
function getAllWebs(success,error)
{
    var siteUrl = '/sites/usaraf/g357';

   var ctx = SP.ClientContext.get_current();
   var web = ctx.get_site().get_rootWeb();
   var result = [];
   var level = 0;
   var getAllWebsInner = function(web,result,success,error)
   {
      level++;
      var ctx = web.get_context();
      var webs = web.get_webs();
      ctx.load(webs,'Include(Title,ServerRelativeUrl,Webs)');
      ctx.executeQueryAsync(
         function(){
            for(var i = 0; i < webs.get_count();i++){
                var web = webs.getItemAtIndex(i);
                result.push(web);
                if(web.get_webs().get_count() > 0) {
                   getAllWebsInner(web,result,success,error);
                }
            }
            level--;
            if (level == 0 && success)
              success(result);
        },
        error);
   };

   getAllWebsInner(web,result,success,error);
}

getAllWebs(
 function(allwebs){
    for(var i = 0; i < allwebs.length;i++){
        console.log(allwebs[i].get_title() + "-" + allwebs[i].get_serverRelativeUrl());
    }
 },
function(sender,args){
     console.log(args.get_message());
});

I am trying to figure out how to tie the two together so I return the following for all specified lists on all sites and sub sites.
Lists on the current site:

URL: /sites/usaraf-ea/visa  |  Title: Applications  |  BaseType: 101  |  Count: 24
URL: /sites/usaraf-ea/visa  |  Title: docDropOff  |  BaseType: 101  |  Count: 28
URL: /sites/usaraf-ea/visa  |  Title: docResources  |  BaseType: 101  |  Count: 5
URL: /sites/usaraf-ea/visa  |  Title: Documents  |  BaseType: 101  |  Count: 2
URL: /sites/usaraf-ea/visa  |  Title: Site Assets  |  BaseType: 101  |  Count: 23

Total Documents: 82

A: When you got listitem collection, you could call listItems.get_count() to return items count.
Sample code:
<script type="text/javascript">
        var clientContext = null;
        var web = null;
        ExecuteOrDelayUntilScriptLoaded(getListItemsCount, "sp.js");
        function getListItemsCount() {
            clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            var list = web.get_lists().getByTitle("Child");
            var camlQuery = new SP.CamlQuery();
            this.listItems = list.getItems(camlQuery);
            clientContext.load(listItems, 'Include(Id)');
            clientContext.executeQueryAsync(function () {
                alert(listItems.get_count());
            },
            function () {
                alert('error');
            });
        }
    </script>


Q: Controlling Multiple Switch button in Android I'm Building a simple profile manager android application Using Switch Button in Android.
There are 3 switches named General,Silent and Vibrate.
Problem is all 3 switches are working together

I want the General Switch to be disabled when the silent switch is activated and silent to be disable when the general Switch is activated.
Where is my Code and what should be added ?
general = (Switch) findViewById(R.id.generalSwitch);
    silent  = (Switch) findViewById(R.id.silentSwitch);
    vibrate = (Switch) findViewById(R.id.vibrateSwitch);

    myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    general.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            Toast.makeText(MainActivity.this,"General Mode Activated",Toast.LENGTH_LONG).show();
        }
    });

    silent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            Toast.makeText(MainActivity.this,"Silent Mode Activated",Toast.LENGTH_LONG).show();
        }
    });

    vibrate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
            Toast.makeText(MainActivity.this,"Vibrate Mode Activated", Toast.LENGTH_LONG).show();
        }
    });

`

A: Test with this:
    general.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if(isChecked){
                silent.setChecked(false);
            }

        }
    });

    silent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if(isChecked){
                general.setChecked(false);
            }

        }
    });

if general switch is inactive and silent switch is active, when you press general, this change your state to active and you change silent switch to inactive.

A: When you say disabled first thing I imagine is switch can not to be touchable. Like in the picture.

If you want to do something like this you should add in setOnClickListener block
something like ;
silent.setEnabled(false)

But I think you meant that;
When the silent switch is ON general switch is OFF and when the general switch is ON silent switch is OFF
Than you can use setChecked method.
Like this;
 general.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            Toast.makeText(MainActivity.this,"General Mode Activated",Toast.LENGTH_LONG).show();
 silent.setChecked(false);
        }
    });

    silent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            Toast.makeText(MainActivity.this,"Silent Mode Activated",Toast.LENGTH_LONG).show();
 general.setChecked(false);
        }
    });


Q: how to hide some models in django grappelli admin? How to hide some of the models?
I need them registred to be used by other models, while calling via FK or nested etc.
I found one solution which is rather much about view layer of (MVC)
http://blog.jholster.com/post/1534211028/hide-app-names-in-django-admin
I would like to set it in admin.py, that some of registred models are hidden.

A: If the models are in your application, just don't register them in the first place. If the model is in a third party app like the django.contrib.auth then use AdminSite unregister method. You can put this in any admin.py or urls.py important is to be discovered by the admin.autodiscover.
# admin.py
from django.contrib.auth.models import User

admin.site.unregister(User)


Q: ImportError: DLL load failed: The file cannot be accessed by the system Traceback (most recent call last):

  File "<ipython-input-9-a40793f9ded7>", line 7, in <module>
    from sklearn.model_selection import train_test_split

  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\__init__.py", line 76, in <module>
    from .base import clone

  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\base.py", line 16, in <module>
    from .utils import _IS_32BIT

  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\__init__.py", line 20, in <module>
    from .validation import (as_float_array,

  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 21, in <module>
    from .fixes import _object_dtype_isnan

  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\fixes.py", line 18, in <module>
    from scipy.sparse.linalg import lsqr as sparse_lsqr  # noqa

  File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\linalg\__init__.py", line 113, in <module>
    from .isolve import *

  File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\linalg\isolve\__init__.py", line 6, in <module>
    from .iterative import *

  File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\linalg\isolve\iterative.py", line 10, in <module>
    from . import _iterative

ImportError: DLL load failed: The file cannot be accessed by the system.

Got this error while trying to run some already used python scripts on pycharm. Has anybody had this error before and has he solved it? It started after I installed a package in python but never used it. The problem is located when I try to import train_test_split on scikit-learn and tensorflow, the sklearn package and seaborn. The other parts of the code seem unaffected.
I have already reinstalled anaconda and python as well as changing the python files. Any help would be greatly appreciated.

A: After reinstalling the python as well as updating all the packages (conda update --all) and changing the PATH file, it seems that the issue is solved in all of my IDE's except PyCharm. It seems that all that remains is an interpreter issue. I will post updates if something else comes into my attention.


Q: WordPress: Getting title tag in PHP variable I am using Yoast SEO for SEO on the website. In my header file I have added
<title><?php wp_title( '|', true, 'right' ); ?></title>
I have also added <?php wp_head(); ?> in header.
Also enabled Force rewrite titles but still the title tag which I have added in page while editing it, in SEO Snippet is not displaying on webpage.
I have not added support for add_theme_support( 'title-tag' ); - Adding it and removing title tag from head also won't make any difference
So my question here is how I can grab the title tag Added in snippet and at list echo it out in page. On API for Yoast they have listed some hooks and filters but their are no examples.
Can get it by wpseo_title?

A: Make sure to add add_theme_support( 'title-tag' ); in functions.php and remove any <title></title> tags from header.php


Q: php streaming wav in firefox vs chrome I have a hidden audio element in a page, and i'm setting the source dynamically. im setting it as a php page with a GET request that finds the file based on the GET parameter.
However, the audio element is taking the wav file just fine in Chrome but not in firefox. Here is the query and html

<audio id = "play_wav" controls>
set source

and here's get_wav.php
if(isset($_GET['fname])){
    $fname = $_GET['fname'];
    readfile($fname);
}

So this is working to play streaming audio in chrome but not in firefox. The source is still being set it's just not loading. Any suggestions?

A: First off, you should not store the audio files in the same directory as your php files because its easy to protect from someone loading your PHP files by using the basename() function to isolate the filename else you must make further checks its not a php or system file path thats been passed to the $_GET['fname'] parameter, you should also put a .htaccess in the media folder with deny from all in it, this will stop direct access and if you want to be able to stream with seek-able functionality then you need to handle the HTTP_RANGE headers.
<?php
if(!empty($_GET['fname'])){
    $file_name = './wav_files/'.basename($_GET['fname']);
    stream($file_name, 'audio/wav');
}

/**
 * Streamable file handler
 *
 * @param String $file_location
 * @param Header|String $content_type
 * @return content
 */
function stream($file, $content_type = 'application/octet-stream') {

    // Make sure the files exists
    if (!file_exists($file)) {
        header("HTTP/1.1 404 Not Found");
        exit;
    }

    // Get file size
    $filesize = sprintf("%u", filesize($file));

    // Handle 'Range' header
    if(isset($_SERVER['HTTP_RANGE'])){
        $range = $_SERVER['HTTP_RANGE'];
    }elseif($apache = apache_request_headers()){
        $headers = array();
        foreach ($apache as $header => $val){
            $headers[strtolower($header)] = $val;
        }
        if(isset($headers['range'])){
            $range = $headers['range'];
        }
        else $range = FALSE;
    } else $range = FALSE;

    //Is range
    if($range){
        $partial = true;
        list($param, $range) = explode('=',$range);
        // Bad request - range unit is not 'bytes'
        if(strtolower(trim($param)) != 'bytes'){
            header("HTTP/1.1 400 Invalid Request");
            exit;
        }
        // Get range values
        $range = explode(',',$range);
        $range = explode('-',$range[0]);
        // Deal with range values
        if ($range[0] === ''){
            $end = $filesize - 1;
            $start = $end - intval($range[0]);
        } else if ($range[1] === '') {
            $start = intval($range[0]);
            $end = $filesize - 1;
        }else{
            // Both numbers present, return specific range
            $start = intval($range[0]);
            $end = intval($range[1]);
            if ($end >= $filesize || (!$start && (!$end || $end == ($filesize - 1)))) $partial = false;
        }
        $length = $end - $start + 1;
    }
    // No range requested
    else {
        $partial = false;
        $length = $filesize;
    }

    // Send standard headers
    header("Content-Type: $content_type");
    header("Content-Length: $length");
    header('Accept-Ranges: bytes');

    // send extra headers for range handling...
    if ($partial) {
        header('HTTP/1.1 206 Partial Content');
        header("Content-Range: bytes $start-$end/$filesize");
        if (!$fp = fopen($file, 'rb')) { // Error out if we can't read the file
            header("HTTP/1.1 500 Internal Server Error");
            exit;
        }
        if ($start) fseek($fp,$start);
        while($length){
            set_time_limit(0);
            $read = ($length > 8192) ? 8192 : $length;
            $length -= $read;
            print(fread($fp,$read));
        }
        fclose($fp);
    }
    //just send the whole file
    else readfile($file);
    exit;
}
?>


Q: thymeleaf get first 3 objects Could you please help me.
I want to display my first 3 objects from product, I don't how it must be.
I try to use thymeleaf sequence, but it don't work. Maybe somebody can hint me how it could be done.
HTML:

Delete

Edit

Controller:
@GetMapping("/products")
public String seeAllProductsIntoAList(Model model){
    model.addAttribute("products", productService.findAll());
    model.addAttribute("categories", categoryService.findAll());
    return "/productView/products";
}

It would be great if somebody can hint me with this issue.
Thank you.

A: Since products is list of Product, you have to iterate over that list. On thymeleaf you can use th:each attribute to do iteration. So for your case you can use something as below. Give it a try.
<th:each="product,iterStat: ${products}" th:if="${iterStat.index} <3">

I am not entirely sure but based on your question you wanted only first three objects. For this you can use status variable that are defined in th:each. More detail you can find here.

A: Here's the way you do it with the #{numbers} context object.

    Delete
    Edit


Q: Codeigniter Email class inside a model Is it possible to use the Codeigniter Email class within a Model?
I have been trying to but it refuses to load the mail object. In general, are libraries allowed to be loaded into models?
Code
<?php

class ClubInvitation extends DataMapper {

        var $table = "club_invitations";
        var $has_one = array("club");

        public function __construct($id){
            parent::__construct($id);
            $this->load->library('email');
        }

        public function inviteEmailToClub($email, $club, $message){
            $invite = new ClubInvitation();
            $invite->email = $email;
            $invite->code = random_string('unique', null);
            //$invite->save($club);

            $club->ClubAdmin->limit(1);
            $mainClubAdmin = $club->ClubAdmin->get()->User->get();
            $data['club'] = $club;
            $data['message'] = $message;
            $data['club_leader'] = $mainClubAdmin;
            $data['invite_code'] = $invite->code;

            $email_body = $this->WBLayout->emailTemplate('invited_to_club', $data);
            $this->email->from($mainClubAdmin->User->getAccount()->email, $club->name);
            $this->email->to($email);
            $this->email->subject($club->name.' has invited you to join');
            $this->email->message($email_body);
            $this->email->send();
        }

}

A: Normally, libraries are loaded in controller and accessed from there, not from models. You could just return the array of data from your model to controller and use email library from controller itself. If thats not feasible for you, then try doing:
public function __construct($id){
   parent::__construct($id);
}

public function inviteEmailToClub($email, $club, $message){
   $CI =& get_instance();
   $CI->load->library('email');
   .....
   $CI->email->from($mainClubAdmin->User->getAccount()->email, $club->name);
   ....
}


Q: PostgreSQL 1 to many trigger procedure I wrote this query in PostgreSQL:
CREATE OR REPLACE FUNCTION pippo() RETURNS TRIGGER AS $$
BEGIN
  CHECK (NOT EXISTS (SELECT * FROM padre WHERE cod_fis NOT IN (SELECT padre FROM paternita)));
END;
$$ LANGUAGE plpgsql;

It returns:

Syntax error at or near CHECK.

I wrote this code because I have to realize a 1..n link between two tables.

A: You can't use CHECK here. CHECK is for table and column constraints.
Two further notes:

*

*If this is supposed to be a statement level constraint trigger, I'm guessing you're actually looking for IF ... THEN RAISE EXCEPTION 'message'; END IF;
(If not, you may want to expand and clarify what you're trying to do.)

*The function should return NEW, OLD or NULL.


Q: Php, Mysql can't retrieve column data for each row I'm trying to give each modal form a unique id based on results retrieved from my database so that different data will be passed onto the php form processor. I have 1 table that is placed in a form which has the unique value for each row being "mapid"
However, each row also has a modal which I've placed another form in but the only value I'm getting is the first row of the sql query. Please help.
    $sql = "SELECT mapid, location, DATE_FORMAT(date,'%d/%m/%y') AS date, status FROM maps ORDER BY status DESC, date DESC ";
$result = $mysqli->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {

echo
'
<form action="map.php" method="post">

         '. $row["mapid"].'

         '. $row["location"].'

         ' . ($row["status"]=='0' ? 'Last Done' : (($row["status"]=='1') ? 'Started' : 'Done')).'

         '.$row["date"].'

         ' .
        (($row["status"]=='0') ?
            '<input type="hidden" name="mapid" value="'. $row["mapid"].'"/>
            <input type="hidden" name="start" value="start"/>
                <button class="btn btn-primary" name="getmap" type="submit">Start</button>'

        : (($row["status"]=='1') ?
            '<input type="hidden" name="mapid" value="'. $row["mapid"].'"/>
            <input type="hidden" name="resume" value="resume"/>
            <button class="btn btn-danger" type="submit" name="getmap" value="'. $row["mapid"].'">Resume</button>'

        : (($row["status"]=='2') ?
           '<input type="hidden" name="mapid" value="'. $row["mapid"].'"/>
            <input type="hidden" name="process" value="process"/>
                <button class="btn btn-primary" type="submit" name="getmap">Process</button>'
        : ''))) . '

</form>

            <button class="btn btn-primary" data-toggle="modal" data-target="#assign['. $row["mapid"].']">Assign</button>

                <form action="work/allocate.php" method="post">

Assign Map

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                    <input type="hidden" name="mapid">

 Assign Map '. $row["mapid"].' - '. $row["location"].'  to:

                    <input class="form-control" id="name" name="name" type="text" >

                    <button class="btn btn-primary" name="assigned" id="assigned" type="submit">Assign</button>

               </form>

    '

A: Just needed to give the modal a unique id by adding ['. $row["mapid"].'] next to #assign.

            <button class="btn btn-primary" data-toggle="modal" data-target="#assign['. $row["mapid"].']" value"">Assign</button>


Q: AKS - Kube State metrics Supported versions I am using AKS and recently upgraded to AKS 1.24.6.
How to determine what version of kube state metrics supports what AKS version?
I am looking at this https://github.com/kubernetes/kube-state-metrics
I am unable to understand the matrix given between Kube state metrics and Client-Go version.

A: According to the matrix, you can either use v2.5.0 or v2.6.0.


Q: Return result when count is below given value in spring mongodb I am relatively new to mongodb and spring data.
I am looking for a way to perform operation below in thread-safe manner. In implementation below, it is possible that result set will exceed 1000 after if statement is executed and just before result is queried.
How do I perform such operation atomically?
if (mongoTemplate.count(myQuery, Document.class) > 1000) {
    throw new ResultSetTooLargeException()
}

return mongoTemplate.find(myQuery, Document::class.java)

A: You cannot do it atomically but you can use limit which reduces it.
return mongoTemplate.find(myQuery.limit(1000), Document::class.java)


Q: Slick2d locating an x and y through pixel colour I am trying to make holdable items for my slick2d game, I figured a good way to do this would be to have a hand on the player, to do this i have 1 pixel a unique colour, allowing me to locate that colour, and the x +y.
It worked perfectly until i tried to scale up the image and i get this crazy out of bounds exeception.
this is my code to find the x and y:
    public int[] getLocation(Image i, Color c){
    Image scaled = i.getScaledCopy(getWidth(), getHeight());
    for(int x = 0; x < scaled.getWidth(); x++){
        for(int y = 0; y < scaled.getHeight(); y++){
            if(scaled.getColor(x, y).r == c.r && scaled.getColor(x, y).g == c.g && scaled.getColor(x, y).b == c.b){
                int[] xy = {x,y};
                return xy;

            }
        }
    }
    return null;
}

and this is how i use it
    float x = (float) (getLocation(walkLeft.getCurrentFrame(), new Color(1, 1, 1))[0] + getX());
    float y = (float) (getLocation(walkLeft.getCurrentFrame(), new Color(1, 1, 1))[1] + getY());
    g.fillRect(x, y, 2, 2);

the exception is:
java.lang.ArrayIndexOutOfBoundsException: 16384

and it leads me back to this line:
                if(i.getColor(x, y).r == c.r && i.getColor(x, y).g == c.g && i.getColor(x, y).b == c.b){

in the getLocation method..
I have a feeling its dead easy, yet its stumped me. Thanks to anyone to responds.

A: The loop(s) in getLocation loop over the dimensions of a 2x scaled copy of the Image, but then attempt to access the pixels of the original. Given the original is half the size, when you are half-way through the loop you will be out of bounds of the image dimensions. Either:

*

*Don't scale the Image

*If you must scale the Image, check the pixel value of the scaled image rather than the original.

As an aside, the code posted contains redundant calls...a) in getLocation if you are going to scale, consider scaling the image once rather than placing that code within the loop itself b) no need to call getLocation twice with the same parameters. Call it once and just use the returned array


Q: I have a .mp4 video how i can add water mark I have .mp4 video and i want to generate new video from that with watermarked on proper place.
Is there possibilities where i can create function and pass video it will return me Water marked video.

A: try this :
This code is add a text or string ON the video and after saving video you will play on any player.
Most Advantage of this code is Provide video with sound. And all things in one code(that is text and image).
    #import <AVFoundation/AVFoundation.h>

    -(void)MixVideoWithText
    {
        AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:url options:nil];
        AVMutableComposition* mixComposition = [AVMutableComposition composition];

        AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
        AVAssetTrack *clipVideoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
        AVMutableCompositionTrack *compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        AVAssetTrack *clipAudioTrack = [[videoAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
        //If you need audio as well add the Asset Track for audio here

        [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:clipVideoTrack atTime:kCMTimeZero error:nil];
        [compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:clipAudioTrack atTime:kCMTimeZero error:nil];

        [compositionVideoTrack setPreferredTransform:[[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] preferredTransform]];

        CGSize sizeOfVideo=[videoAsset naturalSize];

        //TextLayer defines the text they want to add in Video
        //Text of watermark
        CATextLayer *textOfvideo=[[CATextLayer alloc] init];
        textOfvideo.string=[NSString stringWithFormat:@"%@",text];//text is shows the text that you want add in video.
        [textOfvideo setFont:(__bridge CFTypeRef)([UIFont fontWithName:[NSString stringWithFormat:@"%@",fontUsed] size:13])];//fontUsed is the name of font
        [textOfvideo setFrame:CGRectMake(0, 0, sizeOfVideo.width, sizeOfVideo.height/6)];
        [textOfvideo setAlignmentMode:kCAAlignmentCenter];
        [textOfvideo setForegroundColor:[selectedColour CGColor]];

        //Image of watermark
        UIImage *myImage=[UIImage imageNamed:@"one.png"];
        CALayer layerCa = [CALayer layer];
        layerCa.contents = (id)myImage.CGImage;
        layerCa.frame = CGRectMake(0, 0, sizeOfVideo.width, sizeOfVideo.height);
        layerCa.opacity = 1.0;

        CALayer *optionalLayer=[CALayer layer];
        [optionalL addSublayer:textOfvideo];
        optionalL.frame=CGRectMake(0, 0, sizeOfVideo.width, sizeOfVideo.height);
        [optionalL setMasksToBounds:YES];

        CALayer *parentLayer=[CALayer layer];
        CALayer *videoLayer=[CALayer layer];
        parentLayer.frame=CGRectMake(0, 0, sizeOfVideo.width, sizeOfVideo.height);
        videoLayer.frame=CGRectMake(0, 0, sizeOfVideo.width, sizeOfVideo.height);
        [parentLayer addSublayer:videoLayer];
        [parentLayer addSublayer:optionalLayer];
        [parentLayer addSublayer:layerCa];

        AVMutableVideoComposition *videoComposition=[AVMutableVideoComposition videoComposition] ;
        videoComposition.frameDuration=CMTimeMake(1, 30);
        videoComposition.renderSize=sizeOfVideo;
        videoComposition.animationTool=[AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];

        AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
        instruction.timeRange = CMTimeRangeMake(kCMTimeZero, [mixComposition duration]);
        AVAssetTrack *videoTrack = [[mixComposition tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
        AVMutableVideoCompositionLayerInstruction* layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
        instruction.layerInstructions = [NSArray arrayWithObject:layerInstruction];
        videoComposition.instructions = [NSArray arrayWithObject: instruction];

        NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd_HH-mm-ss"];
        NSString *destinationPath = [documentsDirectory stringByAppendingFormat:@"/utput_%@.mov", [dateFormatter stringFromDate:[NSDate date]]];

        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetMediumQuality];
        exportSession.videoComposition=videoComposition;

        exportSession.outputURL = [NSURL fileURLWithPath:destinationPath];
        exportSession.outputFileType = AVFileTypeQuickTimeMovie;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
        switch (exportSession.status)
        {
            case AVAssetExportSessionStatusCompleted:
                NSLog(@"Export OK");
                if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(destinationPath)) {
                    UISaveVideoAtPathToSavedPhotosAlbum(destinationPath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
                }
                break;
            case AVAssetExportSessionStatusFailed:
                NSLog (@"AVAssetExportSessionStatusFailed: %@", exportSession.error);
                break;
            case AVAssetExportSessionStatusCancelled:
                NSLog(@"Export Cancelled");
                break;
        }
      }];
    }
Shows the error they will come after saving video.

    -(void) video: (NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
    {
        if(error)
            NSLog(@"Finished saving video with error: %@", error);
    }

From :https://stackoverflow.com/a/22016800/3901620


Q: How to send a single-image in MediaPipe Javascript? Can you explain me how to send a single-image in MediaPipe Hand with Javascript? (from an uploaded image)
I used the Mediapipe Hand python-solution with a single-image like in the jupyther/google collab demo
I would like to do the same operation in javascript but I can't find any solution
Thanks !


Q: How do I create a top 3 chart list in google sheet I have a column in google sheet that has random numbers from 1 to 20.
I want to create a chart that shows the top 3 numbers that occurred in that column.
Example:
Lucky numbers:

so on....
TIA

A: Let's assume the answer to my questions was 'yes', you want the three numbers that occur most often and how often they occur.
I've tried a couple of ways of doing this. One way is to sort the numbers and use FREQUENCY to get the frequencies. Then you could use a query like this to get the top 3
=query(A1:B20,"select A,B order by B desc limit 3")

Another way is to get the mode, then the mode excluding the most frequent, then the mode excluding both of the previous ones etc.
=ArrayFormula(mode(if(iserror(match(A$2:A$20,F$1:F1,0)),A$2:A$20)))

starting in F2 - you don't need to sort them.
Then you can just use COUNTIF to get how many times they occur.
Then just put them into a chart.


Q: Write to a unique attribute of a non unique div folks!
I have two variables:
var day =  $(this).text();
var day_id =   $(this).data('num');

I have HTML inputs with unique ID:
<input class="update_day" data-id="88" type="text" value="5" name="day">
<input class="update_day" data-id="89 type="text" value="5" name="day">
<input class="update_day" data-id="90" type="text" value="5" name="day">

etc...
I need to update a SPECIFIC input (stored in variable "day_id") with certain data (stored in "day")
It is supposed to look like this:
$(".update_day WHERE data-id= day_id).val(day);

Thank you in advance! Sorry for the newbee question. I have honestly been trying to solve it myself.

A: Try
$(".update_day[data-id='90']").val(day);

if value is stored in variable day_id
$(".update_day[data-id='" + day_id + "']").val(day);

Attribute equals selector


Q: SSIS 2012 SP1 "Value of null is not valid for stream" error on designer components I have just migrated a project from SSIS 2005 to SSIS 2012
Apart from the project, I had a custom pipeline component, which was also migrated to .NET 4.0, and installed in SQL Server DTS directory and the GAC, as usual.
After the migration, when I tried to open and configure the migrated component I got the error: "Value of null is not valid for stream".
The error only happened in "SSDT for BI" of VS 2012. When I tried to open and use the component in SQL Server Data Tools (VS 2010, not 2012, shell) it work without flaws.
So, this is a problem exclusive to SQL Server 2012 SP1 and SSDT for BI for VS2012

A: This problem affects SQL Server 2012 SSIS, and, in some occasssions, it doesn't even allow to open SSIS packages.
This error is solved with a Microsoft patch which can be downloaded from this page:
Micsosoft KB 2832017
Particularly, to solve the problem in VS, as VS is a 32 bit application, you only have to install the x86 download.


Q: Add controller for "plugin::users-permissions.user" [strapi v4] I can create a controller for created contentType, ex: api::restaurant.restaurant.
https://docs.strapi.io/developer-docs/latest/development/backend-customization/controllers.html
But for built-in plugins, ex: plugin::users-permissions.user, I don't know where to put the controller.

Strapi Version: 4.0.2


Q: How to access in the template, reactive form, an array in an array I'm a beginner in programming and i try to understand what i'm doing wrong. :)
I've create a reactive Form that contains an array of string that contains a string an an array of string.
it looks like this:

And the json file looks like this:
  public dbData: any =  {
    'ITEMS':[
      {
        'NAME': 'Farine',
        'QUANTITY': ['140', '60']
      }]
  };

I arrive to create the FormGroup correctly:

When i submit it looks correct:

But i don't arrive to display it in the template correctly :(
page.ts:
export class Form2Page implements OnInit, OnDestroy {
  itemsForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    this.itemsForm = new FormGroup({
      'items': new FormArray([])
    });
    console.log('From initForm', this.itemsForm);
  }

  onFormSubmit() {
    console.log('Submit : ', this.itemsForm.value);
  }

  onAddItems() {
    const control = new FormGroup({ name: new FormControl(''),
                                    quantity: new FormArray([])});

    (<FormArray>this.itemsForm.get('items')).push(control);
    console.log('Add From', this.itemsForm);
  }

Page.html
<ion-content>

    {{dbData.ITEMS[0].QUANTITY[1]}}

  <form [formGroup]="itemsForm" (ngSubmit)="onFormSubmit()">

    <ion-button type="button" (click)="onAddItems()">New Item</ion-button>

ITEMS

          <ion-label>Name :
            <input type="text" formControlName="name">
          </ion-label>

              <ion-label>Quantity :
                <input type="text" [formControlName]="j">
              </ion-label>

    <ion-button type="submit">Submit</ion-button>
  </form>
</ion-content>

Thanks for your help :)

A: I haven't implemented in Ionic. But you can use the exact same thing in Ionic too:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';

export interface Data {
  ITEMS: Array<Item>;
}

export interface Item {
  NAME: string;
  QUANTITY: Array<string>;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dbData: Data = {
    'ITEMS': [
      {
        'NAME': 'Farine',
        'QUANTITY': ['140', '60']
      }]
  };

  itemsForm: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.itemsForm = new FormGroup({
      'ITEMS': this.formBuilder.array(this.dbData.ITEMS.map(item => this.createItem(item)))
    });
  }

  onFormSubmit() {
    console.log('Submit : ', this.itemsForm.value);
  }

  onAddItems() {
    (<FormArray>this.itemsForm.get('ITEMS')).push(this.createItem({ NAME: '', QUANTITY: [] }));
  }

  addQuantity(i) {
    (<FormArray>(<FormArray>this.itemsForm.get('ITEMS')).at(i).get('QUANTITY')).push(this.formBuilder.control(''));
  }

  private createItem(item: Item) {
    return this.formBuilder.group({
      NAME: [item.NAME],
      QUANTITY: this.formBuilder.array(item.QUANTITY.map(item => this.formBuilder.control(item)))
    });
  }

}

And in the template:

{{ itemsForm.value | json }}

<form [formGroup]="itemsForm" (ngSubmit)="onFormSubmit()">
  <button type="button" (click)="onAddItems()">New Item</button>

ITEMS

        Name :
          <input type="text" formControlName="NAME">

            Quantity :
              <input type="text" [formControlName]="j">

          <button (click)="addQuantity(i)">Add Quantity</button>

  <button type="submit">Submit</button>
</form>

Here's a Working Sample StackBlitz for your ref.

A: There are multiple issues in your code
please see the fixed code here

*

*You need to add controls/form to array, just having any empty form array is not enough

*For loading data into your form, you need to refactor a little bit, because you need to loop through your items and add control/form to your array


Q: Azure event hubs metrics not appearing when deploying with terraform When deploying with some other components (of a data pipeline) like function app and cosmosdb, metrics graphs on azure event hubs portal are not appearing instead graphs show "Resource not found".
But when I deploy the same terraform code for event hubs namespace without other components, metric graphs appears. Here is terraform code:
locals {
  ip_rule_map = flatten([
    for cidr in ["182.191.83.208"] : [
      {
        action  = "Allow"
        ip_mask = cidr
      }
    ]
  ])
}
resource "azurerm_eventhub_namespace" "avro-ingestion" {
  name                = "test-eh"
  location            = "Central US"
  resource_group_name = "test-rg"
  sku                 = "Standard"
  capacity            = 1

  network_rulesets = false ? [{
    default_action                 = "Deny"
    ip_rule                        = local.ip_rule_map
    virtual_network_rule           = []
    trusted_service_access_enabled = true
    }] : [
    {
      default_action                 = "Allow"
      ip_rule                        = local.ip_rule_map
      virtual_network_rule           = []
      trusted_service_access_enabled = true
    }
  ]

  tags = {
    Name      = "avro-ingestion"
    Purpose   = "data-ingestion-infra-deployment"
    CreatedBy = "emumba"
  }
}

resource "azurerm_eventhub_namespace_authorization_rule" "user_managed" {
  name                = "UserManagedSharedAccessKey"
  namespace_name      = azurerm_eventhub_namespace.avro-ingestion.name
  resource_group_name = "test-rg"

  listen = true
  send   = true
  manage = true
}
resource "null_resource" "schema-registry" {
  depends_on = [
    azurerm_eventhub_namespace.avro-ingestion
  ]
  provisioner "local-exec" {
    interpreter = ["/bin/bash", "-c"]
    command     = "az eventhubs namespace schema-registry create --name test-schema-group  --namespace-name test-eh --resource-group test-rg --schema-compatibility Backward --schema-type Avro"
  }
}

resource "azurerm_eventhub" "thunder" {
  name                = "test"
  namespace_name      = azurerm_eventhub_namespace.avro-ingestion.name
  resource_group_name = "test-rg"
  partition_count     = 2
  message_retention   = 1

}

resource "azurerm_eventhub_consumer_group" "function-app-cg" {
  name                = "fApp-cons-group"
  namespace_name      = azurerm_eventhub_namespace.avro-ingestion.name
  eventhub_name       = azurerm_eventhub.thunder.name
  resource_group_name = "test-rg"
}

main.tf file where I am calling all modules along with event hubs namespace module:
resource "random_string" "random_Sacc1" {
  length      = 4
  special     = false
  upper       = false
  min_lower   = 1
  min_numeric = 1
}

resource "random_string" "random_Sacc2" {
  length      = 2
  special     = false
  upper       = false
  min_lower   = 1
  min_numeric = 1
}

module "azure-resource-group" {
  source = "../../modules/resource-group"

  region         = var.region
  res_group_name = var.res_group_name
}

module "azure-virtual-network" {
  depends_on = [
    module.azure-resource-group
  ]
  source = "../../modules/virtual-network"

  rg_name               = module.azure-resource-group.name
  rg_location           = module.azure-resource-group.location
  vn_name               = var.vn_name
  vn_cidrs              = var.vn_cidrs
  subnets               = var.subnets
  subnet_cidrs          = var.subnet_cidrs
  pub_nsg_name          = var.pub_nsg_name
  private_nsg_name      = var.private_nsg_name
  internet_ip_cidr_list = var.internet_ip_cidr_list

}

module "azure-ad-app-registration" {
  depends_on = [
    module.azure-resource-group
  ]
  source = "../../modules/app-role-assignment"

  app-display-name = var.app-display-name
  rg_name          = module.azure-resource-group.name
}

module "azure-eventhubs" {
  source                = "../../modules/event-hubs"
  ns_name               = var.eventhub_namespace_name
  eventhub_name         = var.eventhub_name
  cons_group_name       = var.cons_group_name
  rg_name               = module.azure-resource-group.name
  rg_location           = module.azure-resource-group.location
  enable_private_access = var.enable_private_access
  cidr_list             = var.public_cidr_list
  vnet_id_dns           = module.azure-virtual-network.vnet-id
  private_ep_subnet     = module.azure-virtual-network.private-subent1-id
  dns_zone_name         = var.dns_zone_name_private_ep
  schema_group_name = var.eventhub_schema_group_name
}

module "azure-storage-account" {
  depends_on = [
  module.azure-virtual-network
  ]
  source = "../../modules/storage-account"

  storage_acc_name      = "${var.storage_acc_name}${random_string.random_Sacc1.id}"
  rg_name               = module.azure-resource-group.name
  rg_location           = module.azure-resource-group.location
  enable_private_access = var.enable_private_access
  cidr_list             = var.public_cidr_list
  vnet_id_dns           = module.azure-virtual-network.vnet-id
  private_ep_subnet     = module.azure-virtual-network.private-subent1-id
  dns_zone_name         = var.dns_zone_name_private_ep

}

module "azure-cosmos-db" {
  source = "../../modules/cosmos-db"

  acc_name                 = var.cosmos_acc_name
  db_name                  = var.cosmos_db_name
  rg_name                  = module.azure-resource-group.name
  rg_location              = module.azure-resource-group.location
  cosmos_db_container_name = var.cosmos_db_container_name
  enable_private_access    = var.enable_private_access
  cidr_list                = var.public_cidr_list
  vnet_id_dns              = module.azure-virtual-network.vnet-id
  private_ep_subnet        = module.azure-virtual-network.private-subent1-id
  dns_zone_name            = var.dns_zone_name_private_ep
  synapse_link = var.enable_synapse_link
}

# module "fApp-azure-storage-account" {
#   source = "../../modules/storage-account"

#   storage_acc_name      = "${var.storage_acc_fApp_name}${random_string.random_Sacc2.id}"
#   rg_name               = module.azure-resource-group.name
#   rg_location           = module.azure-resource-group.location
#   enable_private_access = var.enable_private_access
#   cidr_list             = var.public_cidr_list
#   private_ep_subnet     = element(module.azure-virtual-network.subnet_id_list, 1)
#   dns_zone_name         = var.dns_zone_name_private_ep

# }

module "data-ingestion-fApp" {
  depends_on = [
    module.azure-cosmos-db,
    module.azure-eventhubs,
    module.azure-storage-account
  ]
  source = "../../modules/function-app"

  rg_name                  = module.azure-resource-group.name
  rg_location              = module.azure-resource-group.location
  application_insight_name = var.application_insight_name
  fApp_service_plan_name   = var.fApp_service_plan_name
  fApp_name                = var.fApp_name
  fApp-storage_acc_name    = "${var.storage_acc_fApp_name}${random_string.random_Sacc2.id}"
  enable_private_access    = var.enable_private_access
  vnet_id_dns              = module.azure-virtual-network.vnet-id
  private_ep_subnet        = module.azure-virtual-network.private-subent1-id
  integration_vnet_name    = module.azure-virtual-network.vnet-name
  integration_subnet_name  = module.azure-virtual-network.private-subent2-name
  func_configurations = { "AZURE_CLIENT_ID" = module.azure-ad-app-registration.client_id
    "AZURE_CLIENT_SECRET"                = module.azure-ad-app-registration.client_secret,
    "AZURE_TENANT_ID"                    = module.azure-ad-app-registration.tenant_id,
    "EVENTHUB_NAME"                      = var.eventhub_name,
    "EVENTHUB_FULLY_QUALIFIED_NAMESPACE" = "${var.eventhub_namespace_name}.servicebus.windows.net",
    "SCHEMA_GROUP_NAME"                  = var.eventhub_schema_group_name,
    "OUTPUT_CONTAINER"                   = var.storage_acc_container_name,
    "OUTPUT_PATH"                        = var.storage_acc_container_path,
    "COSMOS_DB_URI"                      = module.azure-cosmos-db.cosmos_account_uri,
    "COSMOS_DB_PRIMARY_KEY"              = module.azure-cosmos-db.cosmos_account_primary_key,
    "COSMOS_DB_NAME"                     = var.cosmos_db_name,
    "COSMOS_DB_CONTAINER_NAME"           = var.cosmos_db_container_name,
    "a10devops_namespace_connection"     = module.azure-eventhubs.eventhub_conn_str,
  "a10devops_storage_connection" = module.azure-storage-account.storage_account_conn_str }
}


Q: Tool Tip to show entire GridView row I want to create a tooltip feature that will display all of a user data that is being displayed in a gridview.
Expected Result: A GridView displays Last_Name,First_Name,Telephone,Cell_Phone. I want a tool tip to display with a mousehover over that users row of information and display all of the data in that tooltip. The data is only generated when a users uses my search box feature so it can't be a static tooltip string. I"m using a sqldatasource to fill in the gridview which i'm not sure how to call. The only thing I can find is by making the gridview a label which I don't want to do. Any guidance would be much appreciated.
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" GridLines="None" HorizontalAlign="Center" AllowPaging="True" AllowSorting="True" ForeColor="#333333">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>
        <asp:BoundField DataField="Last_Name" HeaderText="Last_Name" SortExpression="Last_Name" />
        <asp:BoundField DataField="First_Name" HeaderText="First_Name" SortExpression="First_Name" />
        <asp:BoundField DataField="Middle_Int" HeaderText="Middle_Int" SortExpression="Middle_Int" />
        <asp:BoundField DataField="Telephone" HeaderText="Work Telephone" SortExpression="Telephone" />
        <asp:BoundField DataField="Cell_Phone" HeaderText="Work Cell" SortExpression="Cell_Phone" />
    </Columns>
</asp:GridView>

SQLDataSource Connection:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myconnection %>" SelectCommand="SELECT [Last_Name], [First_Name], [Middle_Int], [Rank], [Telephone], [Cell_Phone], [Unit], [UserName]  FROM [Person_Search] WHERE (([Middle_Int] LIKE '%' + @Middle_Int + '%') OR ([Cell_Phone] LIKE '%' + @Cell_Phone + '%')  OR ([First_Name] LIKE '%' + @First_Name + '%')  OR ([Telephone] LIKE '%' + @Telephone + '%') OR ([Unit] = @Unit) OR ([Last_Name] LIKE '%' + @Last_Name + '%') OR ([UserName] LIKE '%' + @UserName + '%'))">
    <SelectParameters>
        <asp:ControlParameter ControlID="TextBox1" Name="Middle_Int" PropertyName="Text" />
        <asp:ControlParameter ControlID="TextBox1" Name="Cell_Phone" PropertyName="Text" Type="String" />
        <asp:ControlParameter ControlID="TextBox1" Name="First_Name" PropertyName="Text" Type="String" />
        <asp:ControlParameter ControlID="TextBox1" Name="Telephone" PropertyName="Text" Type="String" />
        <asp:ControlParameter ControlID="TextBox1" Name="Last_Name" PropertyName="Text" Type="String" />
    </SelectParameters>
</asp:SqlDataSource>

Label Control View Code:
<asp:TemplateField HeaderText="Logid">
<ItemTemplate>
     <asp:Label ID="Label1" runat="server" Text='<%# Bind("cityid") %>' ToolTip='<%# Bind("cityName") %>' ></asp:Label>
 </ItemTemplate>

A: You can use the RowDataBound event to add the ToolTip property to a GridViewRow.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the row is d datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //cast the row back to a datarowview
        DataRowView row = e.Row.DataItem as DataRowView;

        StringBuilder tooltip = new StringBuilder();

        //add the data to the tooltip stringbuilder
        tooltip.Append(row["Last_Name"] + ", ");
        tooltip.Append(row["First_Name"] + ", ");
        tooltip.Append(row["Middle_Int"] + ", ");
        tooltip.Append(row["Telephone"] + ", ");
        tooltip.Append(row["Cell_Phone"]);

        //add the tooltip attribute to the row
        e.Row.Attributes.Add("ToolTip", tooltip.ToString());
    }
}


Q: Filter List Debug I'm having trouble debugging this procedure I built. I have over 2 thousand workbooks I'm trying to filter through.
I'm feeding this function a dictionary with its key being the file path & name and the item being a 9 digit part number and the revision number. Based on the folder path and part number, I'm trying to filter out the older revision numbers.
The error message I am recieving is:

Run-time error '10':
This array is fixed or temporarily locked

The debugger is stoping at the line: For Each VKey02 In DUnsorted.Keys. The debug counting variables k1 and k2 end with the values 39 and 1 respectively at the crash.
Any suggestions on how to solve this issue will be appreciated.
Note: I have enabled the "Microsoft Scripting Runtime" reference for this code to work as intended.
Option Explicit

Function HighestRev(ByVal DUnsorted As Scripting.Dictionary) As Scripting.Dictionary
    Dim DSorted As Scripting.Dictionary
    'Keys
    Dim VKey01 As Variant
    Dim VKey02 As Variant
    Dim SKey01 As String
    Dim SKey02 As String
    'Items
    Dim SItem01 As String
    Dim SItem02 As String
    'SKUs
    Dim LSKU01 As Long
    Dim LSKU02 As Long
    'Revs
    Dim IRev01 As Long
    Dim IRev02 As Long
    'File Name
    Dim SName01 As String
    Dim SName02 As String
    'File Path
    Dim SPath01 As String
    Dim SPath02 As String

    'Debug Variables
    Dim k1 As Integer
    Dim k2 As Integer

    'Initializing
    Set DSorted = DUnsorted

    'Looping Through
    k1 = 0
    For Each VKey01 In DUnsorted.Keys

    k1 = k1 + 1: k2 = 1 '<-- Debug
    If VKey01 = "[A Particular File]" Then
        Debug.Print "1 - " & VKey01
        Debug.Print k1 & " - " & k2
    End If

    SKey01 = VKey01
    If Not DSorted.Exists(SKey01) Then GoTo SkipKey01
    SItem01 = DUnsorted(SKey01)
    LSKU01 = Split(SItem01, "-")(0)
    IRev01 = Split(SItem01, "-")(1)
    SName01 = Split(SKey01, "\")(UBound(Split(SKey01, "\")))
    SPath01 = Left(SKey01, Len(SKey01) - Len(SName01))
        For Each VKey02 In DUnsorted.Keys

        k2 = k2 + 1 '<-- Debug
        If VKey02 = "[A Particular File]" Then
            Debug.Print "2 - " & VKey02
            Debug.Print k1 & " - " & k2
        End If

        SKey02 = VKey02
        If Not DSorted.Exists(SKey02) Then GoTo SkipKey02
        SItem02 = DUnsorted(SKey02)
        LSKU02 = Split(SItem02, "-")(0)
        IRev02 = Split(SItem02, "-")(1)
        SName02 = Split(SKey02, "\")(UBound(Split(SKey02, "\")))
        SPath02 = Left(SKey02, Len(SKey02) - Len(SName02))

            'Identifying Match
            If SKey01 <> SKey02 Then
            If LSKU01 = LSKU02 Then
            If UBound(Split(SPath01, SPath02)) > 0 Or UBound(Split(SPath02, SPath01)) > 0 Then

                'Eliminating Older Revision
                If IRev01 > IRev02 Then
                    DSorted.Remove (SKey02)
                ElseIf IRev01 < IRev02 Then
                    DSorted.Remove (SKey01)
                Else    '<-- Last Modified Priority
                    DSorted.Remove (OlderDate(SKey01, SKey02))
                End If
                If Not DSorted.Exists(SKey01) Then GoTo SkipKey01
            End If
            End If
            End If
SkipKey02:
        Next VKey02
SkipKey01:
    Next VKey01
End Function

A: Well the error actually followed one of the workbooks. I'm still puzzled with where in the workbook path and file name it's giving me the issue, but the code itself is now working.


Q: R: Creating a function using dplyr functions I have a data frame with three variables of interest:

*

*survival time

*grouping factor

*event indicator (dead: yes or no)

I want to calculate incidence rate for each group. I do this daily, so it would be great to have a function doing this instead of a long script.
I've tried the following, but doesn't work.
library(survival)
data(lung) # example data
lung$death <- ifelse(lung$status==1, 0, 1) # event indicator: 0 = survived; 1 = dead.

# Function
func <- function(data_frame, group, survival_time, event) {
     library(epitools)
     table <- data_frame %>%
          filter_(!is.na(.$group)) %>%
          group_by_(.$group) %>%
          summarise_(pt = round(sum(as.numeric(.$survival_time)/365.25)),
                     events = sum(.$event)) %>%
          do(pois.exact(.$events, pt = .$pt/1000, conf.level = 0.95)) %>%
          ungroup() %>%
          transmute_(Category = c(levels(as.factor(.$group))),
                     Events = x,
                     Person_years = pt*1000,
                     Incidence_Rate = paste(format(round(rate, 2), nsmall=2), " (",
                                      format(round(lower, 2), nsmall=2), " to ",
                                      format(round(upper, 2), nsmall=2), ")",
                                      sep=""))
     return(table)
}

func(lung, sex, time, death)

**Error: incorrect length (0), expecting: 228 In addition: Warning message:
In is.na(.$group) : is.na() applied to non-(list or vector) of type 'NULL'**

Any ideas? I've read the post about NSE and SE in dplyr, but thought I applied the recommendations correctly?

A: Here is a part of the solution
data_frame = lung
group = "sex"
survival_time = "time"
event = "death"
data_frame %>%
  filter_(paste("!is.na(", group, ")")) %>%
  group_by_(group) %>%
  summarise_(
    pt = paste("round(sum(as.numeric(", survival_time, ") / 365.25))"),
    events = paste("sum(", event, ")")
  )


Q: Easy pattern detection for 3D reconstruction Im currently working on a 3d reconstruction/pose estimation project. To be more specific i have implemented a method which is able to estimate the pose, given horizontal and vertical  line correspondences.
In order to have this method work, i need to create an easily detected pattern (the reference view) in which every single line detected (in others shots-view) can be distinguished from the others in such way i can tell which line is detected with respect to the reference view.
The problem is that i have hard time thinking of a pattern both good looking and functional. What i have come up so far is the pattern above in which given the color of the region, the line is detected, i can tell whether the line is vertical or horizontal and given the color of the line i can discrete the line to tell its coordinates in the reference pattern. Unfortunatly i find myself lost in all these detection methods and i lack the experience of working in such tasks, are there any methods relative to my task ?
Any help or idea is greatly appreciated.
PS: it is worth mentioning that the camera is already calibrated and i need this method to work in case the patter is partially occluded.


Q: Creating a normal class with injections from Spring Well, I have a normal class (LovHelper) that is responsible for doing some utils tasks. When i say normal class is because LovHelper.java don't have @Component, @Service or @Repository annotation.
Inside of this "normal class" i wanna inject a bean from spring, but the bean is always null. Look my Class LovHelper.java bellow:
package br.com.odontonew.helper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import br.com.odontonew.bean.Lov;
import br.com.odontonew.dao.BasicDAO;

public class LovHelper {

    @Autowired
    private BasicDAO dao;

    private static LovHelper instance;

    private LovHelper(){

    }

    public static LovHelper getInstance(){
        if (instance == null)
            instance = new LovHelper();

        return instance;
    }

    public Lov getLovByCodigo(Class lovClass, String codigo){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("codigo", codigo);
        List<Lov> lovs = (List<Lov>)dao.findByQuery("SELECT c FROM "+lovClass.getName()+" c WHERE c.codigo = :codigo", map);
        if (lovs.size() == 1)
            return lovs.get(0);
        else
            return null;
    }

    /*Getters and Setters*/
    public BasicDAO getDao() {
        return dao;
    }

    public void setDao(BasicDAO dao) {
        this.dao = dao;
    }

}

So, in another class i just call: LovHelper.getInstance().getLovByCodigo(param1, param2). But i always get a NullPointerException because the bean "dao" within LovHelper is NULL.
After think a little i decided to change my LovHelper.java (using singleton pattern) to a Bean for Spring inject, then I put @Component annotation and remove all singleton pattern the was developed.
And in another class i inject "lovHelper" and use like this: lovHelper.getLovByCodigo(param1, param2). This second solution works fine, but the first not.
Finally, my doubt is: Why the original code (as posted) don't works.

A: Spring will only handle injection dependencies to a class that is constructed by the container. When you call getInstance(), you are allocating the object itself... there is no opportunity there for Spring to inject the dependencies that you have @Autowired.
Your second solution works because Spring is aware of your LovHelper class; it handles constructing it and injecting it into your other class.
If you don't want to mark the class with@Component, you can declare the class as a bean directly in your XML configuration. If you don't want to have it be a singleton, you can set it with prototype scope.
If you really need to manage the class yourself, you could consider looking at @Configurable. I believe it is intended to solve this problem but it requires aspects and I have not played with it myself.

A: Your helper should be context aware, but you can make it static:
@Component
public class LovHelper {

    private static LovHelper instance;

    @PostConstruct
    void init() {
        instance = this;
    }

    // do stuff

In this case static instance will keep reference to Spring aware bean.


Q: Ways to convert a PDF file into byte array..(for flushing out using outputstream())
*

*Is there any other way to convert a file (PDF) into byte array other than using FileInputStream or toByteArray(InputStream input)..

*Is there any method to convert it directly. I found Files.readAllBytes in java.nio.file.* package but it gives ClassNotFoundException in my RAD. I am having Java 8 JDK in my system.

*Is java.nio.file.* package not available in Java 8?

*My requirement is that i should not to stream the file using InputStram.

A: Seems like you're loading the whole content of your file into a byte[] directly in memory, then writing this in the OutputStream. The problem with this approach is that if you load files of 1 or 2 GBs entirely in memory then you will encounter with OutOfMemoryError quickly. To avoid this, you should read the data from InputStream in small chunks and write these chunks in the output stream. Here's an example for file downloading:
BufferedInputStream bis = new BufferedInputStream(
    new FileInputStream(new File("/path/to/folder", "file.pdf")));
ServletOutputStream outStream = response.getOutputStream();
//to make it easier to change to 8 or 16 KBs
//make some tests to determine the best performance for your case
int FILE_CHUNK_SIZE = 1024 * 4;
byte[] chunk = new byte[FILE_CHUNK_SIZE];
int bytesRead = 0;
while ((bytesRead = bis.read(chunk)) != -1) {
    outStream.write(chunk, 0, bytesRead);
}
bis.close();
outStream.flush();
outStream.close();


Q: Java Thread creation process flow I was reading section ThreadPools section 6.2.3 java concurrency in practice by Brian Goetz. A statement I came across is
"Reusing an existing thread instead of creating a new one amortizes thread creation and teardown costs."
1) I wanted to get some metrics involved in the java thread creation process which as we know will involve the creation/allocation of a stack and the program counter register to the created thread. Is there a tool/utility/visual vm tracer/jmx bean that I can use for the same which can give me some indicators on memory and time usage for thread creation. Can some one guide me to the same ?
2) Is there a text which can guide me to the whole process of java thread creation in detail which should cover the respective OS calls to windows ?
Why is creating a Thread said to be expensive? has given me some information, but I wanted to study the internals of java thread creation in detail
Thanks

A: Concerning your second question:

2) Is there a text which can guide me to the whole process of java
  thread creation in detail which should cover the respective OS calls
  to windows ?

This guide, though slightly off topic is great: http://blog.jamesdbloom.com/JVMInternals.html
And the following book The Java Virtual Machine Specification, Java SE 7 Edition (google book link) explains the JVM internals in depth and as such would be my best bet (disclaimer: I had only skimmed through the visible parts)
If that is not good enough, you could always download the source code for the open jdk (7) and crawl through the code...
An excerpt from the open jdk code is this (openjdk\hotspot\src\share\vm\runtime\thread.cpp - c'tor):
// Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
// JavaThread

Thread::Thread() {
  // stack and get_thread
  set_stack_base(NULL);
  set_stack_size(0);
  set_self_raw_id(0);
  set_lgrp_id(-1);

  // allocated data structures
  set_osthread(NULL);
  set_resource_area(new ResourceArea());
  set_handle_area(new HandleArea(NULL));
  set_active_handles(NULL);
  set_free_handle_block(NULL);
  set_last_handle_mark(NULL);

  // This initial value ==> never claimed.
  _oops_do_parity = 0;

  // the handle mark links itself to last_handle_mark
  new HandleMark(this);

  // plain initialization
  debug_only(_owned_locks = NULL;)
  debug_only(_allow_allocation_count = 0;)
  NOT_PRODUCT(_allow_safepoint_count = 0;)
  NOT_PRODUCT(_skip_gcalot = false;)
  CHECK_UNHANDLED_OOPS_ONLY(_gc_locked_out_count = 0;)
  _jvmti_env_iteration_count = 0;
  set_allocated_bytes(0);
  _vm_operation_started_count = 0;
  _vm_operation_completed_count = 0;
  _current_pending_monitor = NULL;
  _current_pending_monitor_is_from_java = true;
  _current_waiting_monitor = NULL;
  _num_nested_signal = 0;
  omFreeList = NULL ;
  omFreeCount = 0 ;
  omFreeProvision = 32 ;
  omInUseList = NULL ;
  omInUseCount = 0 ;

  _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true);
  _suspend_flags = 0;

  // thread-specific hashCode stream generator state - Marsaglia shift-xor form
  _hashStateX = os::random() ;
  _hashStateY = 842502087 ;
  _hashStateZ = 0x8767 ;    // (int)(3579807591LL & 0xffff) ;
  _hashStateW = 273326509 ;

  _OnTrap   = 0 ;
  _schedctl = NULL ;
  _Stalled  = 0 ;
  _TypeTag  = 0x2BAD ;

  // Many of the following fields are effectively final - immutable
  // Note that nascent threads can't use the Native Monitor-Mutex
  // construct until the _MutexEvent is initialized ...
  // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
  // we might instead use a stack of ParkEvents that we could provision on-demand.
  // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
  // and ::Release()
  _ParkEvent   = ParkEvent::Allocate (this) ;
  _SleepEvent  = ParkEvent::Allocate (this) ;
  _MutexEvent  = ParkEvent::Allocate (this) ;
  _MuxEvent    = ParkEvent::Allocate (this) ;

#ifdef CHECK_UNHANDLED_OOPS
  if (CheckUnhandledOops) {
    _unhandled_oops = new UnhandledOops(this);
  }
#endif // CHECK_UNHANDLED_OOPS
#ifdef ASSERT
  if (UseBiasedLocking) {
    assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
    assert(this == _real_malloc_address ||
           this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
           "bug in forced alignment of thread objects");
  }
#endif /* ASSERT */
}


Q: How do I add double-quotes to each item in my input string? I'm trying to concatenate a string into an object, with the format of "test@yahoo.com,abc@gmail.com,123@yahoo.com". However, the parameter is expecting every value in the string to be surrounded by quotes, such as ""test@yahoo.com","abc@gmail.com","123@yahoo.com"". The error is "Property validation failed", and it is expecting a System.String. How do I go about resolving this?
The exact lines of code are...
$existingconfig = get-mailboxjunkemailconfiguration $_.address
$existingconfig.trustedsendersanddomains += $_.approved_senders

where $_.approved_senders = "test@yahoo.com,abc@gmail.com,123@yahoo.com"

A: Using Get-MailboxJunkEmailConfiguration -Identity BSmith | Get-Memeber shows that the TrustedSendersAndDomains property is a multiValuedProperty string, i.e. an Array.  You can try changing the value of the $_.approved_senders into an array with -Split
$existingconfig = get-mailboxjunkemailconfiguration $_.address
$existingconfig.trustedsendersanddomains += ($_.approved_senders -Split ",")


Q: Get XML Node while using tsql I would like to know, if anyone can help how to get NODE name o XML variable using TSQL.
<ROOT>
<IDS>
<ID>
<NAME>bla1</NAME>
<AGE>25</AGE>
</ID>
<ID>
<NAME>bla2</NAME>
<AGE>26</AGE>
</ID>
</IDS>
</ROOT>

After my query, I should be able to get the nodes names: NAME, AGE
My SQL server is MSSQL 2005.

A: This would give you the node names for the children of the first ID node:
DECLARE @x xml

SET @x = '<ROOT>
<IDS>
<ID>
<NAME>bla1</NAME>
<AGE>25</AGE>
</ID>
<ID>
<NAME>bla2</NAME>
<AGE>26</AGE>
</ID>
</IDS>
</ROOT>'

SELECT T.c.value('local-name(.)', 'varchar(50)')
FROM @x.nodes('/ROOT/IDS/ID[1]/*') T(c)


Q: OLS Regression Results R-squared value ca r2_squared by scikitlearn I followed a tutorial online and used OLS to build the model (from statsmodel!) The OLS analysis result gave me an amazing R^2 value (0.909). However, when I tried using the r2_score function by scikit-learn to evaluate the R^2 score, I only got 0.68.
Can someone tell what the difference is here?
The dataset came from here: https://www.kaggle.com/harlfoxem/housesalesprediction
Attached is my code!
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, accuracy_score, r2_score
import matplotlib.pyplot as plt
import seaborn as sns

import statsmodels.api as sm

df = pd.read_csv('kc_house_data.csv')

df = df.drop(['id','date'], axis = 1)

X = df.iloc[:, 1:]
y= df.iloc[:, 0]

X = sm.add_constant(X)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)

reg_OLS = sm.OLS(endog=y_train, exog=X_train).fit()

reg_OLS.summary()

y_pred = reg_OLS.predict(X_test)

print(r2_score(y_test, y_pred))

Output from OLS Regression Results
OLS Regression Results
Dep. Variable:  price   R-squared (uncentered): 0.909
Model:  OLS Adj. R-squared (uncentered):    0.909
Method: Least Squares   F-statistic:    8491.
Date:   Thu, 17 Mar 2022    Prob (F-statistic): 0.00
Time:   23:36:48    Log-Likelihood: -1.9598e+05
No. Observations:   14408   AIC:    3.920e+05
Df Residuals:   14391   BIC:    3.921e+05
Df Model:   17
Covariance Type:    nonrobust
coef    std err t   P>|t|   [0.025  0.975]
bedrooms    -2.898e+04  2217.526    -13.068 0.000   -3.33e+04   -2.46e+04
bathrooms   3.621e+04   3845.397    9.416   0.000   2.87e+04    4.37e+04
sqft_living 100.2140    2.690   37.257  0.000   94.942  105.486
sqft_lot    0.2609  0.057   4.563   0.000   0.149   0.373
floors  1.201e+04   4187.373    2.867   0.004   3798.844    2.02e+04
waterfront  6.237e+05   2.01e+04    31.012  0.000   5.84e+05    6.63e+05
view    5.237e+04   2566.027    20.410  0.000   4.73e+04    5.74e+04
condition   2.844e+04   2774.191    10.250  0.000   2.3e+04 3.39e+04
grade   9.613e+04   2558.509    37.571  0.000   9.11e+04    1.01e+05
sqft_above  63.2770 2.638   23.985  0.000   58.106  68.448
sqft_basement   36.9370 3.127   11.813  0.000   30.808  43.066
yr_built    -2529.7423  80.708  -31.344 0.000   -2687.940   -2371.544
yr_renovated    13.0704 4.307   3.035   0.002   4.629   21.512
zipcode -510.0820   21.216  -24.043 0.000   -551.667    -468.497
lat 6.084e+05   1.27e+04    47.725  0.000   5.83e+05    6.33e+05
long    -2.076e+05  1.55e+04    -13.371 0.000   -2.38e+05   -1.77e+05
sqft_living15   33.6926 3.996   8.432   0.000   25.860  41.525
sqft_lot15  -0.4850 0.092   -5.275  0.000   -0.665  -0.305
Omnibus:    9620.580    Durbin-Watson:  1.997
Prob(Omnibus):  0.000   Jarque-Bera (JB):   363824.963
Skew:   2.694   Prob(JB):   0.00
Kurtosis:   27.021  Cond. No.   1.32e+17

Output from r2_score
0.6855578295481021

A: Your R2=0.909 is from the OLS on the train data, while the R2_score=0.68 is based on the correlation of the test data.
Try predicting the train data and use R2_score on the train and predicted train data.


Q: MysqL: Perform fulltext search over multiple columns and 100 % match I'd like to do a fulltext search over multiple columns in a MySQL database, only using 1 Input field to search for addresses.
So far my code works but I also get rows returned where not all search words are present.
SELECT *, ((1.3 * (MATCH (city) AGAINST ('+$search*' IN BOOLEAN MODE)))
+ (0.6 * (MATCH (name, zip, str) AGAINST ('+$search*' IN BOOLEAN MODE)))) AS relevance
FROM service
WHERE (MATCH (name, city, zip, str) AGAINST ('+$search*' IN BOOLEAN MODE))
HAVING relevance > 0 ORDER BY relevance DESC LIMIT 10

This could return sth like:
$search = "Anderson City ZIP"

1. Anderson, City, ZIP, street x
2. Anderson, City, ZIP, street y
3. Smith, City, ZIP, street x

So line 3 is wrong because it does not contain Anderson but Smith.
I already tried to add the + operator in the $search string (Anderson City ZIP --> +Anderson +City +ZIP) but then the result often does not show anything.
Is it possible to return only rows with 100 % match?

A: The plus sign is the good thing to do but you have to be sure that one of the strings you are searching for is not in more than 50% of the rows of your table.
Also consider using  quotes to match the full expression: +"Anderson City ZIP"


Q: Dynamic or Conditional display of Jenkins job's parameters (rather than their value population) Let's say I have two(or more) types of projects: app(Application) and svc (Service) and I have created a Jenkins job (common job) which have bunch of parameters. This common job might call another downstream/individual project type jobs (Trigger other project builds etc and pass respective parameters) but it's out of scope of this question.
For ex:
PROJ_TYPE  (a choice parameter type with values: app, svc)
Param2     (of some type)
Param3     (of Cascading type i.e. it depends upon the value of parent parameter PROJ_TYPE).
Param4     (Lets say I want to show this parameter only when PROJ_TYPE is selected as "app")
Param5     (of some type)
Param6     (Lets say I want to show this parameter only when PROJ_TYPE is selected as "svc". This parameter can be of any type i.e. choice, dynamic, extended choice, etc )
If I have the above parameters in a Jenkins job, then Jenkins job will show / prompt all of the parameters when a user will try to build (i.e. Build with Parameters).
Is it possible in Jenkins to show parameter (Param4) only if PROJ_TYPE parameter was selected as app otherwise, I don't want to show this parameter at all -or somehow if it's possible to grey it out? i.e. in this case, the job will show only PROJ_TYPE, Param2, Param3, Param4 and Param5 (and will not show Param6 or it's disabled/greyed out).
Similarly, I want to show parameter (Param6) only if PROJ_TYPE parameter was selected as svc otherwise, I don't want to show this parameter at all -or somehow if it's possible to grey it out? i.e. in this case, the job will show only PROJ_TYPE, Param2, Param3, Param5 and Param6 (and will not show Param4 or it's disabled/greyed out).

A: I know this is an oldie, but I had been searching for something similar until I found Active Choices Plugin. It doesn't hide the parameters, but it's possible to write a Groovy script (either directly in the Active Choices Parameter or in Scriptler) to return different values. For example:
Groovy
if (MY_PARAM.equals("Foo")) {return ['NOT APPLICABLE']}
else if (MY_PARAM.equals("Bar")) {return ['This is the only choice']}
else if (MY_PARAM.equals("Baz")) {return ['Bazoo', 'Bazar', 'Bazinga']}
/Groovy
In this example MY_PARAM is a parameter in the Jenkins job. As long as you put 'MY_PARAM' in the Active Choices 'Referenced Parameters' field the script will re-evaluate the parameter any time it is changed and display the return value (or list of values) which match.
In this way, you can return a different list of choices (including a list of one or even zero choices) depending on the previous selections, but I haven't found a way to prevent the Parameter from appearing on the parameters page. It's possible for multiple Active Choice Parameters to reference the same Parameter, so the instant someone selects "App" or "Svc" all the irrelevant parameters will switch to 'Not Applicable' or whatever suits you. I have played with some HTML text color as well, but don't have code samples at hand to share.
Dirk

A: According to the description you may do this with Dynamic-Jenkins-Parameter plugin:

A Jenkins parameter plugin that allows for two select elements. The second select populates values depending upon the selection made for the first select.

Example provided on the wiki does exactly what you need (at least for one conditional case). I didn't try it by myself.

A: @derik It worked! for me
the second list is populating based on the choice of the first element.
I used Active Choice reactive parameter plugin,
the requirement was the first param will list my servers,
based on the fist selection, the second parm is to connect to selected server and list the backup.
so the list of available backup will the shown here to restore.

*

*enabled parameterized.

*Select Choice Parameter
Name: Server
Choices : Choose..
       qa
       staging
       master
Description : Select the server from the list

*Add new parameter "Active Choice Reactive Parameter"
Name: Backup
Script: Groovy Script
def getbackupsqa = ("sshpass -f  /opt/installer/pass.txt /usr/bin/ssh -p 22 -o StrictHostKeyChecking=no myuser@111.22.33.44 ls /opt/jenkins/backup").execute()

if (Server.equals("Choose..")) {return ['Choose..'] }
else if (Server.equals("qa")) {return getbackupsqa.text.readLines()}
else if (Server.equals("staging")) {return ['Staging server not yet configured']}
else if (Server.equals("master")) {return ['Master server not yet configured']}
Description : Select the backup from the list
Referenced parameters : Server
The result as here


Q: R: Way to map over all entries in a sparse matrix I have a sparse matrix created from R's Matrix package. I would like to iterate over each entry in the matrix and perform an operation, saving the result in another sparse matrix with the same indexes as the original matrix.
For example, let's say I have sparse matrix A:
1 . 1
2 . .
. . 4

ColSums would look like:
3 . 5

RowSums would look like:
2
2
4

I would like to iterate over A and do this
(1,1) > 3*2
(2,1) > 2*3
(1,3) > 2*5
(3,3) > 4*5

Creating B:
6 . 10
6 . .
. . 20

How would I go about doing this in a vectorized way?
I would think the function foo would look like:
B=fooMap(A,fun)

And fun would look like:
fun(row,col) = RowSums(row) * ColSums(col)

What's fooMap?
EDIT:
I went with flodel's solution. It uses summary to convert the sparse matrix into an i,j,x data frame, then uses with & friends to perform an operation on that frame, and then turns the result back into a sparse matrix. With this technique, the with/within operator is fooMap; the sparse matrix just has to be converted into the i,j,x data frame first so that with/within can be used.
Here's a one-liner that solved this particular problem.
B = with(summary(A), sparseMatrix(i=i, j=j, x = rowSums(A)[i] * colSums(A)[j]))

A: Whenever I have element-wise operations on sparse matrices, I go back and forth between the matrix itself and its summary representation:
summ.B <- summary(A)
summ.B <- within(summ.B, x <- rowSums(A)[i]*colSums(A)[j])
B <- sparseMatrix(i = summ.B$i, j = summ.B$j, x = summ.B$x)
B
# 3 x 3 sparse Matrix of class "dgCMatrix"
#
# [1,] 6 . 10
# [2,] 6 .  .
# [3,] . . 20

A: Here's an approach that works with sparse matrices at each step.
## Load library and create example sparse matrix
library(Matrix)
m <- sparseMatrix(i = c(1,2,1,3), j = c(1,1,3,3), x = c(1,2,1,4))

## Multiply each cell by its respective row and column sums.
Diagonal(x = rowSums(m)) %*% (1*(m!=0)) %*% Diagonal(x = colSums(m))
# 3 x 3 sparse Matrix of class "dgCMatrix"
#
# [1,] 6 . 10
# [2,] 6 .  .
# [3,] . . 20

(The 1* in (1*(m!=0)) is being used to coerce the logical matrix of class "lgCMatrix" produced by m!=0 back to a numeric matrix class "dgCMatrix". A longer-winded (but perhaps clearer) alternative would to use as(m!=0, "dgCMatrix") in its place.)


Q: Cant Get Bootstrap Table To Resize Im trying to get a bootstrap table to resize so that the maximum content height is 200px and anything greater will scroll.
I have the css for the table set to:
table.jSpeeds tr:hover, table.jSpeeds tr td:hover{
  cursor:pointer;
}

table.table-fixed thead {
  width: 97%;
}
table.table-fixed tbody {
  height: 230px;
  overflow-y: auto;
  width: 100%;
}

& HTML:

Time	Speed

TestRow	TestVal

However the table is still the height and width of the page. I was wondering if anyone could help.
Please see the JSBin example here
Thanks.

A: Use bootstrap's responsive-table. Wrap your
 with this.

    // your table here

Then add the class fix-table-height on the wrapper so you could define the height of the wrapper. In your case you want 200px;. So you can do this :
.fix-table-height{
    max-height:200px;
}

This is the output jsFiddle

A: You'll need to change your table's body and rows display to block. Do something like this:
table.jSpeeds tr:hover, table.jSpeeds tr td:hover{
  cursor:pointer;
}

table.table-fixed thead {
  width: 100%;
}

table.table-fixed tbody {
  height: 230px;
  overflow-y: auto;
}

table.table-fixed tbody,
table.table-fixed tr {
  display: block;
  width: 100%;
}

table.table-fixed th,
table.table-fixed td {
  width: 300px;
}

EDIT
Since I was challenged to give a robust solution, here is comes:
table.jSpeeds tr:hover, table.jSpeeds tr td:hover{
  cursor:pointer;
}

table.table-fixed thead {
  width: 100%;
}

table.table-fixed tbody {
  height: 230px;
  overflow-y: auto;
}

table.table-fixed tbody,
table.table-fixed tr {
  display: block;
  width: 100%;
}

table.table-fixed th,
table.table-fixed td {
  display: block;
  float: left;
  width: 50%;
}

Gist Link

A: just adjust your css to this:
tbody {
    display: block;
    overflow: auto;
    height: 230px;
}

tbody tr {
    display: table;
    width: 100%;
    table-layout: fixed;
}


Q: How might I add a watermark effect to an image in Android? I have an image with frames and I need to add a watermark effect. How might I do this?

A: I found great tutorial on Android Image Processing here.
public static Bitmap mark(Bitmap src, String watermark, Point location, Color color, int alpha, int size, boolean underline) {
    int w = src.getWidth();
    int h = src.getHeight();
    Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());

    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(src, 0, 0, null);

    Paint paint = new Paint();
    paint.setColor(color);
    paint.setAlpha(alpha);
    paint.setTextSize(size);
    paint.setAntiAlias(true);
    paint.setUnderlineText(underline);
    canvas.drawText(watermark, location.x, location.y, paint);

    return result;
}

Thanks to Pete Houston who shares such useful tutorial on basic image processing.

A: It seems you are looking for a waterrippleeffect as this one. Checkout the complete source code. Also check the screenshot how does the effect look like.

A: For others reference, if you want to add the logo of your application (which is in your drawable folder(s)) on top of image use following method:
private Bitmap addWaterMark(Bitmap src) {
        int w = src.getWidth();
        int h = src.getHeight();
        Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(src, 0, 0, null);

        Bitmap waterMark = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.logo);
        canvas.drawBitmap(waterMark, 0, 0, null);

        return result;
    }

A: If someone is still searching for this, I found a good solution here
It adds a watermark to the bottom right portion and scales it according to the source image which was exactly what I was looking for.
/**
 * Embeds an image watermark over a source image to produce
 * a watermarked one.
 * @param source The source image where watermark should be placed
 * @param watermark Watermark image to place
 * @param ratio A float value < 1 to give the ratio of watermark's height to image's height,
 *             try changing this from 0.20 to 0.60 to obtain right results
 */
public static Bitmap addWatermark(Bitmap source, Bitmap watermark, float ratio) {
    Canvas canvas;
    Paint paint;
    Bitmap bmp;
    Matrix matrix;
    RectF r;

    int width, height;
    float scale;

    width = source.getWidth();
    height = source.getHeight();

    // Create the new bitmap
    bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG);

    // Copy the original bitmap into the new one
    canvas = new Canvas(bmp);
    canvas.drawBitmap(source, 0, 0, paint);

    // Scale the watermark to be approximately to the ratio given of the source image height
    scale = (float) (((float) height * ratio) / (float) watermark.getHeight());

    // Create the matrix
    matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Determine the post-scaled size of the watermark
    r = new RectF(0, 0, watermark.getWidth(), watermark.getHeight());
    matrix.mapRect(r);

    // Move the watermark to the bottom right corner
    matrix.postTranslate(width - r.width(), height - r.height());

    // Draw the watermark
    canvas.drawBitmap(watermark, matrix, paint);

    return bmp;
}

And it is well commented which is what is a huge plus!

A: In Kotlin:
Note: Its just modified code of above answers
private fun mark(src: Bitmap, watermark: String): Bitmap {
        val w = src.width
        val h = src.height
        val result = Bitmap.createBitmap(w, h, src.config)
        val canvas = Canvas(result)
        canvas.drawBitmap(src, 0f, 0f, null)
        val paint = Paint()
        paint.color = Color.RED
        paint.textSize = 10f
        paint.isAntiAlias = true
        paint.isUnderlineText = true
        canvas.drawText(watermark, 20f, 25f, paint)
        return result
    }

val imageBitmap = mark(yourBitmap, "Your Text")
binding.meetProofImageView.setImageBitmap(imageBitmap)

A: You can use androidWM to add a watermark into your image, even with invisible watermarks:
add dependence:
dependencies {
  ...
  implementation 'com.huangyz0918:androidwm:0.2.3'
  ...
}

and java code:
 WatermarkText watermarkText = new WatermarkText(“Hello World”)
                    .setPositionX(0.5)
                    .setPositionY(0.5)
                    .setTextAlpha(100)
                    .setTextColor(Color.WHITE)
                    .setTextFont(R.font.champagne)
                    .setTextShadow(0.1f, 5, 5, Color.BLUE);

 WatermarkBuilder.create(this, backgroundBitmap)
                    .loadWatermarkText(watermarkText)
                    .getWatermark()
                    .setToImageView(backgroundView);

You can easily add an image type watermark or a text watermark like this, and the library size is smaller than 30Kb.

A: I tried a few libraries mentioned in other posts, like this, but unfortunately it is missing, and not downloadable now. So I followed AndroidLearner 's answer above, but after tweaking the code a little bit, for those of you who are having trouble rotating the watermark, and what values are valid for the various methods of Paint class, so that the text shows rotated at an angle(like most of the company watermarks do), you can use the below code.
Note that, w and h are the screen width and height respectively, which you can calculate easily, there are tons of ways you can find on stackoverflow only.
public static Bitmap waterMarkBitmap(Bitmap src, String watermark) {
    int w = src.getWidth();
    int h = src.getHeight();
    Bitmap mutableBitmap = Utils.getMutableBitmap(src);
    Bitmap result = Bitmap.createBitmap(w, h, mutableBitmap.getConfig());

    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(src, 0f, 0f, null);

    Paint paint = new Paint();
    paint.setColor(Color.RED);
    paint.setTextSize(92f);
    paint.setAntiAlias(true);
    paint.setAlpha(70);  // accepts value between 0 to 255, 0 means 100% transparent, 255 means 100% opaque.
    paint.setUnderlineText(false);
    canvas.rotate(45, w / 10f, h / 4f);
    canvas.drawText(watermark, w / 10f, h / 4f, paint);
    canvas.rotate(-45, w / 10f, h / 4f);

    return result;
}

It rotates the text watermark by 45 degrees, and places it at the centre of the bitmap.
Also note that, in case you are not able to get watermark, it might be the case that the bitmap you are using as source is immutable. For this worst case scenario, you can use below method to create a mutable bitmap from an immutable one.
public static Bitmap getMutableBitmap(Bitmap immutableBitmap) {
    if (immutableBitmap.isMutable()) {
        return immutableBitmap;
    }

    Bitmap workingBitmap = Bitmap.createBitmap(immutableBitmap);
    return workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
}

I found above method inside here. I have tested using both the methods in my application, and it works perfectly after I added above tweaks. Try it and let me know if it works or not.

A: use framelayout. put two imageviews inside the framelayout and specify the position of the watermark imageview.


Q: Request jenkins rest api using the authtoken got from by organization's SSO I have a webportal where user login using our organization's SSO, After logging in i get the authtoken for the logged in session.
And currently i have the Jenkins authentication setup using organization LDAP.
From our webportal we will be issuing some jenkins REST APIs. I can see jenkins support API token for the REST APIs.
1. All our jenkins users don't have the token generated
2. Even they do generate, we will have to map each users id with token , which would be very bad.
Is there any way to execute rest api with the auth token got from SSO login ?


Q: Character entry causing infinite loop in C Ok, so I've searched several places for an answer to this, and I found the answer to the same problem in C++, but it involved clearing cin and that stuff, and I'm not sure how to translate that to C. I apologize in advance if this was, in fact, answered somewhere else, and I just missed it. Also, keep in mind that I'm basically teaching myself C, and I don't know much beyond what you see in this code.
Basically, my problem is this: I am running a loop that asks for input and then uses a switch statement to choose what happens. The switch takes an int, and it works fine with any numerical entry. When you enter a char, however, it just loops infinitely, giving no chance to input anything else.
Assuming this is the same problem as it was in the C++ examples I looked up - and I'm not 100% sure it is - when I enter a char it gets added to the buffer, and never gets cleared, so each time it loops the invalid input gets used again. Clearing the buffer seemed simple enough in C++, but I was unable to find anything I could understand in C.
Here's my code, for reference:
int main()
{

  while(1)
  {
    printf("(1-10) -> Run a program | (-1) -> Display menu | (0) -> Quit : ");

    int quit = 0;
    int select;
    scanf("%d", &select);
    switch(select)
    {
      case 1:
        printf("%s", pgmRun);
        helloWorld();
        printf("%s", pgmEnd);
        break;

      //More cases here

      case 0:
        quit = 1;
        break;
      default:
        printf("\n");
        printf("Error: Invalid input\n");
        printf("\n");
    }

    if(quit == 1)
      break;
  }
return 0;
}

Thanks in advance for your help, and sorry for such a lengthy post. I tend to be long-winded. :P

A: fflush(stdin) has undefined behavior. If you want to discard characters entered after the scanf() call, you can read and discard them.
You can use getchar() to clear the character.


Q: Wpf: Prism + MVVM: Changing Modules/Views I'm developing a WPF application using MVVM + Prism.
The Shell is devided into two regions: Menu + MainScreenArea.
The Menu includes navigation: Search Entity, Add Entity, Edit Entity. And Basically the mainScreenArea should load the appropriate module/View. If Search Entity is chosen in the Menu Region, The mainScreenArea should display the SearchEntity Module/View.
I still haven't coded it, but I think I will create A module for each purpose: SearchEntityModule, AddEntityModule and etc.
Then the MainWorkArea will change modules on demand by the corresponding click on Menu Region.
Now, how do I change between the modules in the MainScreenArea Region? Should I load the nameOfModule to eventAggregator from MenuRegion and and MainScreenArea will get the name of screen from the aggregator?
Anyways, I'm new to this, so if I'm going in the wrong direction, please post me your suggestion. Thanks!

A: The prism documentation has a whole section on navigation. The problem with this question is that there are a number of different ways to go when loading modules on demand. I have posted a link that I hope leads you in the right direction. If it does, please mark this as answered. thank you
http://msdn.microsoft.com/en-us/library/gg430861(v=pandp.40).aspx

A: As has been said, there are a number of ways of accomplishing this. For my case, I have a similar shell that has a nav region and a main region, and my functionality is broken into a number of modules. My modules all add their own navigation view to that nav region (in the initialise of the module add their own nav-view to the nav-region). In this way my shell has no knowledge of the individual modules and the commands they may expose.
When a command is clicked the nav view model it belongs to does something like this:
/// <summary>
/// switch to the view given as string parameter
/// </summary>
/// <param name="screenUri"></param>
private void NavigateToView(string screenUri)
{
    // if there is no MainRegion then something is very wrong
    if (this.regionManager.Regions.ContainsRegionWithName(RegionName.MainRegion))
    {
        // see if this view is already loaded into the region
        var view = this.regionManager.Regions[RegionName.MainRegion].GetView(screenUri);
        if (view == null)
        {
            // if not then load it now
            switch (screenUri)
            {
                case "DriverStatsView":
                    this.regionManager.Regions[RegionName.MainRegion].Add(this.container.Resolve<IDriverStatsViewModel>().View, screenUri);
                    break;
                case "TeamStatsView":
                    this.regionManager.Regions[RegionName.MainRegion].Add(this.container.Resolve<ITeamStatsViewModel>().View, screenUri);
                    break;
                case "EngineStatsView":
                    this.regionManager.Regions[RegionName.MainRegion].Add(this.container.Resolve<IEngineStatsViewModel>().View, screenUri);
                    break;
                default:
                    throw new Exception(string.Format("Unknown screenUri: {0}", screenUri));
            }
            // and retrieve it into our view variable
            view = this.regionManager.Regions[RegionName.MainRegion].GetView(screenUri);
        }
        // make the view the active view
        this.regionManager.Regions[RegionName.MainRegion].Activate(view);
    }
}

So basically that module has 3 possible views it could place into the MainView, and the key steps are to add it to the region and to make it active.


Q: MySQL LEFT JOIN Query with WHERE clause Hope someone can help as I am having a hard time understanding how to query properly
I have a Member table and a Member_Card table. Member_Card has a column Member, so the card is associated to a member. Both tables have a LastModifiedDate column. A member can have none, one or several cards.
I need to return all members whose LastModifiedDate >= sinceDate (given date) OR whose card (if any) LastModifiedDate >= sinceDate.
Imagine sinceDate is 2013-01-01 00:00:00. I want to output something like this:
[{
    "Id": "001O000000FsAs7IAF",
    "LastModifiedDate": 2013-01-01 00:00:00,
    "Member_Card": null
}, {
    "Id": "001O000000FrpIXIAZ",
    "LastModifiedDate": 2012-12-12 00:00:00,

    "Member_Card": [{
        "Id": "a00O0000002w8FGIAY",
        "Member": "001O000000FhDSoIAN",
        "LastModifiedDate": 2013-01-01 00:00:00

    }, {
        "Id": "a00O0000002uYMtIAM",
        "Member": "001O000000FhDSoIAN",
        "LastModifiedDate": 2012-12-12 00:00:00
    }]
}, {
    "Id": "001O000000FsAg7IAF",
    "LastModifiedDate": 2013-01-01 00:00:00,
    "Member_Card": [{
        "Id": "a00O0000002w8FFIAY",
        "Member": "001O000000FhDSoIAN",
        "LastModifiedDate": 2012-12-12 00:00:00
    }]
}]

The 1st is a member with a matching LastModifiedDate without cards. The 2nd is a member with a non-matching LastModifiedDate, but he has 2 cards associated, and 1 of them has a matching LastModifiedDate. The 3rd one is a member with a matching LastModifiedDate with a card.
Thanks to SO I got the following query:
SELECT member.*,card.* from member inner join (
SELECT distinct member.id as  mid FROM Member
INNER JOIN Member_Card
    ON Member_Card.Member = Member.id
and ( Member.LastModifiedDate >= sinceDate
    OR Member_Card.LastModifiedDate >= sinceDate ) ) a on a.mid=member.id
inner join member_card card on card.member=a.mid

Which works fine but is missing the case where the member doesn't have any card associated.
I tried to change some INNER JOINs to LEFT JOINs but then it's ignoring the date comparison :-(
Can you help me with this one?

A: You want to move the date check to the where of the inner query.
Try something like:
SELECT member.*,card.*
FROM member
LEFT JOIN member_card card on card.member=member.id
WHERE member.id IN (
    SELECT DISTINCT m.id FROM Member m
        LEFT JOIN Member_Card mc ON (mc.Member = m.id)
        WHERE ( m.LastModifiedDate >= sinceDate
        OR mc.LastModifiedDate >= sinceDate )
)

A: Try this... (yet to be tested)
SELECT * FROM member m1
JOIN card c1 ON c1.member = m1.id
WHERE m1.id IN (
SELECT DISTINCT m.id from member m
JOIN card c ON c.member = m.id
WHERE (c.LastModifiedDate >=sinceDate  OR m.LastModifiedDate >= sinceDate))

A: You can try like this,
SELECT o.status, o.date, c.name
FROM cliente c
LEFT JOIN orders o
ON c.id=o.id
WHERE o.date = '2/1/2015'


Q: FileNotFoundException : /storage/emulated/0/xyz/a bc/abc_06-07-2017 06-12-121481589883.amr I am trying to upload file from my device storage to cloud but whenever I try to upload I am getting following excaption.
java.io.FileNotFoundException: /storage/emulated/0/xyz/a bc/abc_06-07-2017 06-12-121481589883.amr: open failed: ENOENT (No such file or directory)

Here is my code.
        DropboxInstance objDropboxInstance = new DropboxInstance();
        String filePath = intent.getExtras().getString("filePath");
        // filePath is  = /storage/emulated/0/xyz/a bc/abc_06-07-2017 06-12-121481589883.amr
        StringBuilder sb = new StringBuilder();
        InputStream is;
        String name = "abc_06-07-2017 06-12-121481589883";
        try {
            File file = new File(filePath);

            is = new FileInputStream(file);
            long size = f.length();
            objDropboxInstance.getDropBoxStorage(this).upload("/" + name, is, size, true);

        }
        catch(IOException ioe) {
            ioe.printStackTrace();
        }

I don't know what's happening. I think path is correct. But I am not getting why I am getting this error. Please suggest me.