text:
Q: After upgrading to Xampp 1.8.1, can't view my sites I was using xampp 1.7.0 but just decided to upgrade to xampp 1.8.1. I uninstalled the 1.7 but didn't uninstall the htdocs and mysql server.
I now installed 1.8 and create passwords for the xampp directory and mysql through the xampp security page.
Unfortunately, I can't view my sites again, they all give errors, this is a sample error:
Strict Standards: Non-static method JLoader::import() should not be called statically in C:\xampp\htdocs\3nity\libraries\joomla\import.php on line 29
Strict Standards: Non-static method JLoader::register() should not be called statically in C:\xampp\htdocs\3nity\libraries\loader.php on line 71
Strict Standards: Non-static method JLoader::import() should not be called statically in C:\xampp\htdocs\3nity\libraries\joomla\import.php on line 32
Strict Standards: Non-static method JLoader::register() should not be called statically in C:\xampp\htdocs\3nity\libraries\loader.php on line 71
Strict Standards: Non-static method JLoader::register() should not be called statically in C:\xampp\htdocs\3nity\libraries\loader.php on line 138
Strict Standards: Non-static method JRequest::clean() should not be called statically in C:\xampp\htdocs\3nity\libraries\joomla\import.php on line 33
Strict Standards: Non-static method JRequest::_cleanArray() should not be called statically in C:\xampp\htdocs\3nity\libraries\joomla\environment\request.php on line 463

Please what can I do because i don't have a backup of all the sites, 5 years of hard work with a current clients project at hand now.
I use a win 7 operating system 64bit, used xampp-win32-1.8.1-VC9-installer.

A: This is likely due to a different (newer) version of PHP in the latest XAMPP. PHP 5.4 (PHP 5.4.7 to be exact) is more strict about warning for bad code.
The real problem is in the actual PHP code (either yours or code used in a package use use, like Joomla).
If it is coming from your code, you should fix it. Do so by accessing a static method property or property in a static way (e.g. class Foo { public static $bar = 123; } and Foo::$bar to access it, and class Bar { public static function foo() { } } and Bar::foo() to invoke it. Note how we use :: instead of ->. This means there is no active instantiation state (In other words, $bar = new Bar(); $bar->foo(); is incorrect as it calls it as a instance method instead of statically through Bar::foo()).
And likewise if the problem is the other way around, the developer may have to declare a method as static if it is stateless and called statically.
For the Joomla case it seems there are various reports about it already:

*

*http://forum.joomla.org/viewtopic.php?t=271244

*http://www.apachefriends.org/f/viewtopic.php?p=182516

*http://www.apachefriends.org/f/viewtopic.php?p=166802
(Found by just pasting the error in Google!)
Learn more about the difference between state and static:

*

*http://php.net/manual/en/language.oop5.static.php

*http://phpduck.com/php-static-methods-and-properties/
If you only have warnings (not errors), look into "php error_reporting" to find out how to disable these innocent warnings (by lowering the error reporting level). That way you reduce the noise and can focus on things that matter.
During development you should probably not hide any warnings and so that you can spot them and improve your code. But in production it may be better to hide the warnings and only log errors.

A: After going through all the information and links presented, I was able to overcome the strict standard issue. The changes I made earlier didn't reflect because I was changing the values at the wrong line.
This is what I did:
I had to edit line 535 & 552 of my php.ini file and set display errors to OFF and also used this setting: error_reporting = E_ALL & ~E_NOTICE.
Both Joomla 1.5 and 2.5 sites don't give errors again.
Thanks to everybody.


text:
Q: Scrapy:requests didn't obey the LIFO rules I have written a spider and it does crawl some links.But the order of the link is not right and it didn't crawl some links though the request of those link has been sent.
Here is my code:
class DoubanSpider(Spider):
    name = "doubanspider"
    download_delay = 10
    allowed_domains = ["douban.com"]
    start_urls = [
       'http://movie.douban.com/subject/25864085'
    ]
    def parse(self, response):
        sel = Selector(response)
        item = DoubansciencefictionItem()
        print "processing" + str(response.url)
        grade = sel.xpath('//div[@id="interest_sectl"]//strong/text()').extract()
        item['grade'] = str(grade).encode('utf-8')
        grade0 = grade[0].encode('utf-8')
        if float(grade0)<7.7:
            return
        filmurl = str(response.url)
        film    = sel.xpath('//title/text()').extract()

        item['film'] = [n.encode('utf-8') for n in film]
        item['url'] = filmurl.encode('utf-8')

        yield item

        urls = sel.xpath('//div[@class="recommendations-bd"]//dt//a/@href').extract()

        for url in urls:
            yield Request(url, callback = self.parse)

According to http://doc.scrapy.org/en/latest/faq.html the links it crawls should follow this order(namely,DFO and I just write the last number of the link):
25864085-20326665-7065154-1044013…………

but actually the links follow:
25864085-20326665-7065154-7046723…………-1291843-6722879

well,I think maybe the links follow BFO but if they follow BFO,the order should be:
25864085-20326665-7065154-7046723…………-1291843-3274505

I can't figure out what order the spider crawls in.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I build snaps in linux mint 18.3? Can I build snaps in linux mint 18.3? In the snapcraft tutorial I read that they strong recommend ubuntu 16.04.3(LTS) and mint 18.3 is based on 16.04. is only Ubuntu necessary?

A: From official snapcraft install docs:

On Linux Mint snapd is available from the official repositories
  starting with the 18.2 (Sonya) release.

So, you can it use.


text:
Q: How to get if a zip code is in australia or not in android? In my new project I am providing user an edittext where he has to put a zip code, i have to check if this provided zip code is valid for Australia or Not. I am getting so much suggesions, but I need the easiest and simplest one. Moreover it would be the best If I could find a webservice from where I could check this.

A: Here's an api you can use : Sensis

A: First of all I don't live in Australia but Wikipedia says:

Australian Postcodes are four digits

Why don't you just test your zipcode against a Regular Expression that describes this (simple) pattern?
I suggest you to read the allocation rules for the zipcodes and see whether there are contiguous or if there are non valid zipcodes inside a given range...
Now if you don't want to reinvent the wheel, I guess you can use geocoding APIs the Google Geocoding API or Yahoo! Placefinder API. The implementation could be simple: send the postcode (I suppose you could be allowed to send only this information) and check in the response whether the country is Australia or not.


text:
Q: Send integers through python data socket with fixed size I've been trying to send some integer values over socket to a LabVIEW client using json.dumps but as the numbers change the size of each field may change, I would like to know if there is a way to pad the number with '0' without turning it into a string when I do the json dump, as it adds " " to the packet send around each number.
Example:
data = json.dumps({"Data": str(52).zfill(4)]})
self.sock.send(data.encode())

This sends
'"Data":"0052"'

I want
'"Data": 0052'

A: As @jsonharper mentioned, technically what you're asking for is no longer JSON, more on that here
However, that doesn't mean you can't use the json library to do the bulk of the work for you!
You can achieve this by passing a custom encoder class to json.dumps like this:
>>> import json

>>> class MyInt(int):
...     def __str__(self):
...         return '{:0>4}'.format(self)

>>> class MyEncoder(json.encoder.JSONEncoder):
...     def default(self, o):
...         if isinstance(o, MyInt):
...             return str(o)
...         return super(MyEncoder, self).default(o)

>>> obj = {'Data': MyInt(52)}
>>> json.dumps(obj, cls=MyEncoder)
'{"Data": 0052}'

You can do this with any class, but this can result in something that can't be decoded again with a strict JSON decoder.
See if you can get LabVIEW to read standard JSON, but if not, the above should work.


text:
Q: Permission to Send data Is there a permission to send data to the server ?
Because my data sent to the server when I use java project but when the code written in android project the data can not be uploaded.
Thanks...

A: Do you have Internet permission in Manifest file? If not, add this
<uses-permission
        android:name="android.permission.INTERNET" />

into manifest file.


text:
Q: SQL Proc 'Conversion failed' from varchar to int. Why the conversion? My question here would be... Why is it converting to int from varchar?  I'm not sure what it is trying to do
CREATE PROCEDURE #myTestProcedure
(
    @TransId VARCHAR(15)
)
AS
BEGIN
    DECLARE @Result VARCHAR(15);

WITH TestCTE (TransId, AdjRefTransId) AS
(
    SELECT TRANSID, ADJREFTRANSID
    FROM dbo.MyTable
    WHERE TRANSID = @TransId

    UNION ALL

    SELECT pet.TRANSID, pet.ADJREFTRANSID
    FROM dbo.MyTable AS pet
    JOIN TestCTE
        ON TestCTE.ADJREFTRANSID = pet.TRANSID
)

SELECT @Result =
(
    SELECT MAX(MyResult)
    FROM dbo.MyOtherTable
    WHERE TRANSID = TestCTE.TRANSID
)
FROM TestCTE
WHERE TestCTE.ADJREFTRANSID = ''

RETURN @Result
END

EXEC dbo.#myTestProcedure @TransId = 'MyTransId'

Error:
Msg 245, Level 16, State 1, Procedure #myTestProcedure  0004C61A, Line 32
Conversion failed when converting the varchar value 'MyResult' to data type int.

I can't see where it is trying to make this conversion.  Line 32 is a blank line.  No code there.

A: It is your RETURN. Stored procedures return an integer to indicate the status of the execution, not return values. You would either need to Select @Result OR have @Result be an output parameter.


text:
Q: Netbeans appearance on linux any ideas why such a drastic difference in appearance?  Have tried with Ubuntu 11.04 and 12.04 and various versions of netbeans with same results.
Images
Netbeans when started normally
and
Netbeans when started as root or su user

