text:
Q: d3 histogram doesn't show anything I'm trying to draw an histogram using d3.js, but it doesn't show anything, I don't know whats's wrong with my following code histogram.js, the data is available here:
// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 40};
    width = 460 //- margin.left - margin.right;
    height = 400 //- margin.top - margin.bottom;

//var height_histogram = 200,
  //width_histogram = 700;

// append the svg object to the body of the page
let svg = d3.select("#histogram-density")
          .append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
          .attr("transform",
              "translate(" + margin.left + "," + margin.top + ")");

d3.tsv("data/france.tsv")
  .row((d,i)=> {
    return {
      codePostal: +d["Postal Code"],
      inseeCode : +d.inseecode,
      place: d.place,
      longitude: +d.x,
      latitude: +d.y,
      population: +d.population,
      density: +d.density
    };
  })
  .get((error,rows) => {
    console.log("Loaded "+ rows.length + " rows");

            //console.log("First row", rows[0]);
            //console.log("Last  row", rows[rows.length-1]);
            //console.log("First row", rows[4]);
            //console.log("First row", rows[2992]);
            //console.log("First row", rows[2399]);
            //console.log("First row", rows[1200]);
            //console.log("First row", rows[20000]);

            dataset = rows.filter(function(row){
                if (isNaN(row.longitude)) {return false;
                }
                else {return true;}
            });

            var x = d3.scaleLinear()
                      .domain([0, d3.max(rows, function(d) { return +d.population ;})])
                      .range([0, width]);

            svg.append("g")
               .attr("transform", "translate(0," + height + ")")
               .call(d3.axisBottom(x));

            var histogram = d3.histogram()
                  .value(rows.population)
                  .domain(x.domain())
                  .thresholds(x.ticks(70));

            var bins = histogram(dataset);

            var y = d3.scaleLinear()
                      .range([height, 0])
                .domain([0, d3.max(bins, (d)=> d.length)]);

                svg.append("g")
                   .call(d3.axisLeft(y));

            svg.selectAll("rect")
              .data(bins)
              .enter()
              .append("rect")
                .attr("x", d => x(d.x0) + 1)
                .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; })
                .attr("width", function(d) { return x(d.x1) - x(d.x0) -1 ; })
                .attr("height", function(d) { return height - y(d.length); })
                .style("fill", "#9b59b6 ")

  });

The following is the my index.html:

    <meta charset="utf-8">

    <title>Hello, France (D3)</title>
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">

Thank you for your help


text:
Q: How to get pvob name by a given clearcase stream (windows)? Let's say user raise a request:

I'm unable to deliver form stream "spider_dev"

And that user didn't mention view name as well.
How do I get the PVOB name?
Our ClearCase environment is too big (around 300 vobs). It's very difficult to go each and every vob and check.

A: Assume you have been provided only the stream name "spider_dev"and nothing else. After shaming the developer for not helping me help him, consider the following commands to cycle thru the vobs and locate the stream (I have not worked in multi-site, so YMMV, also tagged as Windows, so conversion to PowerShell/DOSShell req'd):
MY_STREAM=spider_dev   # the stream you're looking for
Get a list of all the vobs:
VOB_LIST=$(cleartool lsvob| grep ucmvob| cut -c3-| awk '{print $1}')
# list all vobs, match ucmvob, chop the active indicator (*), print the value

Cycle through the vobs to find matching dev streams:
MY_STREAM=spider_dev   # the stream you're looking for
for vob in ${VOB_LIST}; do
   for stream in $(cleartool lsproject -obs -fmt "%[dstreams]p\n" -inv ${vob}); do
      if [[ ${stream} == ${MY_STREAM} ]]; then
         echo  "!!! ${stream}@${vob}"
         break
      fi
   done
done

Now that you know where the stream is, find the deliver status:
cleartool deliver -status -stream ${stream}@${vob}
The result will be of the form:
Deliver operation in progress on stream "stream:spider_dev@/vobs/my_pvob"
    Started by "username" on "2016-03-15T12:34:56Z"
    Using integration activity "deliver.activity".
    Using view "user_view".
    Activities will be delivered to the default target stream stream:spider_int@/vobs/my_pvob"
in project "project:spider@/vobs/my_pvob".

Baselines to be delivered:

You can of course wrap this up into a shell command, functions, batch script, etc. as appropriate. We have some 250 vobs w/4000 branches and had scripted many little utilities to help us manage many similar problems, so feel your pain.
Finally, remind the user next time help will be more forthcoming with more details and take inordinately longer when fewer details provided.

A: One possibility is to look for any view named after the stream
cleartool lsview|grep -i spider_dev

(grep is available for Windows, or part of gow: Gnu On Windows)
If those views are also named after the user login, you can refine the search further.
Once you have the view, you have its stream with cleartool lsstream:
cleartool lsstream -l -view view_tag -anc

That should include the extended name of its UCM project (with its pvob).

A: This is not quite possible if you have only the information provided in your example. Ideally, the user should provide the name of the stream in the following format
stream:<stream-name>@<pvob>
This is mandatory as there could be another stream named 'spider_dev' in another PVOB.
If the user does not know his PVOB (that can happen), you should try to get the name of the source VOB, i.e. the VOB containing the source code. If you manage to get the name of the source VOB, you can simply use the "cleartool desc" command. Typically, the command
cleartool desc -l vob:<source-vob-tag>
will list a lot of information, including the hyperlink of the VOB with its PVOB. That's how you would then obtain the name of the PVOB.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Row locks on select I have a stored procedure which does the following:

*

*selects top N from table

*sets these rows as processed

*returns these rows to the client

Here is roughly how I am doing it in Sybase ASE:
set rowcount @count

begin tran get_items
  insert into #temp_table
  select item
  from available_item
  where is_processed = 0

  update available_item
  set is_processed = 1
  from available_item, #temp_table
  where available_item.item = #temp_table.item

  # select the processed items...

commit trans

I am wondering whether there is a race condition here. If two separate processes execute this stored procedure at the same time, could they select and mark processed the same data? Or does having it in a transaction stop this?
If not, is there a way to hold locks on selected rows?

A: Some of the details will depend on your tables locking scheme.  Allpages, pages and row level locking will have different impacts on your ability to run concurrent updates on a single table.  I am assuming a page/row level scheme to allow for concurrency.
Your query will grab an initial shared page/row lock, which will be upgraded to an update lock, which will then be followed by an exclusive row lock on the updated pages/rows.  No other processes will be able to make changes to the selected pages/rows for the duration of the transaction, but another process could read the selected rows prior to your update, which could lead to some inconsistency.
To get around this possibility, you can specify the isolation level in the transaction to either isolation level 2 (repeatable reads), or isolation level 3 (serialization).  You may want to read up on the specifics of each level to decide which you want to enforce, and the trade-offs associate with it.
In your transaction, you would use it like this:
set rowcount @count
set transaction isolation level 2

...

Something to note, is that depending on the number of records you grab in your query, you could trigger a lock upgrade which could prevent your concurrent transactions from executing, even if they are not looking at the same rows as your first transaction.  By default, the server will attempt to escalate to a table lock if it acquires locks on more than 200 pages/rows.  This can be changed either to an explicit value or a range of values and percentage, and is configurable at the server, database or table level.
Relevant Documentation:
Transaction: Maintaining Data Consistency and Recovery
Performance and Tuning Series: Locking and Concurrency Control
Transact-SQL Users Guide 15.7 > Transactions: Maintaining Data Consistency and Recovery


text:
Q: Delphi Matrix and Bounds Rect someone who can help me?
I have an object with the follow properties:
FRect := TRectF( 50, 45, 150, 145 );
FRotationScale := 15;
FRotationCenter := TPointF( 0.5, 0.5 );
FScale := 1;
FScaleCenter := TPointF( 0.5, 0.5 );

with this function i get Matrix for drawing on canvas:
function GetMatrix: TMatrix;
var
  LRotationOffSet: TPointF;
  LScalingOffSet: TPointF;
begin
  LRotationOffSet := TPointF.Create( FRect.Left + FRect.Width * FRotationCenter.X, FRect.Top + FRect.Height * FRotationCenter.Y );
  LScalingOffSet := TPointF.Create( FRect.Left + FRect.Width * FScaleCenter.X, FRect.Top + FRect.Height * FScaleCenter.Y );
  Result :=
    TMatrix.Identity
    * TMatrix.CreateTranslation( FRect.Left, FRect.Top )
    * TMatrix.CreateTranslation( - LRotationOffSet.X, - LRotationOffSet.Y )
    * TMatrix.CreateRotation( DegToRad( FRotationAngle ) )
    * TMatrix.CreateTranslation( LRotationOffSet.X, LRotationOffSet.Y )
    * TMatrix.CreateTranslation( - LScalingOffSet.X, - LScalingOffSet.Y )
    * TMatrix.CreateScaling( FScale, FScale )
    * TMatrix.CreateTranslation( LScalingOffSet.X, LScalingOffSet.Y )
  ;
end;

And works fine:

As you can see with the follow function i can get Bounds Rect:
function BoundsPoints: TArray<TPointF>;
begin
  SetLength( Result, 8 );
    Result[ 0 ] := TPointF.Create( FRect.Left, FRect.Top ) * FMatrix;
    Result[ 1 ] := TPointF.Create( FRect.Left + FRect.Width / 2, FRect.Top ) * FMatrix;
    Result[ 2 ] := TPointF.Create( FRect.Left + FRect.Width, FRect.Top ) * FMatrix;
    Result[ 3 ] := TPointF.Create( FRect.Left + FRect.Width, FRect.Top + FRect.Height / 2 ) * FMatrix;
    Result[ 4 ] := TPointF.Create( FRect.Left + FRect.Width, FRect.Top + FRect.Height ) * FMatrix;
    Result[ 5 ] := TPointF.Create( FRect.Left + FRect.Width / 2, FRect.Top + FRect.Height ) * FMatrix;
    Result[ 6 ] := TPointF.Create( FRect.Left, FRect.Top + FRect.Height ) * FMatrix;
    Result[ 7 ] := TPointF.Create( FRect.Left, FRect.Top + FRect.Height /2 ) * FMatrix;
end;

Now the problem is when i drag some points of Bounds:

As you can see in the picture, I can resize the bounds rect smoothly.
But when i release the mouse, should i calculate the FRect starting from Bounds Rect, how?
I try in this way but failed:
NormalizeRectF( [
  BoundsPoint[ 0 ] * FMatrix.Inverse,
  BoundsPoint[ 2 ] * FMatrix.Inverse,
  BoundsPoint[ 4 ] * FMatrix.Inverse,
  BoundsPoint[ 6 ] * FMatrix.Inverse
)

Please help!!!!
UPDATE
Ok, i try that:
From Matrix Reversed Dragged Bounds Rect i set the new FRect
  FRect.TopLeft :=

    FRect.TopLeft

    + ReversedBoundsRect.TopLeft

  ;

  FRect.BottomRight :=

    FRect.TopLeft

    + ReversedBoundsRect.BottomRight

    - ReversedBoundsRect.TopLeft

  ;

works almost if not for:
1) when FScaleCenter is 0,0 i can drag all corners expect Top and Left otherwise all point of FRect move wrong
2) when FScaleCenter is 0.5,0.5 when i drag all corners, all point of FRect move wrong
3) when FScaleCenter is 1,1 i can drag all corners expect Bottom and Right otherwise all point of FRect move wrong
Same for FRotationCenter!
UPDATE
Common guys!
I have Offset the FRect with follow formula, and work well but only for FRotationCenter = 0, 0!
FRect.OffSet(

        ( - ARect.Left * ( 1 - LCos ) - ARect.Top * LSin ),

        ( ARect.Left * LSin - ARect.Top * ( 1 - LCos ) )

      );