A: First of all, NetBeans stores its config by default in ${HOME}/.netbeans/*/etc/netbeans.conf (for more details, see the Wiki). That's the first responsible between differences in NetBeans setup, as it is user dependent.
The option you should be looking at is netbeans_default_options, and you can change your l&f (look and feel) by adding (or changing if it's already set) --laf. Take a look at the list of available l&f.
Notice that the default l&f is javax.swing.plaf.metal. (By the way, this looks like your config, as for your 'Netbeans when started normally' screenshot.)
I have an issue in linux with menus in this look and feel, as they don't render appropriate borders and they don't stand out appropriately (see screenshot below). That's the reason I always use the more recent com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel.
Your 'Netbeans when started as root or su user' screenshot looks like the SystemLookAndFeel (from your image, I would say com.sun.java.swing.plaf.windows.WindowsLookAndFeel, though I'd have expected com.sun.java.swing.plaf.motif.MotifLookAndFeel). In this case, the SystemLookAndFeel is determined at runtime, so you have to also take into account which java version your user is using. Different java versions use different l&f.

Screenshot: Menus in Netbeans 7.1.2 with Metal l&f in linux do not have appropriate borders.

A: On Linux you may change the look of applications by placing configuration files in your home directory. In this case the normal user and the root user will have different files in their home directories. You may check this by entering "ls -al" as normal and as root user and by comparing both listings.

A: As for the normal user screenshot, there is a bug in Ubuntu 12.04, see https://askubuntu.com/questions/125609/netbeans-all-menu-fonts-are-bold-after-upgrade-to-12-04
Or more precisely https://bugs.launchpad.net/ubuntu/+source/netbeans/+bug/669159

A: As it has been pointed out in a previous answer, it is an Ubuntu bug. You have a nice workaround here:
Netbeans and Ubuntu Unity
Briefly, try installing the Java Ayatana plugin
(I don't have Ubuntu, so I haven't tested it myself.)


text:
Q: jQuery: setInterval effects on the server? Sorry if this question is not suitable or too broad for STO but I can't find any information about this so I need to ask here.
This might be a silly question  to some and I think I know the answer but just to make sure, I was wondering what is the effects of using setInterval on my VPS server.
I.e. does it take a lot of resources out of my server?
It is NOT an AJAX. its just a very basic setInterval like this:
setInterval(function(){
    $('.mydiv').remove();
}, 500);

I know this is just a client side code but I was just wondering if it still has any effects on my server?
Thanks in advance.

A: you answer your question yourself: "I know this is just a client side code". It has nothing to do with server side. your server doesn't know what is going on in client browsers. Depending on the callback function of the setInterval it can only affect on browser performance

A: The above jquery execution does not have any effects on the server.  The only effect could be when the page is requested and the jquery file gets downloaded. The jquery execution is completely client side unless you make an ajax call or something to server.


text:
Q: Connecting with MongoDB on different system using PyMongo I have MongoDB working on my MacBook and I am using it in the flask app to save my form data.
Now I also have a windows 10 system in my lab at the institution and I can connect to it via VPN and now I want to run my flask app on my mac and save the form data on that windows 10 system.
I am using pymongo for connection.
client = pymongo.MongoClient('localhost', 27017)
db = client.user_login_system

I tried changing the 'localhost' to the windows 10 system IP but it didn't work.
Is there any way to connect to the windows 10 MongoDB from my mac using pymongo?

A: By default MongoDB only allows connections from the local machine; you can widen access in the mongod.conf file.
On your windows machine, edit your /bin/mongod.cfg file and set the net section to:
net:
   bindIpAll: true
   port: 27017

and then restart the MongoDB service, then try it again.
References:
https://docs.mongodb.com/manual/reference/configuration-options/#net-options
https://docs.mongodb.com/manual/reference/configuration-options/#net.bindIp


text:
Q: double buffering with FBO+RBO and glFinish() I am using an FBO+RBO, and instead of regular double buffering on the default framebuffer, I am drawing to the RBO and then blit directly on the GL_FRONT buffer of the default FBO (0) in a single buffered OpenGL context.
It is fine and I dont get any flickering, but if the scene gets a bit complex, I experience a HUGE drop in fps, something so weird that I knew something had to be wrong. And I dont mean from 1/60 to 1/30 because of a skipped sync, I mean a sudden 90% fps drop.
I tried a glFlush() after the blit - no difference, then I tried a glFinish() after the blit, and I had a 10x fps boost.
So I used regular doble buffering on the default framebuffer and swapbuffers(), and the fps got a boost as well, as when using glFinish().
I cannot figure out what is happening. Why glFinish() makes so much of a difference when it should not? and, is it ok to use a RBO and blit directly on the front buffer, instead of using a swapbuffers call in a double buffering context? I know Im missing vsync but the composite manager will sync anyway (infact im not seeing any tearing), it is just as if the monitor is missing 9 out of 10 frames.
And just out of curiosity, does a native swapbuffers() use glFinish() on either windows or linux?

A: I believe it is a sync-related issue.
When rendering directly to the RBO and blitting to the front buffer, there is simply no sync whatsoever. Thus on complex scenes the GPU command queue will fill quite quickly, then the CPU driver queue will fill quickly as well, until a CPU sync will be forced by the driver during an OpenGL command. At that point the CPU thread will be halted.
What I mean is that, without any form of sync, complex renderings (renderings for which one or more OpenGL command will be put in a queue) will always cause the CPU thread to be halted at some point, since as the queues will fill, the CPU will be issuing more and more commands.
In order to get a smooth (more constant) user interaction, a sync is needed (either with a platform-specific swapbuffers() or a glFinish()) so to stop the CPU from making things worse issuing more and more commands (which in turn would bring the CPU thread to a stop later)
reference:  OpenGL Synchronization

A: There are separate issues here, that are also a little bit connected.
1) Re-implementing double buffering yourself, while on spec the same thing, is not the same thing to the driver. Drivers are highly optimized for the common case. For example, many chips have distinct 2d and 3d units. The swap in swapBuffers is often handled by the 2d unit. Blitting a buffer is probably still done with the 3d unit.
2) glFlush (and Finish) are ignored by many drivers. Flush is a relic of client server rendering. Finish was intended for profiling. But it got abused to work around driver bugs. So now drivers often ignore it to improve the performance of legacy code that used Finish as a workaround.
3) Just don't do single buffered. There is no performance benefit and you are working off the "good" path of the driver. Window managers are super optimized for double buffered opengl.
4) What you are seeing looks a lot like you are simply leaking resources. Do you allocate buffers without freeing them? A quick and dirty way to check is if any glGen* functions return ever increasing ids.


text:
Q: How to make Tikz text nodes the same height? Iam making a quite simple draing in Tikz. I have found that I can set the with of my nodes using text width but text height doesn't work as well. Consider this example:
\documentclass{memoir}

\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}
    \begin{tikzpicture}[node distance = 1.25cm, text width=2.5cm, text height=0.25cm,
                        rectangle, draw, text centered, ]
    \node (dataset) [rectangle, draw]{Dataset};
    \node (trainingset) [rectangle, draw, below left of=dataset, node distance = 2.5 cm]{Training set};
    \node (testset) [rectangle, draw, below right of=dataset, node distance = 2.5 cm]{Test set};
    \end{tikzpicture}
\end{document}

The Test set box is smaller than the Training set box. Why? And how can I make them the same size?

A: This happens because of the g of Training. It has a depth, and given that you do not fix the box depth, that box will result bigger than the box with Text set, which has no descendant.
You can fix the depth too, adding (for exaple) text depth=0.1cm to obtain:


text:
Q: Не работает try...except с argparse Следующий код должен принимать параметр с аргументом. Если у параметра не задали аргумент, то должна отловиться ошибка в блоке except, но этого не происходит. При этом блок finally отрабатывает.
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-a', type=int)
try:
    args = parser.parse_args(['-a']) #Здесь ожидается аргумент, но мы его намеренно не передали
    print(args)
except Exception as e:
    print('Exception: %s'%(e))
finally:
    print('Finally section works')
print('End of code')

При выполнении кода на выходе видим, что блок except не отработал:
usage: t.py [-h] [-a A]
t.py: error: argument -a: expected one argument
Finally section works

Почему это происходит?

A: Смотрим, что выводит ваш код среди прочего (по крайней мере в Google Colab):
SystemExit: 2

Ага, значит argparse бросает не обычное исключение, а SystemExit, которое не унаследовано от Exception. Поймать это исключение можно, если указать, что мы хотим ловить:

*

*SystemExit

*BaseException
То есть вот так исключение поймается и программа доработает до конца:
except SystemExit as e:

И так тоже:
except BaseException as e:

Как сказано в приведённой мной ссылке, так сделано специально, чтобы случайно не поймать исключение SystemExit типовым блоком программы except Exception as e:, всё-таки это особое исключение и ловить его нужно сознательно.


text:
Q: Angular JS - jvector map accessing "onRegionClick" I'm creating a dashboard and I wanted to add this USA map and when I click on any of the region I want it's population to be printed out on the web page from the cities.json file.
Service for importing the json file.
App.factory('citiesData', ['$http', function($http) {

    return {

        getMessageData : function () {

            return $http({ method: 'GET', url: '../app/_data/usa-cities.json'})

            .then(function(response) {

                return response.data;

            }, function(errorResponse) {

                throw errorResponse.status;

            });

        }

    }

}]);

I created a directive for the jvectormap plugin and everything's working just fine.
Here's my directive code.
App.directive('mapUsa', [function() {

    return {

        restrict: 'A',
        link: function(scope, element, attrs) {

            element.vectorMap({
                map: 'us_aea_en',
                backgroundColor: 'transparent',
                zoomButtons: false,
                regionStyle: {
                    initial: {
                        fill: '#343434'
                    },
                    hover: {
                        fill: '#242424'
                    }
                },
                onRegionClick: function(event, code) {

                },
                markerStyle: {
                    initial: {
                        fill: '#F0A518',
                        stroke: '#F0A518',
                    }
                },
                markers: [
                    {latLng: [37.78, -122.41], name: 'San Francisco', style: {r: 10}},
                    {latLng: [40.71, -74], name: 'New York City', style: {r: 15}},
                    {latLng: [41.89, -87.62], name: 'Chicago', style: {r: 5}},
                    {latLng: [34.00, -118.25], name: 'Los Angeles', style: {r: 20}},
                    {latLng: [34.00, -106.00], name: 'New Mexico', style: {r: 10}},
                    {latLng: [44.50, -100.00], name: 'South Dakota', style: {r: 13}},
                    {latLng: [25.78, -80.22], name: 'Miami', style: {r: 7}},
                ]
            });

        }

    }

}])

Sample JSON :
{ "US-AL": { "name": "Alabama", "population": 4833722 }, "US-AK": { "name": "Alaska", "population": 735132 }

HTML :

Population

The code param in the onRegionClick returns me the code and I created a object for each code in the cities.json file.

*

*I wanted to know how can I not access that service in a controller inside the directive.

*How can I access the onRegionClick to get the code and retrieve the respective data of the region clicked.

*

*Using a jquery plugin and trying to use the data binding of angular is the correct method or is there any other method that has to be followed for this scenario?

Thanks in advance.

A: It's just an idea, maybe it's working.
App.directive('mapUsa', [function() {

return {

    restrict: 'A',
    link: function(scope, element, attrs) {
      element.vectorMap({
      ...
         onRegionClick: function(event, code) {
              scope.onRegionClick(event, code);
         }
      }
    },
    controller: ['citiesData', function(citiesData){
         onRegionClick: function(event, code) {
              console.log(citiesData);
         }
    }]

A: You may do something like this
    var mdata;
    app.controller('MapCtrl',['$scope','$location','$http', function($scope, $location,$http) {

            $http.get('ajax/data.json').success(function(data, status, headers, config){
                mdata = data;
              //   $scope.mapdata = data;
            }).error(function(data, status, headers, config) {

                alert("Error retrieving data");
            })

    }]);

    app.directive("mapUsa", [function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch("mdata", function (n, o) {
                $(element).vectorMap({
                    map: 'world_mill_en',
                    backgroundColor: "transparent",
                    regionStyle: {
                        initial: {
                            fill: '#e4e4e4',
                            "fill-opacity": 1,
                            stroke: 'none',
                            "stroke-width": 0,
                            "stroke-opacity": 1
                        }
                    },
                    series: {
                        regions: [{
                            values: mdata,
                            scale: ["#92c1dc", "#ebf4f9"],
                            normalizeFunction: 'polynomial'
                        }]
                    },
                    onRegionLabelShow: function (e, el, code) {

                        if (typeof mdata[code] != "undefined")
                            el.html(el.html() + ': ' + mdata[code] + ' new visitors');
                    },
                    onRegionClick: function (event, code) {

                    },
                    markerStyle: {
                        initial: {
                            fill: '#F0A518',
                            stroke: '#F0A518'
                        }
                    }
                });
            });

        }

    }

}]);


text:
Q: SQLite: Tags and Products intersection I'm new to SQLite and searching for a way to create a query to do the following:
I have 3 tables:
goods: List of goods
tags: list of tags
tag_goods: table used to associate a tag to a product

This is the structure for each table:
Goods:
id (INTEGER, autoincrement)
name (TEXT, name of the product)

Tags:
id (INTEGER, autoincrement)
name (TEXT, name of the tag)

Tag_goods:
tag_id (INTEGER)
goods_id (INTEGER)
UNIQUE (tag_id, goods_id)

What I want:
Obtain ONLY ids and names of the products that are tagged with ALL of the possible tags (NB: I need to reference all the tags in the query, not one by one).
(Meaning, for example I only have four tags: "yellow", "round", "eatable", "organic" and only goods "Cheese" and "Melon" match all of them)
With my very limited experience I understand, that I can try something like intersect, but it is impractical when there are too many tags.

A: This query:
select goods_id
from tag_goods
group by goods_id
having count(*) = (select count(*) from tags)

returns all the ids of goods that have all the tags from tags.
You can use it to return the rows from the table goods with the operator IN:
select * from goods
where id in (
  select goods_id
  from tag_goods
  group by goods_id
  having count(*) = (select count(*) from tags)
)


text:
Q: Sending FormData to different API separatly Is it possible to send FormData into two API? For example, I have two input elements like
<form id="form">
  <input type="text" name="email" ... />
  <input type="file" name="files" ... />
</form>

I want to send some of the form fields to one API and the others to another one. The idea is to have a single simple form for the user, and a single submit action, but behind the scenes we have to send the data to different APIs.
From
const formData = new FormData(document.getElementById('form'));

How can I extract the email value and send it to API1, the files need to goto API2:
fetch('API1', { method: 'POST', body: formData has only 'email' })
fetch('API2', { method: 'POST', body: formData has only 'files' })

This is because my API has different endpoints and protocols for files and meta-data, but I don't want the user to have to submit two different forms.

A: As mentioned in the comments the documentation has all the methods you need to get, set or delete form data.

// Initial form data, just for demo purposes
const initFormData = new FormData();
initFormData.append('email', 'foo@bar.com');
initFormData.append('files', 'baz');

// Email form data
const emailFormData = new FormData();
emailFormData.set('email', initFormData.get('email'));

// Files form data
const filesFormData = new FormData();
filesFormData.set('files', initFormData.get('files'));

// End results
console.log('Init:', ...initFormData.entries());
console.log('Email:', ...emailFormData.entries());
console.log('Files:', ...filesFormData.entries());
.as-console-wrapper { max-height: 100% !important; }

If you for example only want to move email to a separate formData you can also do:

// Initial form data, just for demo purposes
const initFormData = new FormData();
initFormData.append('email', 'foo@bar.com');
initFormData.append('files', 'baz');

// Email form data
const emailFormData = new FormData();
emailFormData.set('email', initFormData.get('email'));

initFormData.delete('email');

// End results
console.log('Init:', ...initFormData.entries());
console.log('Email:', ...emailFormData.entries());
.as-console-wrapper { max-height: 100% !important; }

A: Use an event listener https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
<form id="form">
  <input type="text" name="email" />
  <input type="file" name="files" />
  <input type="submit" />
</form>

<script>
var form = document.getElementById('form');
form.addEventListener('submit', function (event) {
    // Prevent form from submitting to the server
    event.preventDefault();
    var submitted = new FormData(event.target);
    var email = new FormData();
    email.set('email', submitted.get('email'));
    fetch('API1', { method: 'POST', body: email })
    var files = new FormData();
    files.set('files', submitted.get('files'));
    fetch('API2', { method: 'POST', body: files })
});
</script>


text:
Q: Invalid Selector Using Delegate Pattern I am attempting to use the delegate pattern to animate a change in height for a collectionView. The button that triggers this change is in the header. However when I press the button not only does the height not change but it also crashes with the error

'NSInvalidArgumentException', reason: '-[UIButton length]: unrecognized selector sent to instance 0x12f345b50'

I feel like I have done everything right but it always crashes when I click the button. Does anyone see anything wrong and is there anyway that I can animate the change in height for the cell the way I want it to. This is the cell class along with the protocol and the delegate.
import Foundation
import UIKit

protocol ExpandedCellDelegate:NSObjectProtocol{
    func viewEventsButtonTapped(indexPath:IndexPath)
}
class EventCollectionCell:UICollectionViewCell {
    var headerID = "headerID"
    weak var delegateExpand:ExpandedCellDelegate?
    public var indexPath:IndexPath!
    var eventArray = [EventDetails](){
        didSet{
            self.eventCollectionView.reloadData()
        }
    }

    var enentDetails:Friend?{
        didSet{

            var name = "N/A"
            var total = 0
            seperator.isHidden = true
            if let value = enentDetails?.friendName{
                name = value
            }
            if let value = enentDetails?.events{
                total = value.count
                self.eventArray = value
                seperator.isHidden = false
            }
            if let value = enentDetails?.imageUrl{
                profileImageView.loadImage(urlString: value)
            }else{
                profileImageView.image =  imageLiteral(resourceName: "Tokyo")
            }

            self.eventCollectionView.reloadData()
            setLabel(name: name, totalEvents: total)
        }
    }

    let container:UIView={
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.layer.cornerRadius = 16
        view.layer.borderColor = UIColor.lightGray.cgColor
        view.layer.borderWidth = 0.3
        return view
    }()
    //profile image view for the user
    var profileImageView:CustomImageView={
        let iv = CustomImageView()
        iv.layer.masksToBounds = true
        iv.layer.borderColor = UIColor.lightGray.cgColor
        iv.layer.borderWidth = 0.3
        iv.translatesAutoresizingMaskIntoConstraints = false
        return iv
    }()
    //will show the name of the user as well as the total number of events he is attending
    let labelNameAndTotalEvents:UILabel={
        let label = UILabel()
        label.textColor = .black
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        return label
    }()

    let seperator:UIView={
        let view = UIView()
        view.backgroundColor = .lightGray
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    //collectionview that contains all of the events a specific user will be attensing
    lazy var eventCollectionView:UICollectionView={
        let flow = UICollectionViewFlowLayout()
        flow.scrollDirection = .vertical
        let spacingbw:CGFloat = 5
        flow.minimumLineSpacing = 0
        flow.minimumInteritemSpacing = 0
        let cv = UICollectionView(frame: .zero, collectionViewLayout: flow)
        //will register the eventdetailcell
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.backgroundColor = .white
        cv.register(EventDetailsCell.self, forCellWithReuseIdentifier: "eventDetails")
        cv.register(FriendsEventsViewHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerID)
        cv.delegate = self
        cv.dataSource = self
        cv.backgroundColor = .blue
        cv.contentInset = UIEdgeInsetsMake(spacingbw, 0, spacingbw, 0)
        cv.showsVerticalScrollIndicator = false
        cv.bounces = false
        return cv
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUpCell()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setLabel(name:String,totalEvents:Int){
        let mainString = NSMutableAttributedString()

        let attString = NSAttributedString(string:name+"\n" , attributes: [NSAttributedStringKey.foregroundColor:UIColor.black,NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14)])
        mainString.append(attString)

        let attString2 = NSAttributedString(string:totalEvents == 0 ? "No events" : "\(totalEvents) \(totalEvents == 1 ? "Event" : "Events")" , attributes: [NSAttributedStringKey.foregroundColor:UIColor.darkGray,NSAttributedStringKey.font:UIFont.italicSystemFont(ofSize: 12)])
        mainString.append(attString2)
        labelNameAndTotalEvents.attributedText = mainString

    }
}

//extension that handles creation of the events detail cells as well as the eventcollectionview
//notice the delegate methods

//- Mark EventCollectionView DataSource
extension EventCollectionCell:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return eventArray.count
    }
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerID, for: indexPath) as! FriendsEventsViewHeader

            header.viewEventsButton.addTarget(self, action: #selector(viewEventsButtonTapped), for: .touchUpInside)
        return header
    }

    @objc func viewEventsButtonTapped(indexPath:IndexPath){
        print("View events button touched")
        if let delegate = self.delegateExpand{
            delegate.viewEventsButtonTapped(indexPath: indexPath)
        }

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"eventDetails" , for: indexPath) as! EventDetailsCell
        cell.details = eventArray[indexPath.item]
        cell.backgroundColor = .yellow
        cell.seperator1.isHidden = indexPath.item == eventArray.count-1
        return cell
    }
}

//- Mark EventCollectionView Delegate
extension EventCollectionCell:UICollectionViewDelegateFlowLayout{
    //size for each indvidual cell
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 50)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 40)
    }

}

This is the view that ultimately is supposed to be handling the expansion via the delegate function.
import UIKit
import Firebase

class FriendsEventsView: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    var friends = [Friend]()
    var followingUsers = [String]()
    var notExpandedHeight : CGFloat = 100
    var expandedHeight : CGFloat?
    var isExpanded = [Bool]()

    //so this is the main collectonview that encompasses the entire view
    //this entire view has eventcollectionCell's in it which in itself contain a collectionview which also contains cells
    //so I ultimately want to shrink the eventCollectionView
    lazy var mainCollectionView:UICollectionView={
        // the flow layout which is needed when you create any collection view
        let flow = UICollectionViewFlowLayout()
        //setting the scroll direction
        flow.scrollDirection = .vertical
        //setting space between elements
        let spacingbw:CGFloat = 5
        flow.minimumLineSpacing = spacingbw
        flow.minimumInteritemSpacing = 0
        //actually creating collectionview
        let cv = UICollectionView(frame: .zero, collectionViewLayout: flow)
        //register a cell for that collectionview
        cv.register(EventCollectionCell.self, forCellWithReuseIdentifier: "events")
        cv.translatesAutoresizingMaskIntoConstraints = false
        //changing background color
        cv.backgroundColor = .red
        //sets the delegate of the collectionView to self. By doing this all messages in regards to the  collectionView will be sent to the collectionView or you.
        //"Delegates send messages"
        cv.delegate = self
        //sets the datsource of the collectionView to you so you can control where the data gets pulled from
        cv.dataSource = self
        //sets positon of collectionview in regards to the regular view
        cv.contentInset = UIEdgeInsetsMake(spacingbw, 0, spacingbw, 0)
        return cv

    }()

    //label that will be displayed if there are no events
    let labelNotEvents:UILabel={
        let label = UILabel()
        label.textColor = .lightGray
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        label.font = UIFont.italicSystemFont(ofSize: 14)
        label.text = "No events found"
        label.isHidden = true
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        //will set up all the views in the screen
        self.setUpViews()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image:  imageLiteral(resourceName: "close_black").withRenderingMode(.alwaysOriginal), style: .done, target: self, action: #selector(self.goBack))
    }

    func setUpViews(){
        //well set the navbar title to Friends Events
        self.title = "Friends Events"
        view.backgroundColor = .white

        //adds the main collection view to the view and adds proper constraints for positioning
        view.addSubview(mainCollectionView)
        mainCollectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        mainCollectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
        mainCollectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
        mainCollectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
        //adds the label to alert someone that there are no events to the collectionview and adds proper constrains for positioning
        mainCollectionView.addSubview(labelNotEvents)
        labelNotEvents.centerYAnchor.constraint(equalTo: mainCollectionView.centerYAnchor, constant: 0).isActive = true
        labelNotEvents.centerXAnchor.constraint(equalTo: mainCollectionView.centerXAnchor, constant: 0).isActive = true
        //will fetch events from server
        self.fetchEventsFromServer()

    }

    // MARK: CollectionView Datasource for maincollection view
//will let us know how many eventCollectionCells tht contain collectionViews will be displayed
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print(friends.count)
        isExpanded = Array(repeating: false, count: friends.count)
        return friends.count
    }
    //will control the size of the eventCollectionCells that contain collectionViews

height is decided for the collectionVIew here
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let event = friends[indexPath.item]
        if let count = event.events?.count,count != 0{
            notExpandedHeight += (CGFloat(count*40)+10)
        }
        self.expandedHeight = notExpandedHeight

        if isExpanded[indexPath.row] == true{
            return CGSize(width: collectionView.frame.width, height: expandedHeight!)
        }else{
            return CGSize(width: collectionView.frame.width, height: 100)
        }
    }
    //will do the job of effieicently creating cells for the eventcollectioncell that contain eventCollectionViews using the dequeReusableCells function
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "events", for: indexPath) as! EventCollectionCell
        cell.backgroundColor = UIColor.orange
        cell.indexPath = indexPath
        cell.delegateExpand = self
        cell.enentDetails = friends[indexPath.item]
        return cell
    }
}

extension FriendsEventsView:ExpandedCellDelegate{
    func viewEventsButtonTapped(indexPath:IndexPath) {
        isExpanded[indexPath.row] = !isExpanded[indexPath.row]
        print(indexPath)
        UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIViewAnimationOptions.curveEaseInOut, animations: {
            self.mainCollectionView.reloadItems(at: [indexPath])
        }, completion: { success in
            print("success")
        })
    }
}

I used this post for reference to implement
Expandable UICollectionViewCell

A: This is a very common mistake.
The passed parameter in a target / action selector is always the affected UI element which triggers the action in your case the button.
You cannot pass an arbitrary object for example an indexPath because there is no parameter in the addTarget method to specify that arbitrary object.
You have to declare the selector
@objc func viewEventsButtonTapped(_ sender: UIButton) {

or without a parameter
@objc func viewEventsButtonTapped() {

UIControl provides a third syntax
@objc func viewEventsButtonTapped(_ sender: UIButton, withEvent event: UIEvent?) {

Any other syntax is not supported.


text:
Q: C sharp : Window Installed application with their icon/logo? I have a project to build, where I need find some particular installed application on windows "With their specified Logo/icon".
e.g. Mozilla firefox with logo etc
I know two ways to check installed application.
1. to check particular exe, dll in specified folder.
2. check registry key.
Both ways work finally but it not displaying installed program with logo.
anybody have Idea how to do this?
Thanx

A: Check out this code project article Extracting Icons from EXE/DLL and Icon Manipulation. Author explained how to retrieve the logo from the exe.

A: We can find information about icons of installed product from following location This information is stored in registry at Installer\product key also along with Uninstall-
Key name - HKEY_CLASSES_ROOT\Installer\Products{productID}
Value - ProductIcon
From here we can get the icons of installed application. For more detail
http://newapputil.blogspot.in/2015/06/extract-icons-of-installed-windows_17.html


text:
Q: do_rootfs failed while installing gstreamer-1.0 packages I am facing do_rootfs failed while I am installing the package using yocto in final image. Tried options like INHIBIT_PACKAGE_STRIP but to of no use.
How can I force do_rootfs to execute is there any option.

A: You have not provided nearly enough information for anyone to help you.  For example, what failed?  What was/were the error message(s).  INHIBIT_PACKAGE_STRIP likely has nothing to do with your failure.  You could also join #yocto or the yocto-related mail list as an alternative to posting here.


text:
Q: Reuse Redis connections for NodeJS Lambda function I have written the following Lambda function:
exports.handler = (event, context, callback) => {
    const redis = require('redis');
    const redis_client = redis.createClient({
        host: 'hostname',
        port: 6379
    });

    redis_client.set("foo", "bar");

    redis_client.get("foo", function(err, reply) {
        redis_client.quit();
        callback(null, reply);
    });
};

This works fine. However, I would like to reuse the Redis connection between Lambda invocations to improve performance. In theory this would be possible by moving the createClient() to outside of the handler. However, because of the "redis_client.quit()" line, that connection is killed. If I do not quit the client, the Lambda function will time out however.
What is the proper way to reuse a Redis in NodeJS when using AWS Lambda?

A: To reuse the Redis client connection define it as a global outside the handler.
const redis = require('redis');
const redis_client = redis.createClient({
    host: 'hostname',
    port: 6379
});

exports.handler = (event, context, callback) => {
    redis_client.set("foo", "bar");

    redis_client.get("foo", function(err, reply) {
        redis_client.unref();
        callback(null, reply);
    });
};

A: As you already mentioned your approach is correct way but you have to keep in mind that your Redis instance has connection limits, example AWS Elasticache maxclients is set to 65000. AWS currently allows executing 1k Lambdas in parallel so be careful with the external connections.
Currently, there is no silver bullet for Lambda external DB connections. One possible solution would be to create internal web API service which handles the communication between the DB.

A: To avoid the timeout, set callbackWaitsForEmptyEventLoop to false in the AWS Context of your Lambda. This way you do not have to close the redis connection and your lambda will not wait for it (or other connections, i.e. db connections) to close before returning:
https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html

A: Rather than creating the connection for each invocation. A better pattern would be to declare a variable in the global scope then check if empty inside the handler.
This way you are able to establish the connection once per execution environment.
const redis = require('redis');

let redisClient;

exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;

  if (!redisClient) {
    redisClient = redis.createClient({
      host: 'hostname',
      port: 6379
    });
  }

  redisClient.set("foo", "bar");

  ...
}

https://docs.aws.amazon.com/lambda/latest/operatorguide/global-scope.html
https://github.com/sequelize/sequelize/issues/4938#issuecomment-245211042


text:
Q: HTTP Range requests with php for Video Embedding for solving going to specific time in video (seek bar not work) i'm trying to run a video through php file.
it's worked.
but the problem is that when i try to go to special time in video it replay the video from the beginning.
i have 2 php files to do this. first file named "index.php" here is it's code:
<?php
    $vids = ['asbiudsaudsausbdisa' => 'video_1'];
?>
<!DOCTYPE html>
<html>
  <body>
    <video src="videos.php?h=asbiudsaudsausbdisa" controls></video>
  </body>
</html>

second file named "videos.php" here is it's code :
<?php
$vids = ['asbiudsaudsausbdisa' => 'video.mp4'];

$filehash = $_GET['h'];
$filename = $vids[$filehash];
$vd = $filename;
readfile($vd);

$file = $filename;

$filesize = filesize($file);

$offset = 0;

$length = $filesize;

if ( isset($_SERVER['HTTP_RANGE']) ) {
// if the HTTP_RANGE header is set we're dealing with partial content
    $partialContent = true;
    // find the requested range
    // this might be too simplistic, apparently the client can request
    // multiple ranges, which can become pretty complex, so ignore it for now
    preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);

    $offset = intval($matches[1]);
    $length = intval($matches[2]) - $offset;

} else {
    $partialContent = false;
}

$file = fopen($file, 'r');

// seek to the requested offset, this is 0 if it's not a partial content request
fseek($file, $offset);

$data = fread($file, $length);

fclose($file);

if ( $partialContent ) {
    // output the right headers for partial content

    header('HTTP/1.1 206 Partial Content');

    header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize);

}

header('Content-Type: ' . $ctype);
header('Content-Length: ' . $filesize);
header('Content-Type: video/mp4');
header('Accept-Ranges: bytes');

?>

what i have tried and let it works but not like i want.
i run the page with this line of code first readfile($filesize); to read the file size
then i replace it by readfile($vd); then refrech the page.
it's run now and i can go to any time of the video but that's not i want .
i want to to run from the first time and works with the online videos links.
Requested Headers
GET /s/videos.php?h=asbiudsaudsausbdisa HTTP/1.1
Host: localhost
Connection: keep-alive
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"
DNT: 1
Accept-Encoding: identity;q=1, *;q=0
sec-ch-ua-mobile: ?0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36
Accept: */*
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: no-cors
Sec-Fetch-Dest: video
Referer: http://localhost/s/
Accept-Language: en
Range: bytes=0-

Response Headers
Connection: Keep-Alive
Content-Length: 125
Content-Type: text/html; charset=UTF-8
Date: Fri, 23 Apr 2021 11:01:44 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.4.2
X-Powered-By: PHP/7.4.2

A: I have spended half day to solve something like that.
All the answers I've found tried to manually calculate
$_SERVER['HTTP_RANGE']
header('HTTP/1.1 206 Partial Content');
header('Content-Range: ...); //etc ...

as in the example of this question
At least in 2022 with php 8.0 and Chrome v 101 All this is not necessary (and also does not work)
The problem:
If you put the real path/file ex: <source src="/video_folder/file_name.mp4"> everything works correctly (we are talking about the seek bar) forwards and backwards
but
If you handle the videos through a script (as in this question) <source src="/videos.php?my_variable=file_name.mp4"> the seek bar forwards and backwards never working (at least in Chrome)
Solution:
videos.php script must be like this:
<?php
  $vids = ['asbiudsaudsausbdisa' => 'video.mp4'];

  $file_path = "/absolute_path/video_folder";
  $filehash = $_GET['h'];
  $file_name = $vids[$filehash];
  $file = $file_path."/".$file_name;
  $filesize = filesize($file);

  header('Content-Length: ' . $filesize);
  header('Content-Type: video/mp4');
  header('Accept-Ranges: bytes');
  readfile($file);
?>


text:
Q: Double Drop Downs - Content From MySQL I currently have 2 drop downs, for example, country and state. I would like to limit the second drop downs contents depending on the selection of the first drop down box. For example if United Kingdom, then US states like Texas or Alaska wouldn't be shown.
At the moment the only solution Ive found is using JS with a bunch of arrays etc.
But the problem is the contents of the drop downs are fixed, I need the content of the drop down boxes to be fetched from a MySQL database.
Does anyone know of a method to achieve this?
Thanks

A: <select name="country" id="sel1">
  <option>USA</option>
  ...
</select>

<select name="state" id="sel2">
  Some default options
  ...
</select>

<script type="text/javascript">
   var sel1 = document.getElementById('sel1');
   sel1.onchange = function() {
      ---> ajax functionality to change sel2 contents <----
   }
</script>


text:
Q: iTunes wants to delete my books I have just lost my laptop, the one that I use to sync all my books. My iBook size is 2.5g an my iCloud account can support 15g.
I tried to backup my iBooks. It shows only 750mb in the backup. When I try to sync my books, iTunes wants to delete them all.
I did not purchase any from iTunes because they don't sell books in my store. What can I do?
My iOS version is 6.1.3, iTunes is at the lastest version.

A: The most maddening thing about iTunes is it's preference to delete things before. then, syncing them.
One thing you can do now is to be sure and make a copy of your books folder, perhaps in Documents. You might also back that up to Dropbox. iCloud has not proven itself to be a reliable backup in the cloud, no matter that it syncs quite nicely.
Having said all this, I'm not sure where you are seeing the 2.5GB, and where the 750MB. Generally, one refers to books, or e-books. iBook is a reader, as is the Kindle app, for example. Calibri is, at present, the only real e-book manager for the Mac.


text:
Q: Amazon DynamoDB row-level authorization non unique ID According to this post i try to implement Amazon DynamoDB row-level authorization on my dynamoDB table,
According to the post i have to implement a condition in the IAM policy,
use this policy to to create the role which will authenticate, like this :
"ForAllValues:StringEquals": {
        "dynamodb:LeadingKeys": [
              "${cognito-identity.amazonaws.com:sub}"
        ]
}

it's clear, but there's a thing :
each user will have a unique Identiy ID, so if i create items using this unique Identity ID, in the Dynamodb it will not be unique, if the user will put more than one item
According to the post we have this image :

So i'm wondering if i didn't miss something out there, i want Amazon DynamoDB row-level authorization so each user can only query all the items he stores, and users can stores more than one item.
i've thaught to use a different sort ID, but is it the right thing to do ?

A: If your users should be allowed more than one item in the table, you just need to specify a sort key (range key).
Each item in a table must have a unique primary key, which is composed of the partition key and optionally a sort key.
The nature of the sort key will depend on entirely on the items you wish to store. Clearly each item you store must have a unique combination of partition key and sort key.


text:
Q:  does not play after 1 minute I have attached a mouse click event to this function:
play: function(sound) {
  var that = this;
  var aid = uniqueid();
  var audio = "<audio id='" + aid + "' src='" + globals.wwwroot + "sounds/" + sound + ".mp3' preload='auto'></audio>";
  var $container = that.getContainer();
  $container.html(audio);
  var $audio = $("#" + aid);

  if ($audio.length) {
    $audio[0].play();
    $audio[0].addEventListener("loadedmetadata", function() {
      if ($audio[0].duration) {
        setTimeout(function() {
          $container.remove();
        }, $audio[0].duration * 1000);
      } // end if
    });
  } // end if
}, // end method

Now, it works fine when the page loads. But exactly after 1 minute, it does not play the sound anymore. It creates the element, but I can hear nothing.


text:
Q: Stereo AudioRecord gives two identical channels I'm new to Android Studio, and trying to create my first app I need to record stereo audio.
I'm using the AudioRecord class with the following statements :
 recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate,
                                    AudioFormat.CHANNEL_IN_STEREO,
                                    AudioFormat.ENCODING_PCM_16BIT,bufferSize);