Possible that there is no one who has encountered these troubles, or a mathematical I do not know :( !


text:
Q: Logstash Grok parser I'm new to the log-stash and grok, I need to parse very custom log files. I can't find anywhere a good tutorial to get this done. Tried the syslog example but it's not working in my case.
Example:
Nov 19 00:06:37 srv-fe-05 ssh-server-g3: 2037 Sft_server_open_dir, "2037 Sft_server_open_dir, Directory name: /home/folder1/input, File handle: 007800B000782170, "Success", Session-Id: 162351"
The items I'm looking to extract:

*

*Timestamp: Nov 19 00:06:37 will be added to the current year and stored in the elastic search as timestamp.

*Server host srv-fe-05

*Folder name folder1 from /home/folder1/input

*Success status "Success"

*Session-Id: 162351 from Session-Id: 162351

Any help or directions would be appreciated.
Following the answer I came up with this pattern:
%{SYSLOGTIMESTAMP:logTimestamp} %{USERNAME:sftpServer} %{USERNAME:processName}: %{INT:operationType} %{WORD}, \"%{INT} %{WORD}, %{WORD} %{WORD}: /%{WORD}/%{WORD:clientName}/%{WORD}, %{WORD} %{WORD}: %{WORD:submissionId}, \"%{WORD:status}\", %{WORD}-%{WORD}: %{INT:sessionId}

My 2 new questions are:

*

*How efficient is it? I mean what are the ways to make it more efficient?

A: First, become familiar with the basic built-in grok patterns.  Knowing the basic tools of %{WORD}, %{NUMBER}, etc, will go a long way.
Second, become familiar with the online debuggers (heroku and appspot).  They each have advantages over the other.
Third, start slowly.  In your example, can you match the date and time from the beginning of the string in the debugger?  If so, then try to add a match for the hostname.  Keep moving slowly form left to right until you're all done.
If you look in the core patterns, you'll notice that "nov" only appears once, as part of the pattern %{MONTH}.  Makes sense, right?  But also note that %{MONTH} is part of larger constructs like %{SYSLOGTIMESTAMP} which would match your datetime on one step.
Finally, there are some online guides and tutorials.  Here's one.


text:
Q: Get image path from file reference in Extbase PHP based view (TYPO3) I use a PHP based view to return XML in an Extbase extension (TYPO3 6.2). All works great except for the path of images that needs to be included in the XML.
I use the following to get the file reference:
$user->addChild('event_image', $event->getPerformance()->getEventImage());

The output in XML is:
<event_image>TYPO3\CMS\Extbase\Domain\Model\FileReference:124</event_image>

When I try to get the URL path to the image with this code
$user->addChild('event_image', $event->getPerformance()->getEventImage()->getImage()->getOriginalResource()->getPublicUrl());

I get the following error message:

Fatal error: Call to undefined method
  TYPO3\CMS\Extbase\Domain\Model\FileReference::getImage()

My question: How can I get the URL path from the file reference?

A: If you are not using a fluid template, take a closer look at typo3/sysext/fluid/Classes/ViewHelpers/Uri/ImageViewHelper.php within your TYPO3 installation.
That's basically the function call as if you would use the f:uri.image fluid Viewhelper within your XML template:
<event_image><f:uri.image src="{event_image}" treatIdAsReference="1" /></event_image>

A: There seems to be a typo in your code. The method is called getOriginalResource(), not getOriginalRecource().


text:
Q: Custom theme installed via composer require not showing in setup:static-content:deploy or admin panel I've created my own custom theme and uploaded it to my private package repository. This works fine and downloads my folder into vendor/<vendor>/theme-my-theme
I run:
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy

My theme doesn't list itself in setup:static-content:deploy or in the admin panel. I then install snowdog/theme-blank-sass and this shows up fine.
Any ideas as to how to get Magento to register my theme? Please note that this theme was developed in app/design/frontend and worked fine.
composer.json:
{
    "name": "vendor/theme-my-theme",
    "description": "My Base Theme",
    "type": "magento2-theme",
    "version": "1.0.0",
    "require": {
        "magento/theme-frontend-luma": "100.1.*",
        "magento/framework": "100.1.*"
    },
    "license": [
        "OSL-3.0",
        "AFL-3.0"
    ],
    "autoload": {
        "files": [
            "registration.php"
        ]
    }
}

registration.php:
<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::THEME,
    'frontend/Vendor/my-theme',
    __DIR__
);

theme.xml:
<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
 <title>My Base Theme</title>
 <parent>Magento/luma</parent>
 <media>
     <preview_image>web/images/my-logo.png</preview_image>
 </media>

UPDATE:
I've found the cause of the problem. In Composer's installed.json file my theme declaration is missing the autoload section (as well as description). This means that Composers autoload_files.php isn't getting updated with my autload file registration.php.
Anyone know more about this or how to fix it?


text:
Q: Previously benevolent space-faring dinosaurs become hostile with a sudden discovery I think it is a graphic novel, but I can't remember.
Earth makes contact with space-faring travelers, and they are dinosaur-ish creatures. The first contact is peaceful and benevolent until they discover what we use for fuel.
Then war breaks out and humans need to fight back a technological superior adversary.
Maybe there were superheroes in the mix. I don't remember.

A: The Homecoming (1989) by Barry B. Longyear
This review on Goodreads mentions most of the elements you mention:

*

*"I think it is a graphic novel" - It has illustrations.

*"Earth makes contact with space-faring travelers, and they are dinosaur-ish creatures" - Check.

*"The first contact is peaceful" - Whilst I can't find explicit proof of this it appears to be the case.

*"Then war breaks out and humans need to fight back a technological superior adversary." - There is a war and the dinosaurs (Nitolans) are a technological superior.

*"Maybe there were superheroes in the mix." - The review mentions the possibility of telekinesis so could be where this is coming from.