I'm using 2 external mics wired to a soundcard which is plugged into the phone through its usb plug. The stereo recording works fine when using the same soundcard with audacity on my computer.
But in the app the problem appears when using Java's method recorder.read(sData, 0 , Elements2Rec) : I get two identical channels. sData looks like [1,1,8,8,0,0,-9,-9, etc] with identical samples in each frame.
The only signal the app gets actually corresponds to the signal that one of the microphones records, but I've found no solution to get the signal from the second microphone. The same question was asked a long time ago on this link, or on that link, or on thaat link but I couldn't solve my problem with them.
Would anyone have a clue about what I could do please ?

Here is additional information, in case that might help :
My app needs to save the audio in a pcm file, that i'm writing byte after byte using the output of the recorder.read() method.
My target API is 15, i'm testing the app on a Samsung Galaxy A3.
I've declared audio permission in the manifest, but nothing more about how to handle the mics, because I don't know if it is necessary nor how to do it. I'm using WM-4000PTV2 mics and Behringer UCA222 soundcard.


text:
Q: Construction SQL using preg_replace? We are hitting an issue where we are using PHP to construct an SQL statement, and that is using the preg_replace function. Ive found the documentation here
but I'm having trouble understanding what our pattern means (this is legacy code that I've never tinkered with before.)
static function buildQuery ($sql, $params)
{
error_log ("1");
error_log (print_r($params, true));

    foreach ((array) $params as $k => $v)
    {
        $v = pg_escape_string ($v);
    error_log ("2");
    error_log ($v);
        $sql = preg_replace ("/:$k(?=\W|$)/i", "'$v'", $sql);
    }

error_log ("3");
error_log ($sql);

    return $sql;
}

The issue we are trying to fix is that before the preg_replace line is called we have a value going into the statement that is "\ \test" with two backslashes (had to add the space for it to show up here). After that line the two backslashes has evaluated into "\test" and when that gets read into our client from the database it becomes a tab followed by "est" which is not what we want. I understand that the /i has to do with recognizing pretty much any case. the \W seems to be a meta-character to find a word? $k is the key i assume for that column of the table but the rest of it i don't understand, and I don't know why it would result in trimming a backslash.
I'm pretty much a beginner on this, I'll keep looking through the documentation and maybe something will dawn on me but I could use pointers on what this means, where I can find more information about it, and how I might fix this issue.
Thanks
EDIT its a postgres database, version 9.3 if that's relevant.

A: The "\t" is likely getting interpreted by PHP's string interpolation. You could try using a single-quoted string for the pattern (you'll need to concatenate the $k variable in) but if you're able to replace this with actual parameter binding it'd be safer and more reliable.
Here's Regex101's explanation of that pattern, if it's any help:
/:test(?=\W|$)/i
:test matches the characters :test literally (case insensitive)
Positive Lookahead (?=\W|$)
Assert that the Regex below matches
1st Alternative \W
\W matches any non-word character (equal to [^a-zA-Z0-9_])
2nd Alternative $
$ asserts position at the end of the string, or before the line terminator
right at the end of the string (if any)

Global pattern flags
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])


text:
Q: Bubble Sort By Moving Nodes in Linked List (C++) I am doing bubble sort on linked list by comparing values in nodes and then moving nodes but there is a problem in my function. When i run my code it creates nodes fine but when bubblesort() function runs it throws an exception and it says "p2 was nullptr". I don't know what is wrong in my code and any help would be appreciated.
Here is my code:
#include <iostream>
#include <stdlib.h>
using namespace std;

class Node {
public:
    int number;
    Node* next;
};

class LinkedList {
    Node* head;
    Node* tail;
public:
    LinkedList() {
        head = NULL;
        tail = NULL;
    }
    void createnode(int num) {
        Node* temp = new Node;
        temp->number = num;
        temp->next = NULL;
        if (head == NULL) {
            head = temp;
            tail = temp;
        }
        else {
            tail->next = temp;
            tail = temp;
        }
    }
    void bubblesort(int size) {
        Node* temp;
        int i, j, swapped;
        for (i = 0; i <= size; i++){
            temp = head;
            swapped = 0;
            for (j = 0; j < size - i - 1; j++){
                Node* p1 = temp;
                Node* p2 = p1->next;
                if (p1->number > p2->number){
                    Node* temp1 = p2->next;
                    p2->next = p1;
                    p1->next = temp1;
                    temp = p2;
                    swapped = 1;
                }
                temp = temp->next;
            }
            if (swapped == 0)
                break;
        }
    }
    void displaynodes() {
        Node* temp;
        temp = head;
        while (temp != NULL) {
            cout << temp->number << "  ";
            temp = temp->next;
        }
        cout << endl;
    }
};

int main() {
    LinkedList l;
    int size, num;
    cout << "How many Numbers Do You Want to Store: ";
    cin >> size;
    for (int i = 0; i < size; i++) {
        cout << "Enter Number " << i+1 << ": ";
        cin >> num;
        l.createnode(num);
    }
    system("CLS");
    cout << "Data Of Nodes Before Bubble Sort: " << endl;
    l.displaynodes();
    l.bubblesort(size);
    cout << "Data Of Nodes After Bubble Sort: " << endl;
    l.displaynodes();
    system("pause");
}

A: You have many bad coding practice like using namespace std;, bad naming style and using Null instead of nullptr.
However the error was in the sorting snippet. You are trying to swapping the nodes but you can't do that without using the node previous to the current node or using doubly linked list. So in the following code, I swapped the numbers not the nodes.
void bubblesort(int size) {
    int i, j, swapped = 1;
    for (i = 0; swapped && i < size; i++){
        swapped = 0;
        Node* temp = head;
        for (j = 0; j < size - i - 1; j++){

            if (temp->number > temp -> next ->number){
                int tempNumber = temp -> number;
                temp -> number = temp -> next -> number;
                temp -> next -> number = tempNumber;
                swapped = 1;
            }
            temp = temp->next;
        }
    }
}