It was hard to believe that Barry Longyear, the author of "Infinity Hold" and "Sea of Glass", both of which I LOVE (love love), penned this banal, super-white-bread tale of dinosaurs arriving in their spaceships to reclaim the Earth they left so long ago. It read like the script of one of those cheesy 'Amazing Stories' or 'Outer Limits' television shows from the 80s. The illustrations were pretty awful, too. The dinosaurs looked like creepy anorexic chickens and the human protagonist was a strange boxy capsule with legs. Don't get me started on the two-dimensional, clichéd, 80s characters. Of course the humans win, despite the Nitolan's overwhelming superior technology (or telekinesis, I couldn't really understand), because the dinosaurs don't understand humor… Wait, What?
The generous white borders around the text, the illustrations, and blank pages still barely make this story long enough to be a book. Rightfully, it belongs in an anthology. A really dated anthology that no one will ever read again and ends up gathering dust on a shelf in Goodwill. Seriously Longyear, did you really write this?

The only thing I can't track down a reference to is the part about what we use for fuel but this matches enough already that it is worth mentioning.


text:
Q: How to use ProcessStartInfo to run at lowest execution level I have an application that runs using as AsInvoker manifest, this uses ProcessStartInfo to run another application that is using a HighestAvailable manifest (in my case this runs as Admin and I get the UAC prompt) the first app then quits.
The second app then uses ProcessStartInfo to run the first app again, this time it runs as admin (no UAC prompt) I guess this is correct because it is AsInvoker and it is being invoke from an application that is running as admin, but I actually want it to run without Admin rights - or more correctly run it with the lowest possible execution level
I know you can use ProcessStartInfo.Verb = "runas" to elevate but can you descend?

A: No, you cannot "go back down" (There are several answers on this site and external tutorials that claim otherwise, but they all have problems in certain scenarios, this answer from a MS employee confirms that this is the case)
Your only real option is to use a AsInvoker bootstrapper/parent process that can launch unelevated processes. (And even this will fail if the bootstrapper is started elevated, but in those cases the user manually chose to run as admin)

A: @Anders is saying you can't level your own process back down, and that's right. But the OP is asking about launching a non-elevated process from an elevated one.
According to Aaron Margosis (also a Microsoft employee, not that I'm dissing Larry who is a hero of mine) that can be done. An MVP has written a managed wrapper for Aaron's native code.
Use with care.


text:
Q: How to update local database table with remote database table in mysql? I have mysql table created/modifying in localhost.And I need to update those in my remote database.
I have gone through lot of post regarding this scenario and I found out that I need to use mysql replication for overcome this situation.I went through some posts about mysql replication but I couldn't understand how would I do this.
Is this the method I need to use? If yes Please mention how to use this method?
Thank alot


text:
Q: Using fadeIn / fadeOut with Scroll Up For Menu I'm using the jQuery script "Scroll Up for Menu" by David Simpson, (Github Link) and I am trying to get it so that it uses fadeIn and fadeOut, so that when you scroll it fades out, and when you scroll back up the nav fade back in. I can't seem to figure out where to add it. Is it better to add an easing event to the nav div (in this case #top) or a fadeIn within the script?
JS
;(function ( $, window, document, undefined ) {

var pluginName = 'scrollUpMenu';
var defaults = {
        waitTime: 100,
        transitionTime: 550,
        menuCss: { 'position': 'fixed', 'top': '0'},
        showDelta: 0
};

var lastScrollTop = 0;
var $header;
var timer;
var pixelsFromTheTop;

// The actual plugin constructor
function Plugin ( element, options ) {
    this.element = element;
    this.settings = $.extend( {}, defaults, options );
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
}

Plugin.prototype = {
    init: function () {

        var self = this;
        $header = $(this.element);
        $header.css(self.settings.menuCss);
        pixelsFromTheTop = $header.height();

        // $header.next().css({ 'margin-top': pixelsFromTheTop });

        $(window).bind('scroll',function () {
            clearTimeout(timer);
            timer = setTimeout(function() {
                self.refresh(self.settings);
            }, self.settings.waitTime );
        });
    },
    refresh: function (settings) {
        // Stopped scrolling, do stuff...
        var scrollTop = $(window).scrollTop();
        var change = lastScrollTop - scrollTop;

        if (scrollTop > lastScrollTop && scrollTop > pixelsFromTheTop){ // ensure that the header doesnt disappear too early
            // downscroll
            $header.slideUp(settings.transitionTime);
        } else {
            // upscroll
            if ( change > settings.showDelta ) {
                $header.slideDown(settings.transitionTime);
            }
        }
        lastScrollTop = scrollTop;
    }
};

$.fn[ pluginName ] = function ( options ) {
    return this.each(function() {
            if ( !$.data( this, 'plugin_' + pluginName ) ) {
                    $.data( this, 'plugin_' + pluginName, new Plugin( this, options ) );
            }
    });
};
})( jQuery, window, document );

HTML
$(function() {
        $('#top').scrollUpMenu({'transitionTime': 100});
    });

JSFiddle
https://jsfiddle.net/09qxdx43/2/

A: Solved! fadeIn/fadeOut instead of slideUp
;(function ( $, window, document, undefined ) {

    var pluginName = "scrollUpMenu";
    var defaults = {
            waitTime: 20,
            transitionTime: 300,
            menuCss: { 'position': 'fixed', 'top': '0'}
    };

    var lastScrollTop = 0;
    var $header;
    var timer;
    var pixelsFromTheTop;

    // The actual plugin constructor
    function Plugin ( element, options ) {
        this.element = element;
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    Plugin.prototype = {
        init: function () {

            var self = this;
            $header = $(this.element);
            $header.css(self.settings.menuCss);
            pixelsFromTheTop = $header.height();

            $header.next().css({ 'margin-top': pixelsFromTheTop });

            $(window).bind('scroll',function () {
                clearTimeout(timer);
                timer = setTimeout(function() {
                    self.refresh(self.settings)
                }, self.settings.waitTime );
            });
        },
        refresh: function (settings) {
            // Stopped scrolling, do stuff...
            var scrollTop = $(window).scrollTop();

            if (scrollTop > lastScrollTop && scrollTop > pixelsFromTheTop){ // ensure that the header doesnt disappear too early
                // downscroll
                $header.fadeOut(settings.transitionTime);
            } else {
                // upscroll
                $header.fadeIn(settings.transitionTime);
            }
            lastScrollTop = scrollTop;
        }
    };

    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
                if ( !$.data( this, "plugin_" + pluginName ) ) {
                        $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
                }
        });
    };

})( jQuery, window, document );


text:
Q: How to convert actual hex address to be stored in a char array in C Good day.
I am trying to produce a SHA1 of the hex memory address of the following ksym_name:
static char ksym_name[KSYM_NAME_LEN] = "pid_max";

The above code is from : Watch a variable (memory address) change in Linux kernel, and print stack trace when it changes?, file name : testhrarr.c
I am trying to implement this proof of concept -that differing hashes signifies violation of ksym_name integrity. Implementation shall be in the form of a Linux Kernel Module via insmod module_name.ko, hence
C codes to work at the Linux Kernel level.
Example:
    0xf7ce31a8 - original memory location of kysm_name of pid_max
    If the memory location changes to e.g. 0xf7ce31c1 - signifies integrity violation, symbol pid_max isn't
    running at the original location and that an alert should be raised.
I am able to print the hex address of ksym_name via :
printk(KERN_INFO " Addresses of ksym_name of %s is : 0x%p" ,&ksym_name);

the output of which displays a hex address e.g. 0xf7ce31a8.
To illustrated what I wish to achieve, I provide an example from : How come an array's address is equal to its value in C?.
In reference to the code found in the above link, what I desire is for :
char hex_array[40] = for storage of the hex address of  %p output of &my_array' i.e. 0xf7ce31a8
as per :
char hex_array[40] = " 0xf7ce31a8 ";
then, next step is to channel the output of %p into a char array and produce a SHA1 hash of the hex address from the output of the %p of &my_array. See printf () below:
printf("&my_array = %p\n", &my_array);

To summarize: Put %p of &my_array into char hex_array[40] and produce a SHA1 hash from the hex address of %p for &my_array.
My questions are :

*

*How can I place the output from %p in the printf() above into char hex_array[40], and then produce a SHA1 hash from the hex address of the output from %p?

*How can I place the output from 0x%p in the printk() above into char my_array[100], and then produce a SHA1 hash from the hex address of the output from 0x%p?
I had perused these resources, but has yet to find the solution:
a. How to convert an address stored in char array to actual address? ,
b. How to convert a string which is holding a hexadecimal number into a hexadecimal format in c?
c. How to convert char[] array of hex characters to a byte array of values?
Thanks in advance for any kind assistance.


text:
Q: IF Exists MSSQL always errors I'm trying to drop a table if it exists.
I created a table, that worked fine.  I can drop the table with the DROP TABLE command.  What I can't do is any form of this:
DROP TABLE IF EXISTS customer;

In fact, I can't seem to get any form of IF EXISTS to work at all.  I went to the MS website and looked up how to do this, and their example won't even run:
CREATE TABLE T1 (Col1 int);
GO
DROP TABLE IF EXISTS T1;
GO
DROP TABLE IF EXISTS T1;

Any ideas?

A: According to the documentation, the IF EXISTS clause is only allowed in Azure SQL Database and SQL Server 2016 or later. So it seems you are using SQL Server 2014 or earlier.
You'll need to first check that the table exists in earlier versions. One method is checking for a OBJECT_ID that is NOT NULL:
IF OBJECT_ID(N'dbo.customer', 'U') IS NOT NULL DROP TABLE dbo.customer;


text:
Q: Триггеры SQL, AFTER INSERT Есть таблица timetable с 3мя полями (id, time, user)
CREATE TRIGGER addTime
AFTER INSERT ON timetable
FOR EACH ROW
BEGIN
  SET NEW.time = now();
END

Как должно работать: Вставляем запись со значениями для колонок id, user... time вставляется после действия INSERT.
Но это не работает т.к программа ругается на AFTER INSERT

A: Ключевые слова NEW и OLD можно применять только в BEFORE-триггере. Корректно триггер может выглядеть следующим образом:
DELIMITER //
CREATE TRIGGER addTime
BEFORE INSERT ON timetable
FOR EACH ROW BEGIN
  SET NEW.time = NOW();
END//

Вы можете вызывать в AFTER-триггере операторы UPDATE для обновления данных, но только не в отношении текущей таблицы - MySQL не даст изменять ее. Однако, если ваша задача изменить время только одного вставляемого столбца, нет необходимости задействовать триггер, достаточно задать условие ON UPDATE для столбца time при определении таблицы timetable
CREATE TABLE timetable (
  id int(11) NOT NULL,
  ...
  `time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Такой столбец можно не заполнять - ему автоматически будет назначаться текущее время.


text:
Q: Texel offsets in pixel shaders I am currently porting an app over from iOS to Windows Phone 8. It is an image processing app, and all calculations are done on the GPU using pixel shaders.
There is one detail that I just haven't been able to figure out, that is Texel Width/Height offsets. I have absolutely no idea what these values are, and I can't seem to find any information on them.
Are they common terms? Does anybody know what they represent? Does anyone know what sort of values should be in them?

A: Texel is a pixel of texture localized by a coordinate, the offset in a texture is where a texture begin mapped on a model or render target.
The most simple example of this:
http://lifeasa.files.wordpress.com/2011/02/super_mario_world_by_xinzax.png
The map of stage is a few textures, when Mario advances in level, the X coordinate offset increases, and the right part of texture became visible, at same time the left side becames hidden.
Check the textures, if have more than a 'part' in a single image, is this.
Another case is a single texture that is mapped in multiple objects, and each object have a offset to appears a 'segment' of previous object.


text:
Q: how to resolve StackOverFlowError? My Inner and outer class file here:-
package com.demo;

public class Outer {
int outer_x=100;

void test(){
    Inner inner =new Inner();
    inner.display();
}
public class Inner {
void display(){
    Outer ob=new Outer();
    ob.test();

    System.out.println("display: outer_x= "+outer_x);
}
}

}

Another  main class acess outer class member :-
package com.demo;

class InnerClassDemo{
    public static void main(String args[]){
        Outer outer=new Outer();
        outer.test();
    }
}

Exception:-
Exception in thread "main" java.lang.StackOverflowError
    at com.demo.Outer.<init>(Outer.java:3)
    at com.demo.Outer$Inner.display(Outer.java:12)
    at com.demo.Outer.test(Outer.java:8)

How can resolve this issue ,pls give me any idea?

A: Your test method creates an Inner and calls its display() method, which creates an Outer and calls its test method.  Nothing in your code stops this from continuing forever, until enough methods have been called to fill up the stack space and a StackOverflowError occurs.
Either don't have test call display, or don't have display call test.

A: I resolved this  issue  from @rgettman answer modified my Inner and outer class  here
package com.demo;
public class Outer {
int outer_x=100;

void test(){
    Inner inner =new Inner();
    inner.display();
}
public class Inner {
void display(){

    System.out.println("display: outer_x= "+outer_x);
}
}

}

A: Outer.test calls Inner.display which calls Outer.test which calls Inner.display which calls Outer.test which calls Inner.display which...
This goes on until your program runs out of stack space.

A: You get StackOverFlowError, because your call has a infinite method call which always exceeds program stack.
Your test method calls display and display method calls testunconditionaly.
It is the basic requirement to define a base case for recursive methods, so you should define a base case which will return and stop recursive method calls.
See also
Recursion


text: Q: How do I quit and copy the map? My sister and I made a really cool house. She wanted to download the world so she could have it too. Problem is, in 0.7.3 it just say "quit to menu" or whatever. How do you quit and copy the world? Where did the menu option go to copy a multiplayer world?


text:
Q: Angular Js: How to setup cookies? THE SITUATION:
I need to use cookies in my Angular App.
I have followed what should be the proper steps to properly setup the ngCookies module in my app, but somehow it isn't working.
This is the error message i am getting:
 Unknown provider: $$cookieReaderProvider <- $$cookieReader <- $cookies <- $cookies

THE STEPS:
These are the steps i have done:

*

*bower install angular-cookies

*Choose first option in bower:
 angular#1.3.13 which resolved to 1.3.13 and is required by angular-animate#1.3.13, angular-sanitize#1.3.13, ionic#1.0.0

*In index.html include:
<script src="lib/angular-cookies/angular-cookies.min.js"></script>

*Include the module ngCookies:
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngCookies'])

angular.module('starter.controllers', ['ngCookies'])

*Inject the service in the controller:
.controller('MainCtrl', function( $scope, $rootScope, $cookies )

VERSIONS -- EDIT
I thought the issue could be related with versions since these were the previous versions:
Angular version: 1.3.13
Angular-cookies version: 1.4.1

I have then reinstall angular to the latest version: #1.4.1 and reinstall angular-cookies but the issue persists with the same error message.
THE QUESTION:
How can i properly setup angular-cookies?
Why i am getting that error?

A: The angular packages should have the same version as the angular version you are using. So in this case you want to use 1.3.13 for angular cookies.
Angular does not use semantic versioning and is not necessarily backwards compatible.
Edit: I am not sure whether 1.4 has been released yet. If it has you could consider switching to the newer version.

A: I will give perfect solution for this same issue which is came for me at my fresher  time.
How can i properly setup angular-cookies?
You have already did that pretty much. That's enough for you.
Why i am getting that error?

May be you are configure invalid structure

Don't worry about the version,I think you have configured correct versions. So Just come out from version issue.
Solutions
Please check under verifications :-

*

*Have you put correct script path in your index.html screen?

*Please put the cookie.js before your main module code run.
like this below format
<script src="Scripts/angular.js"></script>// angular script
<script src="Scripts/angular-cookies.min.js"></script>// cookie script
<script src="app/home/home.js"></script>//my sub module js for home  screen
<script src="app/app.js"></script>// this is my main module js, here i configure the cookie

*

*Remove installed scripts in your index page. just past this and try one more time ⌚

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-cookies.js"></script>
I hope these both verification will don for you.

A: Latest angular-cookies seem to use AngularJS v1.4.1 but by default angular installs v1.3.x. Install latest version of angular by using
bower install angular#1.4.1

Don't forget to select 3) angular#1.4.1. Hope this solves your problem.


text:
Q: Android VideoView will not play MKV files My VideoViewer will not play any MKV files.  I've tested on .3gp video files and they work fine but MKV files won't work.  The video never shows up, no buffering or anything.  The screen will show up fine but as I said, the video player is either invisible or isn't there, I can't tell.  In the output, it will say something along the lines of:
connect to ........
new range: ........

and repeat them over and over depending on how big the MKV is.  It'll then either make the application stop responding or give the following output.
The output is:
09-25 07:54:40.767: INFO/ActivityManager(68): Starting: Intent { cmp=com.anime/.VideoPlayer } from pid 336
09-25 07:54:41.227: DEBUG/MediaPlayer(336): Couldn't open file on client side, trying server side
09-25 07:54:41.237: INFO/StagefrightPlayer(34): setDataSource('http://pbgl.net/Android/Naruto%20Shippuden/Hun_subtitle_sample1.mkv')
09-25 07:54:41.237: INFO/NuHTTPDataSource(34): connect to pbgl.net:80/Android/Naruto%20Shippuden/Hun_subtitle_sample1.mkv @0
09-25 07:54:41.767: INFO/ActivityManager(68): Displayed com.anime/.VideoPlayer: +968ms
09-25 07:54:43.017: INFO/NuCachedSource2(34): new range: offset= 821676
09-25 07:54:43.017: INFO/NuHTTPDataSource(34): connect to pbgl.net:80/Android/Naruto%20Shippuden/Hun_subtitle_sample1.mkv @821676
09-25 07:54:43.954: INFO/NuCachedSource2(34): new range: offset= 959025
09-25 07:54:43.954: INFO/NuHTTPDataSource(34): connect to pbgl.net:80/Android/Naruto%20Shippuden/Hun_subtitle_sample1.mkv @959025
09-25 07:54:45.564: INFO/NuCachedSource2(34): new range: offset= 1173410
09-25 07:54:45.564: INFO/NuHTTPDataSource(34): connect to pbgl.net:80/Android/Naruto%20Shippuden/Hun_subtitle_sample1.mkv @1173410
09-25 07:54:46.126: INFO/NuCachedSource2(34): ERROR_END_OF_STREAM
09-25 07:54:46.266: INFO/DEBUG(31): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
09-25 07:54:46.266: INFO/DEBUG(31): Build fingerprint: 'generic/sdk/generic:2.3.3/GRI34/101070:eng/test-keys'
09-25 07:54:46.266: INFO/DEBUG(31): pid: 34, tid: 345  >>> /system/bin/mediaserver <<<
09-25 07:54:46.266: INFO/DEBUG(31): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 00000024
09-25 07:54:46.266: INFO/DEBUG(31):  r0 00000000  r1 00000008  r2 00000003  r3 000151c0
09-25 07:54:46.266: INFO/DEBUG(31):  r4 0000fac0  r5 00014fb0  r6 00000000  r7 a30638bc
09-25 07:54:46.266: INFO/DEBUG(31):  r8 a2f60ab1  r9 0000f444  10 00100000  fp 00000001
09-25 07:54:46.266: INFO/DEBUG(31):  ip afc01100  sp 40606d58  lr a2ff0fd3  pc a2ff2b78  cpsr 40000030
09-25 07:54:46.426: INFO/DEBUG(31):          #00  pc 000f2b78  /system/lib/libstagefright.so
09-25 07:54:46.426: INFO/DEBUG(31):          #01  pc 000f0fce  /system/lib/libstagefright.so
09-25 07:54:46.426: INFO/DEBUG(31):          #02  pc 000f140e  /system/lib/libstagefright.so
09-25 07:54:46.436: INFO/DEBUG(31):          #03  pc 00054624  /system/lib/libstagefright.so
09-25 07:54:46.436: INFO/DEBUG(31):          #04  pc 00046290  /system/lib/libstagefright.so
09-25 07:54:46.436: INFO/DEBUG(31):          #05  pc 00047f08  /system/lib/libstagefright.so
09-25 07:54:46.436: INFO/DEBUG(31):          #06  pc 00044ea8  /system/lib/libstagefright.so
09-25 07:54:46.436: INFO/DEBUG(31):          #07  pc 00060a7e  /system/lib/libstagefright.so
09-25 07:54:46.436: INFO/DEBUG(31):          #08  pc 00060acc  /system/lib/libstagefright.so
09-25 07:54:46.436: INFO/DEBUG(31):          #09  pc 00011a7c  /system/lib/libc.so
09-25 07:54:46.446: INFO/DEBUG(31):          #10  pc 00011640  /system/lib/libc.so
09-25 07:54:46.446: INFO/DEBUG(31): code around pc:
09-25 07:54:46.446: INFO/DEBUG(31): a2ff2b58 685cd104 d101428c e0031c18 42933318
09-25 07:54:46.446: INFO/DEBUG(31): a2ff2b68 2000d1f4 46c0bd70 47706a00 47706b00
09-25 07:54:46.446: INFO/DEBUG(31): a2ff2b78 47706a40 600b6ac3 47706a80 47702001
09-25 07:54:46.446: INFO/DEBUG(31): a2ff2b88 47702000 47702000 47702000 47702000
09-25 07:54:46.446: INFO/DEBUG(31): a2ff2b98 6d591c03 47706d00 6dd91c03 47706d80
09-25 07:54:46.446: INFO/DEBUG(31): code around lr:
09-25 07:54:46.446: INFO/DEBUG(31): a2ff0fb0 fd4cf001 1c2b4f76 447f3308 90079306
09-25 07:54:46.446: INFO/DEBUG(31): a2ff0fc0 e0cb2300 98079904 fe26f001 f0011c06
09-25 07:54:46.446: INFO/DEBUG(31): a2ff0fd0 a909fdd3 1c309003 fdd0f001 201c9005
09-25 07:54:46.446: INFO/DEBUG(31): a2ff0fe0 ebb0f74d f7631c04 9408ff6f d0032c00
09-25 07:54:46.446: INFO/DEBUG(31): a2ff0ff0 a9081c20 eba0f74d f0011c30 2801fd97
09-25 07:54:46.446: INFO/DEBUG(31): stack:
09-25 07:54:46.446: INFO/DEBUG(31):     40606d18  000154c8  [heap]
09-25 07:54:46.446: INFO/DEBUG(31):     40606d1c  afc009cf  /system/lib/libstdc++.so
09-25 07:54:46.446: INFO/DEBUG(31):     40606d20  000154c8  [heap]
09-25 07:54:46.446: INFO/DEBUG(31):     40606d24  a8114ba7  /system/lib/libutils.so
09-25 07:54:46.446: INFO/DEBUG(31):     40606d28  0000fac0  [heap]
09-25 07:54:46.446: INFO/DEBUG(31):     40606d2c  000154c8  [heap]
09-25 07:54:46.446: INFO/DEBUG(31):     40606d30  a3060eb0  /system/lib/libstagefright.so
09-25 07:54:46.446: INFO/DEBUG(31):     40606d34  a8114ca9  /system/lib/libutils.so
09-25 07:54:46.446: INFO/DEBUG(31):     40606d38  00000002
09-25 07:54:46.446: INFO/DEBUG(31):     40606d3c  40606d78
09-25 07:54:46.446: INFO/DEBUG(31):     40606d40  00014fb0  [heap]
09-25 07:54:46.446: INFO/DEBUG(31):     40606d44  000154f0  [heap]
09-25 07:54:46.446: INFO/DEBUG(31):     40606d48  a30638bc  /system/lib/libstagefright.so
09-25 07:54:46.446: INFO/DEBUG(31):     40606d4c  a2f42a4d  /system/lib/libstagefright.so
09-25 07:54:46.446: INFO/DEBUG(31):     40606d50  df002777
09-25 07:54:46.446: INFO/DEBUG(31):     40606d54  e3a070ad
09-25 07:54:46.446: INFO/DEBUG(31): #01 40606d58  00000004
09-25 07:54:46.446: INFO/DEBUG(31):     40606d5c  00000000
09-25 07:54:46.446: INFO/DEBUG(31):     40606d60  00000004
09-25 07:54:46.446: INFO/DEBUG(31):     40606d64  000152b0  [heap]
09-25 07:54:46.446: INFO/DEBUG(31):     40606d68  00000002
09-25 07:54:46.446: INFO/DEBUG(31):     40606d6c  00000000
09-25 07:54:46.446: INFO/DEBUG(31):     40606d70  00014fb8  [heap]
09-25 07:54:46.446: INFO/DEBUG(31):     40606d74  00015198  [heap]
09-25 07:54:46.446: INFO/DEBUG(31):     40606d78  0000fac0  [heap]
09-25 07:54:46.446: INFO/DEBUG(31):     40606d7c  00000000
09-25 07:54:46.457: INFO/DEBUG(31):     40606d80  000152f0  [heap]
09-25 07:54:46.457: INFO/DEBUG(31):     40606d84  40606da0
09-25 07:54:46.457: INFO/DEBUG(31):     40606d88  00014fb0  [heap]
09-25 07:54:46.457: INFO/DEBUG(31):     40606d8c  00000000
09-25 07:54:46.457: INFO/DEBUG(31):     40606d90  40606e74
09-25 07:54:46.457: INFO/DEBUG(31):     40606d94  a2ff1413  /system/lib/libstagefright.so
09-25 07:54:47.646: WARN/MediaMetadataRetriever(260): MediaMetadataRetriever server died!
09-25 07:54:47.646: WARN/AudioSystem(124): AudioFlinger server died!
09-25 07:54:47.646: WARN/AudioSystem(124): AudioPolicyService server died!
09-25 07:54:47.646: WARN/AudioSystem(336): AudioFlinger server died!
09-25 07:54:47.646: WARN/IMediaDeathNotifier(336): media server died
09-25 07:54:47.646: ERROR/MediaPlayer(336): error (100, 0)
09-25 07:54:47.646: ERROR/MediaPlayer(336): Error (100,0)
09-25 07:54:47.646: DEBUG/VideoView(336): Error: 100,0
09-25 07:54:47.666: WARN/AudioSystem(68): AudioFlinger server died!
09-25 07:54:47.666: WARN/AudioSystem(68): AudioPolicyService server died!
09-25 07:54:47.666: INFO/ServiceManager(28): service 'media.audio_flinger' died
09-25 07:54:47.666: INFO/ServiceManager(28): service 'media.audio_policy' died
09-25 07:54:47.666: INFO/ServiceManager(28): service 'media.player' died
09-25 07:54:47.666: INFO/ServiceManager(28): service 'media.camera' died
09-25 07:54:47.666: INFO/BootReceiver(68): Copying /data/tombstones/tombstone_04 to DropBox (SYSTEM_TOMBSTONE)
09-25 07:54:49.166: ERROR/AudioService(68): Media server died.
09-25 07:54:49.166: INFO/ServiceManager(68): Waiting for service media.audio_flinger...
09-25 07:54:49.977: INFO/(348): ServiceManager: 0xad50
09-25 07:54:49.977: DEBUG/AudioHardwareInterface(348): setMode(NORMAL)
09-25 07:54:49.977: INFO/CameraService(348): CameraService started (pid=348)
09-25 07:54:49.977: INFO/AudioFlinger(348): AudioFlinger's thread 0xc658 ready to run
09-25 07:54:50.198: ERROR/AudioService(68): Media server started.
09-25 07:54:50.207: DEBUG/AudioHardwareInterface(348): setMode(NORMAL)

My code: (Not the main activity)
package com.anime;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;

import android.app.*;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.*;
import android.text.*;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

public class VideoPlayer extends Activity implements OnClickListener {
    /** Called when the activity is first created. */

    VideoView vv;
    Button close;
    public static String selectedVideo = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vidplayer);
        close = (Button) findViewById(R.id.button1);
        vv = (VideoView) findViewById(R.id.videoView1);
        playVideo(selectedVideo);
        View btn1 = findViewById(R.id.button1);
        btn1.setOnClickListener(this);
    }

    public void playVideo(String selected) {
        setContentView(R.layout.vidplayer);
        String url = RunApp.videoUrls.get(RunApp.currentShow).get(RunApp.videos.get(RunApp.currentShow).indexOf(selected)).toString(); // your URL here
        vv = (VideoView) findViewById(R.id.videoView1);
        try {
            vv.setVideoURI(Uri.parse(url));
            vv.setMediaController(new MediaController(this));
            vv.requestFocus();
            vv.start();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        System.out.println("ID: " + v.getId());
          switch (v.getId()){
          case R.id.button1:
              finish();
              break;
          }

    }
}

A: MKV is not a supported media container under Android.
The supported video file types (container formats) are: .3gp, .mp4 and .webm. There are also restrictions on supported video codecs.
Also, video codec format (h263, h264, mpeg-4, vp8) and container format (3gp, mp4, webm) are two different things. Which means that even if you have a .mp4 file it does not mean Android will be able to play it. It's content would also need to be encoded with a supported codec.

A: Since Android 4.0+, MKV videos are supported as described here. But as @Peter Knego said, video codec format and container format are two different things.
The Android Media API seems to be poorly documented (or at least it was at question time), as other guys have already pointed here. However, using tips from this post and this answer I was able to retrieve both information from two sample videos:
Uri videoUri = Uri.parse("android.resource://"
            + getPackageName() + "/" + R.raw.sample_video);
// Codec Format
extractor = new MediaExtractor();
extractor.setDataSource(this, videoUri, null);

for (int i = 0; i < extractor.getTrackCount(); i++) {
     MediaFormat format = extractor.getTrackFormat(i);
     String mime = format.getString(MediaFormat.KEY_MIME);
     if (mime.startsWith("video/")) {
         Log.d(TAG, "CODEC: " + mime);
         break;
     }
}
// Container Format
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(this, videoUri);

Log.d(TAG, "CONTAINER: "
      + mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE));

From two different MKV videos, I got the following outputs:
D/VideoActivity: CODEC: video/mp4v-es
D/VideoActivity: CONTAINER: video/x-matroska

D/VideoActivity: CODEC: video/avc
D/VideoActivity: CONTAINER: video/x-matroska

Although I think the best approach to handle unsupported files might be using try/catch blocks and/or VideoView.setOnErrorListening (doc & example), someone could use above methods to extract more details of media before playing it or at least to log what happened if something went wrong.


text:
Q: Why microservice accepts request event though it is down in eureka server registry? I have few microservices which is registered to Eureka Server(http://localhost:10100)
I am removing instance from eureka server using below REST API
Ref : https://github.com/Netflix/eureka/wiki/Eureka-REST-operations
1) Remove instance from eureka server (DELETE) (It remove instance but again re-register..)
http://localhost:10100/eureka/apps/MICRO-SERVICE-1/localhost:micro-service-1:10501
2) Update status of service to DOWN/OUT_OF_SERVICE
http://localhost:10100/eureka/apps/MICRO-SERVICE-1/localhost:micro-service-1:10501/status?value=DOWN
So even when micro-service-1 status is set to DOWN/OUT_OF_SERVICE I am able to send request to micro-service-1 (http://localhost:10501/MyService/hello)
Instead it should be unavailable but it accepting request an giving response.
So, Why microservice accepts request event though it's status is down in eureka server registry ?
Eureka Server application.yml file
server:
  port: 10100
  address: localhost
eureka:
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://localhost:10100/eureka/
  instance:
    prefer-ip-address: true
  server:
    enable-self-preservation: true
    wait-time-in-ms-when-sync-empty: 0

Eureka Client (micro-service-1) application.yml file
server:
  port: 10501
  address: localhost
eureka:
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://localhost:10100/eureka/
  instance:
    hostname: localhost
    prefer-ip-address: true

A: Your service has no built-in way of interpreting that you've taken it down in Eureka so calling your service by directly hitting its port will always work.
To make use of the directory's knowledge of server status and multiple instances of servers you need to call your service from an API such as ribbon that can construct a software load balancer from the directory. Alternatively make your calls through the Zuul API proxy which is essentially just a microservice built around ribbon internally.
In all these cases remember that the cloud microservices are eventually consistent. That is, changes you make may not be instantly available and will take time to propagate out to the running services.


text:
Q: Preload Image Without BuildContext Is there a way to load images in Flutter in a function without access to a BuildContext?
Flutter can preload images with precacheImage() which requires a BuildContext and is inconvenient to use.
I would like to load images in the initState() method of a StatefulWidget which precacheImage() does not support.
There is an open issue about preloading images that suggests loading images without a BuildContext is not currently supported.
https://github.com/flutter/flutter/issues/26127

A: I know two workarounds, first one is initstate "delayed" like so :
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var image;

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero).then((_) {
      //Your code here
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Second way is to use didChangeDependencies like so :
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var image;

  bool init = true;

  @override
  void didChangeDependencies() {
    if (init) {
      init = false;
      //your code here
    }
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

init boolean is to prevent didChangeDependecies from running same code so many time as it reruns alot
Hope this helps.


text:
Q: MVC Model Binding List of objects I am having trouble binding a model that contains list of objects. There are no problems when i try to pass the data from the controller to the view, but when i want to send the data back, i get a message that the method doesnt exists.
I am using an ajax call and as data i put $form.serialize() and can see the list with all the data in fiddler, but i am having no luck with the binding.
The Model is:
public class Single
{
   public int Id {get;set;}
   public string Name {get;set;}
   public List<SimpleDropdown> dddl {get;set;}
   public int SelectedEmp {get;set;}
}
public class MainModel
{
   public List<Single> main_model_list {get;set;}
}

In my controller the method for now is:
[HttpPost]
public string SaveModel(MainModel model)
{
   return "";
}

This method doesn't get called, but when i remove the parameter the calling works. So i'm sure that the binding doesn't work. I had a lot more complex model, but i simplified it as much as i can and still couldn't get it to work.
So my question is how can i test this to see what is the problem?
Edit:
I dont have the code at the moment, but that code is functional because i use it in other places in the project. It is something like this:
$("#form").submit(function( ) {
      $.ajax({
        url: "/Controller/SaveModel",
        type: "POST",
        data: $(this).serialize()
    });
});

The form looks something like this:
@using (Html.BeginForm("SaveModel", "Home", FormMethod.Post, new { id = "form" }))
{
    @for (var z = 0; z < ViewBag.groupes.Length; z++)
    {

@ViewBag.groupes[z]

    }
    @for (var i = 0; i < Model.main_model_list.Count; i++)
    {

@Html.LabelFor(x => x.main_model_list[i].Id)

@Html.LabelFor(x => x.main_model_list[i].Name)

@Html.DropDownListFor(x => main_model_list[i].SelectedEmp, new SelectList(main_model_list[i].dddl, "Id", "Value", main_model_list[i].SelectedEmp), new { @class = "preferences_dd_lists" })

    }
}

A: You can try to use
  @using(Ajax.BeginForm("SaveModel", "controller", formMethod.Post, new AjaxOptions{ }))
  {
      // your form
  }

Don't forget use the jquery.unobtrusive-ajax.js
and with Ajax.BeginForm you can remove that block of jQuery code to send your form, and it makes that your form be bind directly in the Action.

A: You can change your code.
data:{ model:$(this).serialize()}

Because you don't give the parameter name, the mvc model binding do not work.

A: Try the following:
$("#form").submit(function( ) {
      $.ajax({
        url: "/Controller/SaveModel",
        contentType: "application/json",
        type: "POST",
        data: $(this).serialize()
    });
});

A: while binding the binder is looking for value Id which was not provided by you.
so add this in the loop in your view page
@Html.HiddenFor(x => x.main_model_list[i].Id)

A: I'm sure that you wrote html wrongly, you want to post a collection to controller , but your data-form doesn't match with your model.
I think if you want to send a collection to your controller you have to modify your html-form
like that:
<input type="hidden" name="main_model_list[0].Id" value="1 />
<input type="hidden" name="main_model_list[0].Name" value="xyz" />
<select name="main_model_list[0].SelectedEmp">
.....
</select>
<input type="hidden" name="main_model_list[1].Id" value="1 />
<input type="hidden" name="main_model_list[1].Name" value="xyz" />
<select name="main_model_list[1].SelectedEmp>
.....
</select>

.................
And I think you should remove List dddl from single model.

A:
I have executed below code it is working fine. Declare Model(s) as below

 public class SimpleDropdown
{
    //
    // Summary:
    //     Gets or sets the text of the selected item.
    //
    // Returns:
    //     The text.
    public string Text { get; set; }
    //
    // Summary:
    //     Gets or sets the value of the selected item.
    //
    // Returns:
    //     The value.
    public string Value { get; set; }
}

public class SingleEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<SimpleDropdown> dddl { get; set; }
    public int SelectedEmp { get; set; }
}

public class MainModel
{
    public List<SingleEntity> main_model_list { get; set; }
}

And Controller action methods are as follows

public class BasicController : Controller
{
    public ActionResult GetModel()
    {
        MainModel mainModel = new MainModel();
        List<SimpleDropdown> dropdownlist = new List<SimpleDropdown>();
        List<SingleEntity> selist = new List<SingleEntity>();
        for (int j = 1; j < 10; j++)
        {
            dropdownlist.Add(new SimpleDropdown { Text = "Text" + j, Value = j.ToString() });

        }
        SingleEntity se;
        for (int i = 0; i < 10; i++)
        {
            se = new SingleEntity();
            se.Id = i;
            se.Name = "Name" + i;
            se.SelectedEmp = i;
            se.dddl = dropdownlist;
            mainModel.main_model_list = selist;
            mainModel.main_model_list.Add(se);

        }
        return View(mainModel);
    }

    [HttpPost]
    public ActionResult SaveModel(MainModel mainModelasdfafsf)
    {
        // do stuff here... please not only selectedEmp only will get reflected but not the property ddl since its again another list
        return View("GetModel");
    }
}

And Finally View should be something like this

@model MvcDemo.Models.MainModel
@using (Html.BeginForm("SaveModel", "Basic", FormMethod.Post, new { id = "formModel" }))

{
for (var i = 0; i < Model.main_model_list.Count; i++)
{

@Html.TextBoxFor(x => Model.main_model_list[i].Id)

@Html.TextBoxFor(x => Model.main_model_list[i].Name)

    @Html.TextBoxFor(x => Model.main_model_list[i].SelectedEmp)

    @Html.DropDownListFor(x => Model.main_model_list[i].SelectedEmp, new SelectList(Model.main_model_list[i].dddl, "Text", "Value", Model.main_model_list[i].SelectedEmp), new { @class = "preferences_dd_lists" })

}

<input type="button" value="Save" id="btnsave" name="btnsave" />

}
@section Scripts{

}

Above All make sure all the script files are loaded and also
  Check this Link where Model binding will not work for Lable and LableFor


text:
Q: Converting a .sql file into a .csv file using mysql giving empty output I have exported my mysql databse into a .sql file using the command
$ sudo mysqldump Company_Employee_Projects > dump.sql

I would like to simply convert this .sql file into a .csv file without being too fussy for now about the format of the csv file. There are numerous threads that provide simple solutions and one that I want to specifically carry out was this answer by user stan:
$ mysql Company_Employee_Projects --password=PASSWORD < dump.sql > out.csv

Entering that command gave me an Error 1045 (28000): Access denied for user 'USERNAME'@'localhost' (using passwod : NO) even though I entered the password that I set for sql. Note that PASSWORD and USERNAME are fields which are placeholders to the actual string I typed out. Nevertheless, when I sudo the same command, my PC (the server) takes a moment and outputs a .csv file. However, the file size indicates 0 Bytes and opening the file shows a blank document. The .sql file is extremely small so I doubt there is any lag or processing which delays the output .csv file. May anyone provide any hints as to what is the problem in trying to specifically implement stans solution?


text:
Q: Negators and modifiers with Syuzhet vs. SentimentR for sentiment analysis in R This question is twofold. An answer to either question would be an adequate solution. Very thankful if you could show suggestion as R-code.
1) The NRC lexicon in the Syuzhet packet yields the broadest range of emotions, but it doesn't seem to control for negators. After reading the documentation I'm still not sure how to overcome this. Perhaps by multiplying the positively and negatively coded words for each sentence, e.g. I(0) AM(0) NOT(-1) ANGRY(-1) = (-1*-1) = 1. However, I don't know how to write this in proper code.
2) After much research and testing, I found the jockers_rinker lexicon in SentimentR handles negators and modifies better(https://github.com/trinker/sentimentr#comparing-sentimentr-syuzhet-meanr-and-stanford). I could use SentimentR to "quality test" the results from the Suyzhet/NRC results by comparing the binary sentiment outputs from the two packages. If they deviate too much, the NRC isn't accurate enough for that particular body of text. However, I only know how to get individual scores and not the total scores for each sentiment (sum of positive and sum of negative)
You can see how my test results compare here on a concatenated string with emotions expressed with and without modifiers and negators.
   #Suyzhet:
   library("syuzhet")
   MySentiments = c("I am happy", "I am very happy", "I am not happy","It was
                   bad","It is never bad", "I love it", "I hate it")
   get_nrc_sentiment(MySentiment, cl = NULL, language = "english")
   #Result:
   anger anticipation disgust fear joy sadness surprise trust negative positive
    0            1       0    0   1       0        0     1        0        1
    0            1       0    0   1       0        0     1        0        1
    0            1       0    0   1       0        0     1        0        1
    1            0       1    1   0       1        0     0        1        0
    1            0       1    1   0       1        0     0        1        0
    0            0       0    0   1       0        0     0        0        1
    1            0       1    1   0       1        0     0        1        0

   #SentimentR:
    library("sentimentr")
    MySentiments = c("I am happy", "I am very happy", "I am not happy","It was
                   bad","It is never bad", "I love it", "I hate it")
                   sentiment(MySentiments, polarity_dt =
                   lexicon::hash_sentiment_jockers_rinker,
                   valence_shifters_dt = lexicon::hash_valence_shifters, hyphen
                   = "", amplifier.weight = 0.8, n.before = 5, n.after = 2,
                   question.weight = 1, adversative.weight = 0.25,
                   neutral.nonverb.like = FALSE, missing_value = NULL)
      #Results:
       element_id sentence_id word_count  sentiment
           1           1          3  0.4330127
           2           1          4  0.6750000
           3           1          4 -0.3750000
           4           1          3 -0.4330127
           5           1          4  0.3750000
           6           1          3  0.4330127
           7           1          3 -0.4330127

The first output seems not to recognize the importance of "very", "not" and "never".


text:
Q: Creating Browser Extensions ClickOnce is currently a very undersupported technology in my opinion. Currently only Internet Explorer can natively execute it, and FireFox if you use the FFClickOnce add-on.
My questions are multiple (after an edit):

*

*Does anybody know of supported methods to open ClickOnce applications from Opera/Safari/Chrome?

*If not, where would one begin in creating a usable, robust plug-in to achieve this functionality.

*Where would one start in making FireFox, Safari and Opera extensions?
I guess this boils down to explaining how a ClickOnce application is in fact launched, as well as if the browser frameworks can support it.
Also, with Chrome, I understand there is no add-on infrastructure, so if no answers exist for it, I fully understand.

A:
ClickOnce is currently a very
  undersupported technology in my
  opinion. Currently only Internet
  Explorer can natively execute it, and
  FireFox if you use the FFClickOnce
  add-on.

This used to be the case but isn't anymore: .NET Framework 3.5 SP1 does install its own add-on for this purpose (see .NET Framework Assistant for Firefox). Whether you consider this to be 'native' support or not is up to you, but of course it's still a regular add-on, though being officially released and supported by Microsoft helps a lot to improve Firefox user experience in regard to ClickOnce applications.
Obviously, in order to facilitate this new official Firefox add-on, the .NET Framework 3.5 SP1 must be bootstrapped by itself in case users don't happen to have it already, but this is another topic and doesn't differ much from installing any other baseline technology. It's worth nothing though that there has been improvements in this area too: By means of the .NET Framework Client Profile (see related FAQ too) many applications can reduce deployment size significantly (apparently ~28 MB instead of ~230 MB for the full framework).

Does anybody know of supported methods to open ClickOnce applications
  from Opera/Safari/Chrome?

Other then some questionable workarounds I'm not aware of any robust solutions.

If not, where would one begin in
  creating a usable, robust plug-in to
  achieve this functionality.

Your first stop regarding ClickOnce development (available for .NET 2.0 and higher) should be ClickOnce Deployment for Windows Forms Applications (the name is misleading, ClickOnce is not limited to Windows Forms). You'll find a wealth of information there on how to use the ClickOnce API, both implicitly via the build in deployment tools and especially programmatically from your own applications. The latter seems to be rarely used so far, unfortunately, though it is actually quite powerful. Consequently you should be able to include this functionality in almost any kind of 3rd party application, including browsers of course, as long as those do provide any kind of plug-in architecture.

Where would one start in making
  FireFox, Safari and Opera extensions?

I understand (and applaud) your approaching this issue from the single angle of end user ClickOnce experience, still I think given the broad scope of the topic it should best be asked in a separate question, if not in a separate question per browser even. That said, there are quite some related questions to be found on Stack Overflow already, see e.g. for Firefox (most obvious ;) questions/tagged/firefox+add-on and questions/tagged/firefox+extension.

A: The only way to execute a clickonce app from an unsupported browser is to download and then open the .application file. The .NET framework 2.0 or higher must be already installed or you'll just get a files of XML gibberish.

A: *

*http://social.msdn.microsoft.com/forums/en-US/winformssetup/thread/5f6fe523-1162-442a-b305-fd1bc4c17dcf/
Components, developed in Visual Studio 2008 should work ok in IE, Firefox, Safari, and Opera (there was a problem in VS2005).
Developping a cross-browser extension is a super-mega-task I would never take ;)


text:
Q: Can't stop automatic Thunderbird updates (TB & LIghtning incompatible) It seems Thunderbird (currently 38.6.0 on Windows 8.1 64bit on an Acer laptop) is still automagically updating itself, although I've already set the update policy from "ask" to "never".
Not recommended, I know, but I need Lightning as well, and there are always a few days after a Thunderbird update during which it happily declares Lightning could not be used with this new version of Thunderbird.
So my idea was to go from "automatic" updates to "ask" and do this manually only if Lightning was available for the new Thunderbird release. But not even "never" updating removes this issue.
Question 1 - How can I stop Thunderbird from updating? The setting seems to be ignored.
Question 2 - Right now, there is a Lightning 4.0.6 version listed to be compatible with TB 38.6.0, but it has no download link at
[https://developer.mozilla.org/en-US/docs/Mozilla/Calendar/Calendar_Versions]. How am I supposed to download it?
Thanks for sheding some light on this!

A: I could not send emails with TB 45.0.0 so I went back to TB 38.6.0 Now to answer your question No. 1:

*

*When you install your favourite version, uncheck the Maintenance/update box in Advanced Install.

*After the install, go to the (X86) Program Files where you will find TB. Open its Folder and delete maintenanceservice.exe and maintenanceservice_installer.exe

*Do NOT open the 'About Thunderbird' as it puts TB into an Update mode!

A: Sorry for the confusion - my fault: I am using an external drive with the TB data on different computers which had different TB versions installed. Destined to cause all sorts of problems... Getting all computers to TB 45.0 hopefully will solve it.


text:
Q: Magento 2 getMediaGalleryImages() return null I am writing an import product job on Magento 2. I want to delete all product images if I need to update the product. I try to use $product->getMediaGalleryImages() to get all the images from the product but it returns null after running. I ensure that the product has an image. Follows is the code I tried.
$product = $objectManager->create('\Magento\Catalog\Model\Product');
$product = $product->getCollection()->addFieldToSelect("*")->addAttributeToFilter('sku', 'sku-01')->getFirstItem();
$images = $product->getMediaGalleryImages(); // it return null

And follows is the code to upload product image.
$product->setMediaGallery(array('images' => array(), 'values' => array()))
                            ->addImageToMediaGallery($image_directory, array('image', 'thumbnail', 'small_image'), false, false);

A: You can get the product media gallery images as given below.
Method 1: Use dependency. (Recommended)
Create a helper

app/code/Vendor/Module/Helper/Data.php

<?php

namespace Vendor\Module\Helper;

use Magento\Catalog\Model\Product\Gallery\ReadHandler as GalleryReadHandler;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $galleryReadHandler;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        GalleryReadHandler $galleryReadHandler
    )
    {
        $this->galleryReadHandler = $galleryReadHandler;
        parent::__construct($context);
    }

    /** Add image gallery to $product */
    public function addGallery($product) {
        $this->galleryReadHandler->execute($product);
    }

}

Now add code to your phtml file as below.
$_helperGallery = $this->helper('Vendor\Module\Helper\Data');
$_helperGallery->addGallery($product);
$images = $product->getMediaGalleryImages();
foreach ($images as $image) {
    print_r($image->getData());
}

Method 2: Use objectManager directly in your phtml file. (Not Recommended)
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->get("Magento\Catalog\Model\Product\Gallery\ReadHandler")->execute($product);
$images = $product->getMediaGalleryImages();
foreach ($images as $image) {
    print_r($image->getData());
}

A: /* Add media gallery data to loaded items
 * @since 101.0.1
 * addMediaGalleryData()
 */
$product = $objectManager->create('\Magento\Catalog\Model\Product');
$product = $product->getCollection()
->addFieldToSelect("*")
->addAttributeToFilter('sku', 'sku-01')
->addMediaGalleryData()
->getFirstItem();
$images = $product->getMediaGalleryImages();

Try to add addMediaGalleryData() to your collection. Without it, getMediaGalleryImages() will always return null

A: Your issue may be with this code
$product = $product->getCollection()->addFieldToSelect("*")->addAttributeToFilter('sku', 'sku-01')->getFirstItem();

Try below code instead
$product = $objectManager->create('\Magento\Catalog\Model\Product');
$product = $product->loadByAttribute('sku', 'sku-01');
$images = $product->getMediaGalleryImages();

Note:-  you should not use object manager directly instead use ProductRepository check this answer for proper Magento 2 way to load product


text:
Q: Python: Reading multiple CSV files, and assigning each to a different variable I would like to read all the CSV files in my path and assign them each to a different variable name within my python code.
For example,
dshfd9438dks.csv
ansjewi38Ekd.csv

Would turn into:
df1 and df2

The code I have now is:
for f in glob.iglob('*.csv'):
df = pd.read_csv(f, low_memory=False)

How would I manipulate it to add a number to the df var?

A: Use a dictionary for a variable number of variables
It's poor practice to name linked variables explicitly. In this case, you can use a dictionary with enumerate:
dfs = {}
for idx, f in enumerate(glob.iglob('*.csv'), 1):
    dfs[idx] = pd.read_csv(f, low_memory=False)

If you wish, you can convert this into a dictionary comprehension:
files = enumerate(glob.iglob('*.csv'), 1)
dfs = {idx: pd.read_csv(f, low_memory=False) for idx, f in files}

Then access your dataframes via dfs[1], dfs[2], etc.

A: Why not put them in a dictionary?
dfs = dict(("df{}".format(i), pd.read_csv(f)) for i,f in enumerate(glob.iglob('*.csv')))


text:
Q: Can we import MyBatis XML file into another MyBatis XML file? I am using Spring and MyBatis. I have tried to import another MyBatis file(which is auto-generated) by refering Can we import XML file into another XML file?.
1) MyTest.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" [
        <!ENTITY BaseTest.xml SYSTEM "BaseTest.xml" >
        ]>
<mapper namespace="com.test.abc">
    &BaseTest.xml;

    <select id="CUSTOMIZED_SELECT">
    ...
    </select>
    <insert id="CUSTOMIZED_INSERT">
       ...
    </insert>
</mapper>

2) BaseTest.xml. Actually it's just a XML snippet; it has no xml header nor outer mapper element:
<sql id="GENERAL_WHERE">
    ...
</sql>
<select id="GENERAL_SELECT">
    ...
</select>
<insert id="GENERAL_INSERT">
    ...
</insert>

These two files are located at the same directory. But Spring always complains that it can't find the BaseTest.xml.
Is there any special that I need to adjust ?
BTW, the reason behind BaseTest.xml and MyTest.xml is that BaseTest.xml is auto-generated and MyTest.xml is manual-written.
Thanks!

A: No you cannot import Mybatis XML mapper into another.
If you could: what would happen to <mapper> namespace attribute?
<sql> fragments, <resultMap> defined in a mapper may be referenced from another mapper. just make sure to use full qualified name: namespace.id
e.g: <include refid="com.test.abc.TestMapper.sqlFragementId" />
Ans don't forget that if included fragment also includes a fragment, references will be made from the root mapper, then using full qualified name may be required even when referencing fragment in the same mapper. Anyway, keeping with simple id reference allows overriding (a kind of inheritance). But this is to handle with care.


text:
Q: universal content manager I found one limitation in Oracle UCM. Well it might not be limitation but I am not able to figure it out yet:
I didn't find mapping between metadata and content type. What if I wish to associate different set of metadata with different content type which is likely the case?
Thanks.

A: Use Content profiles for this. You should find these described in the documentation. These are created via the Configuration Manager applet. You need to create a trigger field (for doctype, for example) and then your profiles. You then create rules which you associate with each profile that will specify which metadata applies for the profile in question.


text:
Q: Efficient way to remove all entries in a dictionary lower than a specified value I need to remove all entries in a dictionary accordingly to a specified lower bound.
My current solution is this:
    List<string> keys = new List<string>();

    foreach (KeyValuePair<string, int> kvp in dic)
    {
        if (kvp.Value < lowerBound)
            keys.Add(kvp.Key);
    }

    foreach (string key in keys)
        dic.Remove(key);

However this is rather expensive, especially since the size of the dictionary is rather large.
I've seen a LINQ solution like:
foreach(var kvp in dic.Where(kvp.Value <= lowerBound).ToDictionary())
{
    dic.Remove(kvp.Key);
}

which I assume to be better since it's just 1 foreach, but I'm getting:

The name 'kvp' does not exist in the current context
The type arguments for method 'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I admit I don't know anything about LINQ so any ideas how to make this 2nd solution work, or a better one?

A: Don't remove them explicitly, reassign the dictionary using only the values that are above that lower bound instead:
dic = dic.Where(kvp => kvp.Value > lowerBound).ToDictionary();

That way you can completely eliminate that foreach loop you've got in there.
Also, the reason you're getting that error is that you're not using the proper lambda syntax.  In fact, you're not using a lambda at all.  The expression:
kvp => kvp.Value > lowerBound

Is shorthand for a method that takes one parameter, called "kvp", and returns the evaluation of the expression:
kvp.Value > lowerBound

The => is called the "lambda operator", and it separates the parameter intake from the returned output.  Every LINQ method that takes a Func is asking for a delegate of some sort, typically expressed as a lambda expression for brevity.  When you give it the lambda expression, the compiler will stop complaining.
Read this for more information on lambda expressions.

A: Try this.
foreach(var kvp in dic.Where(x => x.Value <= lowerBound).ToDictionary())
{
    dic.Remove(kvp.Key);
}

A: dic.Where(kvp.Value <= lowerBound)

replace with
dic.Where(kvp1 => kvp1.Value <= lowerBound)


text:
Q: Compile source files to a different directory and then accessing them in another directory, how? JAVA My directory structure:
C:\jaBHa
here I want to create two packages - sources and classes.
so it looks like
C:\jaBHa\classes
C:\jaBHa\sources
the sources package must contain all the source files i.e., the .java files.
And then I want them to compile to the classes package which would contain all the .class files.
here are the codes for the three classes...
// MyDate.java
package classes;

public interface MyDate {
    void showDate();
}

// DateImpl.java
package classes;

import java.util.*;
import classes.*;
public class DateImpl implements MyDate {
    public void showDate() {
        Date d = new Date();
        System.out.println(d);
    }
}

// Test.java
package classes;

import classes.*;
public class Test {
    public static void main(String[] args) {
        DateImpl d = new DateImpl();
        d.showDate();
    }
}

Now, I know that there's some issue with my class DateImpl java file, but my objective is...
that I want to compile these java files using the commands
C:\jaBHa> javac -d C:\jaBHa\sources MyDate.java
C:\jaBHa> javac -d C:\jaBHa\sources DateImpl.java
C:\jaBHa> javac -d C:\jaBHa\sources Test.java
with this the MyDate.java, DateImpl.java and Test.java files will compile to classes package...
and then i run it by typing
C:\jaBHa> java classes.Test
as the class file of Test.java is in C:\jaBHa\sources\classes package...
but here's the problem, it compiles to C:\jaBHa\sources\ here it will create a package classes but I want it to compile to C:\jaBHa\classes not C:\jaBHa\sources\classes...
so I have to keep my all java files in C:\jaBHa\ so that it can compile to classes package.

A: The -d option specifies the output directory for class files.
Try this.
C:\jaBHa>javac -d . sources\*.java

C:\jaBHa>java classes.Test
Mon Oct 24 19:19:05 JST 2022

C:\jaBHa>


text:
Q: Passing reference as lvalue/rvalue depending on function signature Let's say I have some data :
struct Bar {};

I need to wrap a function and feed it with this data.
template<typename F>
void foo(F f) {
    Bar bar;
    f(bar);
}

As you can see in this trivial example:

*

*bar is not a temporary

*I don't need it after calling f
I want to support multiple function signatures, such as :
foo([](Bar){}); // (1)
foo([](Bar&){}); // (2)
foo([](Bar&&){}); // (3)

However gcc complains :
f(bar); // (3) : cannot bind 'Bar' lvalue to 'Bar&&'
f(std::move(bar)); // (2) : no match for call to ...

How would you do to get both ?

A: struct BarIsh{
  Bar&b;
  operator Bar&&()&&{return std::move(b);}
  operator Bar&()&&{return b;}
};

then f(BarIsh{bar}).
The downside is that if f takes a deduced parameter, it gets a BarIsh not a Bar.
Assuming you have a SFINAE friendly result_of...
template<class...>struct voider{using type=void;};
template<class...Ts>using void_t=typename voider<Ts...>::type;

template<class...>struct types{using type=types;};

namespace details{
  template<template<class...>class Z,class types,class=void>
  struct can_apply:std::false_type{};
  template<template<class...>class Z,class...Ts>
  struct can_apply<Z,types<Ts...>,void_t<Z<Ts...>>>:
    std::true_type
  {};
};
template<template<class...>class Z,class...Ts>
using can_apply=details::can_apply<Z,types<Ts...>>;

template<class Sig>
using result_of_t=typename std::result_of<Sig>::type;

template<class Sig>
using can_invoke=can_apply<result_of_t,Sig>;

and now we can test.
template<typename F>
void foo(F&& f,std::true_type)
{
  Bar bar;
  std::forward<F>(f)(std::move(bar));
}

template<typename F>
void foo(F&& f,std::false_type)
{
  Bar bar;
  std::forward<F>(f)(bar);
}

template<typename F>
void foo(F f)
{
  foo(std::forward<F>(f),can_apply<F(Bar&&)>{});
}

and done.  (there may be typos above, code written on phone)


text:
Q: Pulse sensor coding for Netduino Plus 2 gone wrong I'm currently doing a project on Netduino Plus 2 using .net micro framework which requires me to code for a pulse sensor. I have tried finding codes for pulse sensor but to no avail. I tried using AnalogInput codes for pulse sensor but the output values seemed wrong (there was a constant high value despite no heartbeat placed near the sensor). Please advise!
Here are my current codes for the heartbeat sensor:
  using System;
  using System.Net;
  using System.Net.Sockets;
  using System.Threading;
  using Microsoft.SPOT;
  using Microsoft.SPOT.Hardware;
  using SecretLabs.NETMF.Hardware;
  using SecretLabs.NETMF.Hardware.Netduino;

  namespace heartrate
   {
   public class Program
  {
  public static void Main()
   {

    SecretLabs.NETMF.Hardware.AnalogInput rate =
    new SecretLabs.NETMF.Hardware.AnalogInput(Pins.GPIO_PIN_A0);
    int sensorvalue = 0;
    while (true)
    {
        sensorvalue = rate.Read();
        Debug.Print("" + sensorvalue);
        Thread.Sleep(1000);
    }
   }
 }
 }

Here are the specs of the sensor, how it looks like and how it is connected.
http://www.elecrow.com/wiki/index.php?title=Pulse_Sensor
(This tutorial is for arduino, but I think the wiring is similar to that of Netduino)

A: Hard to tell without specs on your pulse device and how it is attached. For Analog input & output in my latest project (https://github.com/osstekz/cncBuddy) I use classes InputPort & OutputPort (Microsoft.SPOT.Hardware)
ex:
public NESControllerAdapter(Cpu.Pin pinClk, Cpu.Pin pinLatch, Cpu.Pin pinData1/*, Cpu.Pin pinData2 = Cpu.Pin.GPIO_NONE*/) {
        // Binds to all pins
        this._outpClk = new OutputPort(pinClk, false);
        this._outpLatch = new OutputPort(pinLatch, false);
        this._inpData1 = new InputPort(pinData1, false, Port.ResistorMode.Disabled);
        //if (pinData2 != Cpu.Pin.GPIO_NONE) this._inpData2 = new InputPort(pinData2, false, Port.ResistorMode.Disabled);
        }

...then like your rate.Read(); loop
public int ButtonPressed() {
    // Locks all parms
    this._PinTick(this._outpLatch);

    // Reads plug state value
    for (int i = 0; i < CncBuddyShared.iTOTALNESCONTROLLERBUTTONS; ++i) {
        // Read the value, if true return this index as the first pressed button
        if (this._inpData1.Read() == false) return i;

        // Selects the next value
        this._PinTick(this._outpClk);
        }
    return NESCONTROLLER_PRESSEDBUTTOM_NONE;
    }


text:
Q: Regarding GPT-3 Android Studio Project. (JAVA) I am not able to generate output in my resultTextview. App get crashed when I click generate button.
Below is my MainActivity.java or you can get it from github
    search = findViewById(R.id.search);
    resultTextView = findViewById(R.id.resultTextView);
    generateButton = findViewById(R.id.generateButton);

    generateButton.setOnClickListener(this::onClick);
}

private void onClick(View view) {
    String searchText = search.getText().toString();
    String token = System.getenv("OPENAI_TOKEN");
    OpenAiService service = new OpenAiService(token);
    Engine davinci = service.getEngine("davinci");
    ArrayList<CompletionChoice> storyArray = new ArrayList<CompletionChoice>();
    CompletionRequest completionRequest = CompletionRequest.builder()
            .prompt(searchText)
            .temperature(0.7)
            .maxTokens(96)
            .topP(1.0)
            .frequencyPenalty(0.0)
            .presencePenalty(0.3)
            .echo(true)     // echoes back the prompt in addition to tokens
            .build();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        service.createCompletion("davinci", completionRequest).getChoices().forEach(line -> {
            storyArray.add(line);
        });
    }
    String result = "";
    for (CompletionChoice line : storyArray) {
        result += line.getText() + "\n";
    }

    resultTextView.setText(storyArray.get(0).getText());

 }

}


text:
Q: php json obj parsing in java in the php file I am creating a 2d dynamic array and while returning it am encoding using json_encode
 $ans=array('x'=>array(),'y'=>array(),'z'=>array());
    foreach ($result as &$y)
    { if(strpos($y,"x")){$ans['z'][]=substr(strstr($y,':'),12);}
      else if(strpos($y,"y")){$ans['y'][]=substr(strstr($y,':'),2);}
      else if(strpos($y,"z")){$ans['z'][]=substr(strstr($y,':'),2);}
     }//$y is a very big string
     return json_encode($ans);

the output in browser shows as {...} I.E. jsonobject
but when in java I try to convert httpentity to string(using entityutils.tostring) and then make
jsonobject ja=new jsonobject(entityutils.tostring(entity));

shows following
error : org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
why is it showing this?
edited :
List<NameValuePair> namevaluepair=new ArrayList<NameValuePair>(1);
         namevaluepair.add(new BasicNameValuePair("request",""+x));
         HttpClient httpclient = new DefaultHttpClient();
         HttpPost httppost = new HttpPost("http://localhost/webc.php");
         httppost.setEntity(new UrlEncodedFormEntity(namevaluepair));
         HttpResponse response = httpclient.execute(httppost);
         HttpEntity entity = response.getEntity();
if(entity!=null)
{String line=EntityUtils.toString(entity);
JSONObject ja=new JSONObject(line);//showing error here
}


text:
Q: Big files loading fail in some cases I'm writing a little HTML5/Javascript game for the LudumDare contest and some players reported me an issue concerning asset loading on browsers like Firefox or Safari.
(especially big assets like musics (~600kb each)).
The game is hosted here:
dl.dropbox.com/u/4936312/LD24/index.htm
(So that you can test if you see a black screen OR the game starting, meaning respectively asset loading fail and success).
The loader script is over here:
https://github.com/cboissie/LD24-Evolution/blob/master/script/ResourceManager.js
(ResourceManager calls ResourceLoader which calls File)
If you get a look to a web developer console, you can see that when it fails, at least one of the response to a GET request failed. (And the GET request was obviously for a file with a 'big' size).
Does anyone have an idea how to solve this?
EDIT: after checking the web console on Firefox, I can see that some resources have the HTTP1.0 GET 206 status (instead of 200).
EDIT2: This "resources" concerned by the 206 messages are only .wav or .ogg. This means it's related to the HTML5  tag and/or maybe the library I'm using. I will try later to switch to a different library and see if it's working after that. (EDIT3 later this week)

A: Don't host on dropbox. Dropbox is for sharing files only!
Dropbox is a free service that lets you bring your photos, docs, and videos anywhere and share them easily.
Example
If you host your database in dropbox you will get corrupted tables etc. https://forums.dropbox.com/topic.php?id=32069


text:
Q: How to know the last view index of MultiView on ActiveViewChanged event? Is there a way to know what was the last view index on the event ActiveViewChanged?
protected void mltv_ActiveViewChanged(object sender, EventArgs e)
    {
       //Here i nedd to know what it was, because here it is already changed
    }

A: Check the property mltv.ActiveViewIndex.  Got here.

A: Just used the Load Event for user control and reference the ActiveViewIndex.  It should have the ActiveViewIndex before it has been changed.  For the example below I just used the context items as backing, but if you have a class level variable that could be used instead:
protected void mltv_Load(object sender, EventArgs e)
{
   //Add your property backing or class variable here
   int pos = mltv.ActiveViewIndex;
   if (pos == -1)
       return;
   Context.Items["mltv_ActiveViewIndexOnLoad"] = pos;

}
protected void mltv_ActiveViewChanged(object sender, EventArgs e)
{
   //Retrieve property, private variable, here:
   var lastViewIndex = -1;
   if (Context.Items["mltv_ActiveViewIndexOnLoad"] != null)
   {
       lastViewIndex = (int)(Context.Items["mltv_ActiveViewIndexOnLoad"]);
   }

}


text:
Q: TypeError: must be real number, not str : Django I'm getting this Error: TypeError: must be real number, not str. when i printing the request data lat2, lon2 then it's print float types of number. when i running below code then it's throwing me error that, must be realnumber not str type.
It would be great if anybody could help me out to solve this issues. thank you so much in advance.
def distance(lon1, lat1, lon2, lat2):

    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    # Haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2

    c = 2 * asin(sqrt(a))
    r = 6371 # Radius of earth in kilometers
    return(c * r) # calculate the result

class GarageShopDetailAPIView(APIView):
    def get(self,request,*args,**kwargs):
        lat2 = self.request.GET.get('lat2', None)
        lon2 = self.request.GET.get('lon2', None)

        queryset = ShopOwnerShopDetails.objects.filter(id=query_id)
        serializer = ShopOwnerShopDetailsSerializer(queryset, many=True, context={'request':request})
        data = serializer.data
        km_difference = []
        for record in data:
            lon1 = record['lon']
            lat1 = record['lat']
            km_differ = distance(lon1, lat1, lon2 , lat2)
            km_difference.append({"km_difference":km_differ})


text:
Q: How can I make the battery icon appear in my gnome-3 panel only when charging or discharging? I am using ubuntu 11.10. There was an option for the same in 11.04.
I found a suggestion listed here. Unfortunately, it does'nt work.

$ GSETTINGS_BACKEND=dconf gsettings set org.gnome.power-manager
  icon-policy charge No such key 'icon-policy'

A: Manually creating icon-policy key & setting it to "charge" might help, however I did it from terminal & it worked fine for me(both in gnome-shell & fallback mode).
Run update manager & make sure you have latest updates.Disable any extension(if you have any) related to power or battery.Then open terminal & run following command:
gsettings get org.gnome.power-manager icon-policy

it should return something like these:
:~$ gsettings range org.gnome.power-manager icon-policy
enum
'present'
'charge'
'low'
'critical'
'never'

Now set the icon policy to charge:
gsettings set org.gnome.power-manager icon-policy charge

Restart gnome-shell.
Done!
Does this help?

Update: This above method only works with gnome 3.1.3 or less.
Unfortunately in latest gnome  this isn't possible any more. "org.gnome.power-manager icon-policy" has been removed in GNOME 3.2, as gnome-power-manager code has been moved to gnome-settings-daemon, where there is no key to configure this. See this bug report(bug 655298).
If you want to hide battery icon in gnome shell, see this post:
how to remove battery indicator in gnome-shell?
On Unity, support for hiding of icon and settings has been added with indicator-power - 1.90-0ubuntu1 (bug 811769).


text:
Q: How to disable mod_security and mod_security2 in .htaccess I've created a Wordpress plugin which became popular but I'm getting lots of complaints that it's not working. After logging in to many user's WP websites(after asking for admin password) I noticed that the last problem I can't easily solve is mod_security and mod_security2 blocking some AJAX requests or .htaccess which is causing 500 error on some configurations.
So first of all why is this piece of code causing some servers to return 500 error
<IfModule mod_security2.c>
  SecRuleRemoveById 300015
  SecRuleRemoveById 300016
  SecRuleRemoveById 300017
  SecRuleRemoveById 950907
  SecRuleRemoveById 950005
  SecRuleRemoveById 950006
  SecRuleRemoveById 960008
  SecRuleRemoveById 960011
  SecRuleRemoveById 960904
  SecRuleRemoveById phpids-17
  SecRuleRemoveById phpids-20
  SecRuleRemoveById phpids-21
  SecRuleRemoveById phpids-30
  SecRuleRemoveById phpids-61

on other servers removing rules by id this way is causing 500 error:
<IfModule mod_security.c>
  SecRuleRemoveById 300015
  ...
  SecRuleRemoveById phpids-61
</IfModule>

so for now the only working thing which is not causing any server to crash is
<IfModule mod_security.c>
  SecFilterEngine Off
  SecFilterScanPOST Off
</IfModule>

but it's not enough for servers with mod_security2 !
How to write a cross-server .htaccess file, and what IF conditions should I add to disable mod_security and mod_security2 anywhere where it applies and not cause 500 errors on other configurations?
Edit:
Not only in Apache. Anywhere where .htaccess is used.

A: Ryan C. Barnett, ModSecurity Community Manager claimed:

Support for .htaccess files was discontinued in 2.x as it raised too
  many security issues.

source: http://article.gmane.org/gmane.comp.apache.mod-security.user/3065
The only possible configuration that enable on htaccess are the following (since 2.7.3) but you need to ./configure --enable-htaccess-config:

*

*SecAction

*SecRule

*SecRuleRemoveByMsg

*SecRuleRemoveByTag

*SecRuleRemoveById

*SecRuleUpdateActionById

*SecRuleUpdateTargetById

*SecRuleUpdateTargetByTag

*SecRuleUpdateTargetByMsg

https://github.com/SpiderLabs/ModSecurity/blob/876d4f5f9558595c00f40af25ea6216386f15cd7/CHANGES#L69

A: Displaying a message telling to contact server administrator will be the last thing to do. First of all I'll try one of this solutions for automatic config creation:
Create 2-3 sandboxed .htaccess configs in subfolders

*

*During plugin activation test configs one by one with simulated remote AJAX test

*Start from the best general settings config subfolder

*Check for AJAX proxy script calls and image, style etc. files access in this folder

*After finding successful(unblocking and not crashing) config, save selected .htaccess file to the folder containing AJAX proxy PHP file

*If none of the configs (or built-in wordpress AJAX script - not very reliable) is functional display an error telling to contact server admin to allow htaccess for given folder

OR

*

*Check loaded modules with PHP

*add SecRuleRemoveById id only if mod_security2 is present to prevent
basic mod_security crashing