text:
Q: Count how many times a specific value appears in a table I've an html table that contains a list of names within sentences, which are inside  elements (i.e. Mike (Jeremy's father) used to play piano	 or The only one who speaks french is Desmond, but Mike speaks very well spanish	). I would like to count how many times a specific name appears within the entire table. I need this to be done through javascript/jquery, and not via php.
Any help would be appriciated!

A: You could use
var nbMikeInTheTable = (' '+$('table').text()+' ').split('Mike').length-1;

(the added ' ' are for the compatibility with the buggy implementation of split on IE)
Or, if you want to be sure it's the entire word and it's not cut by HTML
 var nbMikeInTheTable = $('table').html().split(/\W+/).filter(
     function(v){return v=="Mike"}
 ).length;

If you want to guard against end of words and end of cells and be sure it's not part of an attribute of a td, it's a little more complex :
var nbTimesMikeIsInTheTable = $('table td').map(function(){
    return $(this).text().split(/\W+/).filter(function(v){return v=="Mike"}).length
}).toArray().reduce(function(p,v){return p+v});

This isn't elegant but is probably not needed ;)
Demonstration (open the console)


text:
Q: Disecting a group of words from an XML file and storing them in an array in Javascript I have this XML file here.
<?xml version="1.0" encoding="UTF-8"?>
<xml>

<word>
  <threeletter>RIP</threeletter>
  <threeletter>PIE</threeletter>
  <fourletter>PIER</fourletter>
  <fourletter>RIPE</fourletter>
  <fiveletter>SPIRE</fiveletter>
  <sixletter>SPIDER</sixletter>
 </word>

 <word>
  <threeletter>SUE</threeletter>
  <threeletter>USE</threeletter>
  <fourletter>EMUS</fourletter>
  <fourletter>MUSE</fourletter>
  <fiveletter>SERUM</fiveletter>
  <sixletter>RESUME</sixletter>
 </word>
</xml>

And then  I will load them and store these words in a array called word once the page is done loading
$(document).ready(function() {

    $.ajax
    ({
        url: "dictionary.xml",
        success: function( xml )
        {
            $(xml).find("word").each(function()
            {
            words.push($(this).text());
            });
        }
    });

})
and then when I access each contents of alert(word[0]) it shows me this result
RIP
PIE
PIER
RIPE
SPIRE
SPIDER

So I am assuming that word[0] is something like this, word[0] = "RIP PIE PIER RIPE SPIRE SPIDER "
but when I do this "
var x = word[0].split(" ");
                    alert(x[0]);

it is not giving me the word "RIP"
any idea why is this happening? I want to disect all of the words in words[0](that came from an xml) and then split those words and store those words in an array but it seems to be not working any idea why?

A: May be something like this
$.ajax({
    url: 'dictionary.xml',
    async: false,
    success: function(xml) {
        $(xml).find("word").each(function(index) {
            words[index] = [];
            $(this).children().each(function() {
                words[index].push($(this).text());

            });
        });

    },
    dataType: 'XML'
});
console.log(words[0]);
console.log(words[1]);


text:
Q: prove that if an odd prime p divides $a_n, 2^{n+3} | p^2 - 1$
A past problem and its solution are shown below. For an answer, it's fine if an alternative solution is provided, though it might be significantly easier to answer the four questions below instead.

*

*In the solution, why exactly does "the claim together with the previous observation" imply that the minimal r with $((1+\sqrt{3})a_{n-1})^r - 1\in I $ equals $2^{n+3}$? Clearly one can't have $((1+\sqrt{3})a_{n-1})^{2^r} -1\in I$ for some $r < n+3.$ Let $A = ((1+\sqrt{3})a_{n-1})$. Is this because if you write $2^{n+3} = rq + r_2, 0\leq r_2 < r$, then $A^{2^{n+3}} - 1\in I$ and $A^r - 1\in I$ implies $A^{r_2} - 1\in I$ so that $r$ divides $2^{n+3}$ and hence $r$ must be a power of $2$?

*Why does the claim imply that the map $f$ is bijective?

*Why does $\prod_{x\in S} x = \prod_{x\in S} f(x)$ imply that $\prod_{x\in S} (((1+\sqrt{3}) a_{n-1})^{p^2-1} - 1)\in I$?

*Why does the claim imply $A^{p^2 - 1} - 1 \in I$?

A: Let us denote $x-y\in I$ by $x\equiv y\pmod I$.

*

*Yes.

Let $r'=\gcd(r, 2^{n+3}).$ Then there exists integers $c_1, c_2$ such that $c_1r+c_22^{n+3}=r'$.
$$A^{r'}=A^{c_1r+c_22^{n+3}}=\left(A^r\right)^{c_1}\left(A^{2^{n+3}}\right)^{c_2}\equiv1^{c_1}1^{c_2}=1 \pmod I$$
Since $r'$ is a factor of $2^{n+3}$, $r'=2^k$ for some $k\le n+3$.
If $k\le n+2$, $A^{2^{n+2}}=\left(A^{2^{k}}\right)^{2^{n+2-k}}\equiv1^{2^{n+2-k}}=1\pmod I$, which contradicts with $A^{2^{n+2}}\equiv1^{2^{n+2-k}}=-1\pmod I$, since $p$ is odd.
The contradiction above means that $k=n+3$.

*The claim implies that there is $A'\in S$ such that $A'A\equiv 1\pmod I$.

Define $f$ by $f(x)= (g\% p)+(h\%p)\sqrt3$ where $xA=g+h\sqrt3$ from some integer $g$ and $h$, $~\%~$ is the integer remainder operation, i.e.,$g\%p$ is the unique integer between $0$ and $p-1$ such that the difference between it and $g$ is a multiple of $p$.
Note that $f(x)\equiv xA\pmod I$.
If $x\in S$, then $f(x)A'\equiv xAA'\equiv x\cdot1=1\pmod I$, which implies $f(x)\not=0$. Hence $f$ maps $S$ to $S$.
Suppose $Ax\equiv Ay\pmod I$ for some $x, y\in S$. Then $x=1\cdot x\equiv A'Ax\equiv A'Ay\equiv1\cdot y = y.$ Hence $f$ is injective.
Since $f$ is an injective map from the finite set $S$ to itself, $f$ must be bijective from $S$ to $S$.

*$$\prod_{x\in S} x = \prod_{x\in S} f(x)\equiv\prod_{x\in S} (xA)=\prod_{x\in S}x~\prod_{x\in S}A=(\prod_{x\in S}x)~A^{|S|}=(\prod_{x\in S}x)~A^{p^2-1}\pmod I $$
which means $(\prod_{x\in S} x)-(\prod_{x\in S}x)~A^{p^2-1}=(\prod_{x\in S}x) (A^{p^2-1} - 1)\in I$

*For each $x\in S$, let $x'$ be the element in $S$ such that $xx'\equiv1\pmod I$, as guaranteed by the claim.
$(\prod_{x\in S}x')(\prod_{x\in S}x) (A^{p^2-1} - 1)=(\prod_{x\in S}(xx'))(A^{p^2-1} - 1)\equiv(\prod_{x\in S}1) (A^{p^2-1} - 1)=1(A^{p^2-1} - 1)=A^{p^2-1} - 1$
Since $(\prod_{x\in S}x) (A^{p^2-1} - 1)\in I$, the left-hand side of the equation above is in $I$. So is the right-hand side.


text:
Q: Evaluating a complex path integral using the complex fundamental theorem of calculus. I am currently stuck on a question that I think would be quite simple with some direction. It is:
Evaluate the integral $\int_{\gamma|[0,1]}f(z)dz$ where $f(z) = z^3-z^2+z$ where $\gamma(0) = i + 1$ and $\gamma(1) = i - 1$.
I am almost certain that I have to use the fundamental theorem of calculus in the complex plane such that:
$\int_{\gamma|[a,b]}f'(z)dz = f(\gamma(b)) -f(\gamma(a))$
but I am not sure how to get the normal path integral of $f(z)$ and not $f'(z)$. Im thinking along the lines of introducing a function $g(z) = f'(z)$ but am not sure how to proceed. Any help is appreciated.

A: If you define $F(z)=\frac14z^4-\frac13z^3+\frac12z^2$, then, since $F'=f$,$$\int_\gamma f(z)\,\mathrm dz=F\bigl(\gamma(1)\bigr)-F\bigl(\gamma(0)\bigr).$$


text:
Q: Can NumericUpDown control do this? I'm experimenting with the NumericUpDown control and have a question regarding its' flexibility.  Basically, what I would like to do is display year ranges like so:
2006-2007;
2007-2008;
2008-2009;
2009-2010
Obviously, I would like the control to cycle through a range similar to this when the buttons are pushed.
If this is possible, the range would need to start at 2006-2007 and at the current year + 1 (i.e. 2009-2010; next year: 2010-2011).
Is this possible?  Anyone have any examples?  I currently have this set up as a combo box, but thought the NumericUpDown control would be nifty to use in this situation.
Thanks...

A: Would a DomainUpDown control do what you want?

A: Try putting a NumericUpDown next to a label on the form and resize so the value is not visible (this could be done within a user control) then in the ValueChanged event handler on the NumericUpDown:
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
   int year = DateTime.Now.Year + (int)numericUpDown1.Value;
   label1.Text = String.Format("{0} - {1}", year, year + 1);
}


text:
Q: In FabricJS how do I stop object from jumping 'to top' on selection When you select an object with FabricJS the depth is changed so that it appears on top of everything else. I'd like to stop this from happening.
The selection border and handles should be on top, but the object itself should be behind the other objects so that users can see how it will be positioned once they have finished moving it around.
Is there an easy way to do this?

A: I've now found out the answer. You have to pass preserveObjectStacking = true to the constructor.
eg
canvas = this.__canvas = new fabric.Canvas('YOUR_CANVAS_NAME', {preserveObjectStacking: true});


text:
Q: Make with with multiple targets with pattern I thought that having multiple targets in a rule was the same as defining multiple rules with the same recipe for each of the targets; however, I seem to have a problem when the target/dependency have patterns.
Here's a simplified sample makefile with two different methods for building files.
all: $(foreach n, 1 2 3, $(foreach l, a b, out.$(l).$(n).txt))

1.txt 2.txt 3.txt:
    touch $@

#Method One
out.a.%.txt out.b.%.txt: %.txt
    touch $@

#Method Two
out.a.%.txt: %.txt
   touch $@
out.b.%.txt: %.txt
   touch $@

Using method one with a "make -n" I get
touch 1.txt
touch out.a.1.txt
touch 2.txt
touch out.a.2.txt
touch 3.txt
touch out.a.3.txt

but with method two I get the desired output
touch 1.txt
touch out.a.1.txt
touch out.b.1.txt
touch 2.txt
touch out.a.2.txt
touch out.b.2.txt
touch 3.txt
touch out.a.3.txt
touch out.b.3.txt

I didn't see any exceptions to the multiple target in a rule in the on-line docs. Did i miss a part of the documentation that explains why this doesn't work? Is there an easy way to make it work? (In reality, I have many more combinations of files to build than in this simple example).
(Using GNU Make 3.81)

A: Implicit (pattern) rules and explicit rules work in the opposite way from each other.  For explicit rules, multiple targets define multiple separate rules, one for each target.  For pattern rules, multiple targets means that a single invocation of the pattern rule recipe builds all the targets.
See the documentation on pattern rules.
Oh and BTW, no, there is no alternative to writing the pattern rule multiple times.  You can use various methods to automatically generate the pattern rules, but that's about it.


text:
Q: Convert a string to a resource Uri for mp3 playback I am trying to play an mp3 using the Media player class. When I hardcode the mp3 resource it works, however I would like the resource to come from a string instead of directly accessing it like R.raw.mp3name.
Bundle bundle = getIntent().getExtras();
String Choice= bundle.getString("bundledChoice");
Uri myUri = Uri.parse("R.raw." + Choice);
mPlayer = MediaPlayer.create(activity.this, myUri);
mPlayer.start();

If I change the second to last line to mPlayer = MediaPlayer.create(activity.this, R.raw.song) it will work, the problem is creating the resource URI dynamically from the string which is obtained from the bundle.
Please advise.

A: The solution I am using to this little challenge is based on @Creator's answer to this post: Android - getting an image resource into Uri: IllegalArgumentException.
The solution is to use
Uri uri = Uri.parse("android.resource://[package]/[res type]/[res name]");

[package] you either know (com.company.blah.superdooperthing), or can be determined using getPackageName().
[res type] is (I think, and it seems to work) the directory inside "res" that you are pulling the resource from. So, for an audio file .../res/raw/nicemusic.mp3, res would be "raw".
[res name] is (I think, and it seems to work) the file name (less extension) of the resouce. So, for the example above, it would be "nicemusic".
So, a more systematic approach might be:
String dataResourceDirectory = "raw";
String dataResoruceFilename = "nicemusic";

Uri uri=Uri.parse("android.resource://" + getPackageName() + "/" +
                  dataResourceDirectory + "/" + dataResoruceFilename);

Better solutions welcome!

A: Have you tried to do it this way?
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(path+"/"+fileName);

hope this helps

A: I found this solution which is very simple and works (for me), where everything I tried with Uri.parse() did not work.
private void playMp3(String nameOfFile){
    MediaPlayer mPlayer = MediaPlayer.create(this, getResources().getIdentifier(nameOfFile, "raw", getPackageName()));
    mPlayer.start();
}

A: Answer can be found here. Resolving the int ID of the resource helps: Android findViewbyId with a variant string

A: What you are trying to do it to turn the literal stringR.raw.xyz into a URI.
What you really want is to first resolve R.war.xyz into a string and then turn that into an Uri.
There is e.g. Context.getString() for this purpose.

A: Try this :
Bundle bundle = getIntent().getExtras();
    String choice= blabla// your solution to get song name
    String debug = "R.raw." + choice;
    Uri myUri = Uri.parse(debug);
    mPlayer = MediaPlayer.create(activity.this, myUri);
    mPlayer.start();


text:
Q: Espresso Framework - consistent cross-controller rendering? I have a basic CMS and i'm hugely using cross-controller rendering within it.
class Index < E
  map '/'

  # some actions

  def ad
    @steroids = render_p('anabolic-steroids/ads/left-banner')
    # some logic
  end
end

Steroids class:
class Steroids < E
  map 'anabolic-steroids'

  # actions
end

View folder:
view/
  |
  - anabolic-steroids/
      |
      - ads/
          |
          - left-banner.erb
  # other templates

Everything works well, but now customer wants anabolic-steroids URL
to be renamed into steroids
To make this work i remapped Steroids class:
map :steroids

and renamed view/anabolic-steroids/ folder to view/steroids/.
And Steroids controller works well with new URL.
But now all other controllers that were rendering steroids ad are broken :(
And i have to find all places where it is used and rename
render_p('anabolic-steroids/ads/left-banner')

to
render_p('steroids/ads/left-banner')

Odd!
I have also other lot of places where i'm using cross-controller rendering like this.
Any way to avoid useless refactoring
when such innocent renaming requests comes from customers?

A: Quite long description for a slightly trivial issue :) (joking, sorry, good question though)
The solution is simple, really simple - never use strings where you can use something else...
Seems you missed this on documentation - "To render a template of inner controller, pass controller as first argument and the template as second."
See official docs here
So to survive any renaming issues use cross-controller rendering like this:
render_p(Steroids, 'ads/left-banner')

Now you should not worry about "innocent renaming requests" :)


text:
Q: Updating values in real time Talend I'm trying to update my data with talend.I'm using tOracleOutput with the option 'update or insert' but my problem is that when there is an update i want to sum the older and the newer value of a row because my app is executing in real time.There is any help? (sorry for my bad english)

A: You can use a tOracleRow component containing a SQL update statement . Take the new value (from context, row, or globalMap) and use that in the update statement within tOracleRow, adding it to the existing value of the desired record.
Ex
"
UPDATE target_table
SET target_field = target_field " + globalMap.get("newVal") + "
WHERE target_id = " + globalMap.get("id") + "
"


text:
Q: Remove \" characters while returning json I'm returning data as a JSON via Python/Django.
I used the below code:
jsonObject = serializers.serialize('json', object, fields=('value', 'record_time'))
return HttpResponse(json.dumps(jsonObject), mimetype="application/json")

The problem is I'm getting the response as below:
"[{\"pk\": null, \"model\": \"model.table\", \"fields\": {\"record_time\": \"2009-11-18T22:45:44Z\", \"value\": 0.6533125480476399}}, {\"pk\": null, \"model\": \"model.table\", \"fields\": {\"record_time\": \"2009-11-19T15:02:15Z\", \"value\": 0.4386133754377899}}]"

where as I should be getting it in below format:
"[
  {
   "pk": null,
   "model": "model.table",
   "fields":
      {
        "record_time": "2009-11-18T22:45:44Z",
        "value": 0.6533125480476399
      }
  },
  {
    "pk": null,
    "model": "model.table",
    "fields":
      {
        "record_time": "2009-11-19T15:02:15Z",
        "value": 0.4386133754377899
      }
  }
]"

Where am I going wrong here?

A: You are serializing the object into jsonObject, but you return the original object. Just fix that and everything should work as expected.
Update:
Just change your code like this:
jsonObject = serializers.serialize('json', object, fields=('value', 'record_time'))
return HttpResponse(jsonObject, mimetype="application/json")

The change is the jsonObject in the second line.

A: Where you're going wrong is confusing the printed representation of a JSON string with the actual string itself. Those slashes are just the console showing that the double-quotes inside the string are not ending the string, but are part of it. In other words, your JSON is just fine.


text:
Q: Disable this message - Expression assignment to _ now disabled? NodeJs-REPL when I use var _ = require('underscore'), I got this message Expression assignment to _ now disabled..
Is there any way I can use to avoid this message?
I can do change the variable name, but I found someone with the same node and the message did not be raised.
root@other:/# node
> var _ = require('underscore');
undefined
>

root@my:/# node
> var _ = require('underscore');
Expression assignment to _ now disabled.
undefined
>

A: So, you can actually define your own custom repl if you want, the docs are here: https://nodejs.org/api/repl.html
For example, if you wanted to change the behavior you're describing you could overwrite the writer function to skip that output or just (probably easier) redefine the context variable itself:
  const repl = require('repl');
  const underscore = require('underscore');

  const r = repl.start('> ');
  Object.defineProperty(r.context, '_', {
     configurable: false,
     enumerable: true,
     value: underscore
   });

Or if you just want to allow it without the error, just do what they did but skip the error message:
  Object.defineProperty(context, '_', {
      configurable: true,
      get: () => this.last,
      set: (value) => {
           this.last = value;
       }
   });

To actually use the above, you need to run the script containing it (as described in the linked docs). This can be done simply with
  node myrepl.js

Or if you re running Linux or MacOS you can make it an executable script and put it in your PATH.


text:
Q: Classification for series of lat, lon points of varying lengths I have a dataset of series of latitude and longitude points. Each series of points corresponds to some activity. The number of latitude/longitude points is not the same for the series.
My dataset looks something like this:
Series
Series Time    Lat  Lon
     1    1  -43.0 97.2
     1    2  -43.1 97.2
     1    3  -43.1 97.2
     1    4  -43.1 97.3
     :    :      :    :
     2    1  -37.8 96.2
     2    2  -37.8 96.3
     2    3  -37.9 96.2
     2    4  -37.9 96.2
     2    5  -37.9 96.1
     :    :      :    :

Classifications
Series Activity
     1        A
     2        A
     3        C
     4        B
     5        C
     :        :

So for each series there a number of latitude and longitude points that occur across time.
My question, is how to classify these series of points when they have different numbers of observations?


text:
Q: Extracting the year from a timestamp field inside an Esqueleto query I am trying to make use of the unsafeSqlExtractSubField from Esqueleto to create one that will extract the year from a date, such as:
data ReportRow = ReportRow Text

userSignupData :: MonadIO m => Key User -> SqlPersistT m [ReportRow]
userSignupData _ = fmap toRow <$> select (from query)
  where
    query s =
      pure $ (extractYear $ s ^. UserCreatedAt)

    toRow yearVal = ReportRow (showText . unValue $ yearVal)

extractYear :: UnsafeSqlFunctionArgument a => a -> SqlExpr (Value Integer)
extractYear =
  unsafeSqlExtractSubField "year"

showText :: Show a => a -> Text
showText = T.pack . show

But I am getting the error:
Could not deduce
  (UnsafeSqlFunctionArgument
    (expr0 (Value UTCTime)))

  arising from a use of 'query'
from the context: MonadIO m
  bound by the type signature for:
    userSignupData :: forall (m :: * -> *).
                      MonadIO m =>
                      Key User -> SqlPersistT m [ReportRow]

The type variable 'expr0' is ambiguous

   |
20 | userSignupData _ = fmap toRow <$> select (from query)
   |                                                ^^^^^

Do I need to define an instance of UnsafeSqlFunctionArgument for UTCTime here or am I trying to fit a square peg into a round hole ?
I'm not after answers that state that I could extract the date at the haskell level, I'd like to get the year inside the query so that I can perform an SQL GROUP BY inside the query.


text:
Q: How to login Google Play use cookie and Python I want to use python script to login Google Play.And my idea is send a HTTP requset with cookie.
My Python code is like this:
import cookielib
import Cookie
import urllib2

def build_opener_with_cookie_str(cookie_str,domain,path='/'):
    simple_cookie = Cookie.SimpleCookie(cookie_str);
    cookiejar = cookielib.CookieJar();

    for c in simple_cookie:
        cookie_item = cookielib.Cookie(
            version = 0, name = c, value = str(simple_cookie[c].value),
                        port = None, port_specified = None,
                        domain = domain, domain_specified = None,domain_initial_dot = None,
                        path = path, path_specified = None,
                        secure = None,
                        expires = None,
                        discard = None,
                        comment = None,
                        comment_url = None,
                        rest = None,
                        rfc2109 = False,
            );
        cookiejar.set_cookie(cookie_item);
    return urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar));

if __name__ == '__main__':
    cookie_str = 'My Cookie str look from Chrome Request Headers cookie';
    opener = build_opener_with_cookie_str(cookie_str,domain='https://play.google.com/store/apps/collection/topselling_free');

    html_doc = opener.open('https://play.google.com/store/apps/collection/topselling_free').read();
    print html_doc;

But Google Play's response is not a login result.
So what's wrong with my Python code ? Or it was a wrong way use cookie.

A: I did not look at Google Play for the login but maybe there is for example an hidden field or something similar. You could try to use Beautiful Soup or something similar.
First analyze a normal login with Firebug or similar, where you can see what Google Play will send within a login. If there are hidden fields which are maybe random then try it with Beautiful Soup. But sometimes it is also not functional with Frameworks like Beautiful Soup when Google Play can detect it.
It would be also nice to know what you want to do with your login to maybe give a better answer.


text:
Q: cannot set custom colors for pie charts I am using iOS charts to make a pie chart, and I cannot figure out how to set the colors as custom colors with RGBA values. here is the code
        var  colors: [UIColor] = []
        colors.append(UIColor.init(red: 206, green: 173, blue: 128, alpha: 1))
        colors.append(UIColor.init(red: 136, green: 169, blue: 132, alpha: 1))
        colors.append(UIColor.init(red: 183, green: 73, blue: 32, alpha: 1))
        colors.append(UIColor.init(red: 106, green: 152, blue: 150, alpha: 1))
        colors.append(UIColor.init(red: 226, green: 120, blue: 123, alpha: 1))
        colors.append(UIColor.init(red: 47, green: 122, blue: 153, alpha: 1))

        chartDataSet.colors = colors

but it doesn't work and the chart looks like
this
edit: here is the rest of the function

    func updateChartData() {

        let chartDataSet = PieChartDataSet(entries: moods, label: nil)
        let chartData = PieChartData(dataSet: chartDataSet)
        chartDataSet.drawValuesEnabled = false
        pieChartVIew.drawEntryLabelsEnabled = false

        var  colors: [UIColor] = []
        colors.append(UIColor.init(red: 206, green: 173, blue: 128, alpha: 1))
        colors.append(UIColor.init(red: 136, green: 169, blue: 132, alpha: 1))
        colors.append(UIColor.init(red: 183, green: 73, blue: 32, alpha: 1))
        colors.append(UIColor.init(red: 106, green: 152, blue: 150, alpha: 1))
        colors.append(UIColor.init(red: 226, green: 120, blue: 123, alpha: 1))
        colors.append(UIColor.init(red: 47, green: 122, blue: 153, alpha: 1))

        chartDataSet.colors = colors

        pieChartVIew.holeColor = UIColor.clear
        pieChartVIew.data = chartData
}

and here is where I set the values
    var happyDataEntry = PieChartDataEntry(value: 0)
    var happyCount = 0
    var moods = [PieChartDataEntry]()

    override func viewDidLoad() {
        super.viewDidLoad()

        happyDataEntry.value = Double(happyCount)
        happyDataEntry.label = "happy!"
        moods = [happyDataEntry}
        updateChartData()

}

A: I have updated your code a bit: (Value changed to: var happyCount = 1)
var happyDataEntry = PieChartDataEntry(value: 0)
var happyCount = 1
var moods = [PieChartDataEntry]()

viewDidLoad Method:
override func viewDidLoad() {
    super.viewDidLoad()

    happyDataEntry.value = Double(happyCount)
    happyDataEntry.label = "happy!"
//  moods.append(happyDataEntry)   //If you uncomment this line you will see pie chart with 2 colors.
    moods.append(happyDataEntry)
    updateChartData()
}

Updated Chart method: (I have updated the color init, please take a look. )
func updateChartData() {
    let chartDataSet = PieChartDataSet(entries: moods, label: nil)
    let chartData = PieChartData(dataSet: chartDataSet)
    chartDataSet.drawValuesEnabled = false
    pieChartVIew.drawEntryLabelsEnabled = false

    var  colors: [UIColor] = []
    colors.append(UIColor.init(red: 206.0/255.0, green: 173.0/255.0, blue: 128.0/255.0, alpha: 1.0))
    colors.append(UIColor.init(red: 136.0/255.0, green: 169.0/255.0, blue: 132.0/255.0, alpha: 1.0))
    colors.append(UIColor.init(red: 183.0/255.0, green: 73.0/255.0, blue: 32.0/255.0, alpha: 1.0))
    colors.append(UIColor.init(red: 106.0/255.0, green: 152.0/255.0, blue: 150.0/255.0, alpha: 1.0))
    colors.append(UIColor.init(red: 226.0/255.0, green: 120.0/255.0, blue: 123.0/255.0, alpha: 1.0))
    colors.append(UIColor.init(red: 47.0/255.0, green: 122.0/255.0, blue: 153.0/255.0, alpha: 1.0))

    chartDataSet.colors = colors

    pieChartVIew.holeColor = UIColor.clear
    pieChartVIew.data = chartData
}

Please comment if you have any questions.
Happy to help!


text:
Q: .animate jquery not working properly i am using the .animate function to animate a div inside another div.
it works fine, in the first block of divs in the same page, but it doesnt in the other divs.
any ideas on how to fix that?
here is the jsfiddle example http://jsfiddle.net/atseros/CkaHG/2/
     $(document).ready(function() {

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

});

A: change id to other attribute.
change id to class sample:
html:

    details

    details

script :
$("div.displayscroll").hover( // <---- change to class
    //on mouseover
    function() {
      $(this).animate({
        height: '+=170' //adds 250px
        }, 'slow' //sets animation speed to slow
      );
    },
    //on mouseout
    function() {
      $(this).animate({
        height: '-=170px' //substracts 250px
        }, 'slow'
      );
    }
  );

css :
.displayscroll {
    height:30px;
    overflow:hidden;
    opacity:0.82;
    position:absolute;
    left:0px;
    right:0px;
    bottom:0;
    text-align:justify;
    background-color:#4e81bc;
    }


text:
Q: How to write a query with a AND condition as part of ContentResolver query - Android Content Provider I have this content resolver query which translates to select * from book where favflag = 1.
But now I want to change it so that it translate to select * from book where favflag = 1 AND bookid = 2;
How do I achieve this?
Here is the content resolver query:
Cursor BookCursor = getActivity().getContentResolver().query(
    BookContract.BookEntry.CONTENT_URI,
    null,
    BookContract.BookEntry.COLUMNFAVFLAG + " = ?",
    new String[]{"1"},
    null);

A: Since there is no BookContract in the Android SDK that I am aware of, I assume this is your own class. In that case, we do not know the API of that class.
With that in mind, try:
Cursor BookCursor = getActivity().getContentResolver().query(
  BookContract.BookEntry.CONTENT_URI,
  null,
  BookContract.BookEntry.COLUMNFAVFLAG + " = ? AND "+BookContract.BookEntry.COLUMNID + " = ?",
  new String[]{"1", "2"},
  null);

Substitute in the proper value for BookContract.BookEntry.COLUMNID.

A: Try this
Cursor BookCursor = getActivity().getContentResolver().query(
    BookContract.BookEntry.CONTENT_URI,
    null,
    BookContract.BookEntry.COLUMNFAVFLAG + " = ? AND "+BookContract.BookEntry.COLUMNBOOKID + " = ?", // Use your variable here in place of COLUMNBOOKID
    new String[]{"1", "2"},
    null);


text:
Q: "Accept-Ranges" header is set to "none" when a spring boot app is hosted in remote VM. It is set to "bytes" when hosted locally I have a spring boot application which needs to serve range requests for resuming downloads. Things works fine when this spring boot app is hosted in local windows machine and "Accept-Ranges" header is set to "bytes" by default. But when the same application is hosted in a remote virtual machine running windows, "Accept-Ranges" header is set to "none" by default and resuming download is not working. What can be the issue here?
>curl -I http://localhost:8080

HTTP/1.1 200
Accept-Ranges: bytes
Content-Type: application/json
Content-Length: 36121548
Date: Tue, 14 Sep 2021 13:00:19 GMT

>curl -I http://{IPofRemoteVM}:8080

HTTP/1.1 200
Accept-Ranges:  none
Content-Type: application/json
Content-Length: 36121548
Date: Tue, 14 Sep 2021 13:00:23 GMT


text:
Q: Work with 404 and response from an API I use an API to check voucher code if exist. And if voucher code exist everything is fine but problem is when I enter wrong code then I get this:
Client error: `GET https://apidev.example.co.uk/api/v1/vouchers/2869512_1-9FDS` resulted in a `404 Not Found` response:
{
"Code": 1000,
"Description": "Voucher no. is unknown please check and try again or contact Acorne on 0330 111 04 (truncated...)

I have this code in back end (laravel php):
$res = json_decode($res->getBody()->getContents(), true);
dd($res);

How I can access code 1000, and remove this error screen?
UPDATE:
screen when voucher is valid and dd($res);

A: Maybe this will help https://stackoverflow.com/a/39868378/5844171
Seems a try catch is probably what you need for that exception


text:
Q: How do I lock a file for editing that's stored on a shared folder? I have installed a windows server 2008 r2 with file service enabled. I have a network with 5 computers with windows 7 and all are on the same workgroup (I do not have domain controller and active directory).
All the computers can connect to the server and see the shared folder and the files.
My question is how can i secure that the files that are in the shared folder open once a time so everytime only one user from the network can edit the specific file.
Thanks in advance,
Spiros

A:
My question is how can i secure that the files that are in the shared
  folder open once a time so everytime only one user from the network
  can edit the specific file.

That's built-in by design.  It's called opportunistic locking, see here: http://support.microsoft.com/kb/296264

By default, opportunistic locking is enabled for server message block
  (SMB) clients that run one of the Windows operating systems that is
  listed in the "Applies to" section. Opportunistic locking lets clients
  lock files and locally cache information without the risk of another
  user changing the file. This increases performance for many file
  operations but may decrease performance in other operations because
  the server that grants the opportunistic lock must manage the breaking
  of that lock when another user requests access to the file.

See also: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365433%28v=vs.85%29.aspx