text:
Q: Getting incorrect northing/easting in proj4 from converting Lat/long to NAD83 Maine West 1802 I'm trying to convert latitude/longitude to northing and easting via proj4js.
This is the string im using to project from.
+proj=tmerc +lat_0=42.83333333333334 +lon_0=-70.16666666666667 +k=0.9999666666666667 +x_0=900000.0000000001 +y_0=0 +ellps=GRS80 +datum=NAD83 +to_meter=0.3048006096012192 +no_defs

And here are the latitude/longitude coordinates:
44.128783,-70.201664

This is what I get back as  a result:
9650143.893240128, -51464079.10841816

But this is not correct. When I try to convert this back to lat/long with this tool:
https://www.earthpoint.us/stateplane.aspx
and the proper zone number 1802 - Maine West (1983)
I get incorrect response. I'm sure I'm using the right zone / project string so why is it shooting out the wrong northing and easting?


text:
Q: Use field from previous query result in another query in mongodb I have below query, in 2nd query I get null for que.name.
var que  = db.que.find({ _id: u.que_id }, {name:1})
db.documents.update(u, {$set: {que_name: que.name}})

I can see data for que as below
 { "_id" : "general", "name" : "General" }

but no data for que.name. What's wrong?

A: find returns cursor to the matching documents. So que is not a single document - it is cursor. Cursor do not have field name - that's why you have no data for que.name. Cursor points to documents which you have found (yes, there could be several documents). If you will iterate over cursor, you will get each document. Just to show what is cursor:
var que  = db.que.find({ _id: u.que_id }, { name: 1 }) // que is a cursor
que.forEach(function(d) { print(d.name); })

If you want to get document, then use findOne method, which returns one document matching your search criteria:
var que  = db.que.findOne({ _id: u.que_id }, { name: 1 }) // now que is document
que.name // prints name value

A: db.collection.find returns a cursor. Try using findOne()
var que = db.que.findOne( { _id: u.que_id }, {name:1})

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set a javascript code value for an asp variable? How to set a javascript code value for an asp variable?
In the following code title: '<%=Zaman%>', part <%if act="buhafta" then%> gives an empty result. What I have to do to make sure there is no empty result.

<%Dim Zaman
if act="bugun" then%>
<%Zaman=date()%>
<%end if%>
<%if act="dun" then%>
<%Zaman=date()-1%>
<%end if%>
<%if act="" OR act="buay" then%>
<%Zaman=(monthname(month(date)) & (" / ") & (year(date)))%>
<%end if%>
<%if act="oncekiay" and NOT operatorGor.eof then%>
<%Zaman=(monthname(month(operatorGor(4)))& (" / ") &(year(date)))%>
<%end if%>
<%if act="buhafta" then%>
<%Zaman=Response.Write("") %>
<%end if%>
<%if act="gecenhafta" then%>
<%Zaman=Response.Write("") %>
<%end if%>


text:
Q: Ethernet gives me 169.254.xx.xx When I try to connect my computer to the internet via Ethernet I get 'unidentified network', my IP address becomes 169.254.xx.xx and has no default gateway.
Setting a static IP address still gives me the 'unidentified network'.
I've checked the DHCP settings on my router and they are all fine.
I've tried replacing my ethernet cables too as a few sources says it may be a faulty wire.
edit:
forgot to actually ask a question. Does anyone know a possible way to fix this issue?
Also I've already tried the suggested fixes listed here:
I am using Windows 7 and I get a 169.254.x.x ip address to no avail. WiFi works just fine so it's not that. I've tried replacing the cables and nothing. I am using a powerline adapter so it might be those.

A: Your DHCP service is not working correctly... "getting" a 169.254.x.x address means your computer is not receiving a DHCP offer that it can accept. After an attempt to get DHCP, if an offer is not received or cannot be accepted for some reason, the adapter/network driver automatically assigns the interface a bogus IP address of 169.254.x.x

A: Okay so after trying a few things I managed to get it working. The issue wasn't the cables or the computer itself it was simply the powerline adapters. For some reason they were out of sync and thus no data was being transferred between them. Thank you all for the help.


text:
Q: What does "$>" represent in Ruby documentation? As in:
def PP.pp(obj, out=$>, width=79)
...

This is from the pp method of the PP class:
http://www.ruby-doc.org/stdlib-2.0/libdoc/pp/rdoc/PP.html#method-c-pp

A: $> is the IO destination for Kernel#print (and therefore puts), and other output methods. It defaults to $stdout, but can be changed to change the behavior of print, printf, puts, etc.


text:
Q: Processing huge file in PHP I have a large file which needs to be uploaded and processed in Laravel. The file is stored in an API server and is processed using a background worker. It is impossible to process the file in one stretch as it will cause PHP memory overflow. So what I am doing is the worker will call API end point which process the file with an offset which will be incremented by 1000 each time. So the API will fetch from this offset and process the data. This process continues until all the records are processed.
Now I would like to know is there any better method for doing this ? I am asking this because the methodology that I am following involves lot of network calls and it will increase as the number of entries in the file grows. Also if a call fails, how can I start from the current offset other than starting again from the beginning ?


text:
Q: Need help on multiselect for bootstrap typehead using ajax source? I want`s to use bootstrap Typehead for auto fill but I am getting confused, I am using below JS for this can any body help on this.
My Requirement is :
What ever user fill using typehead should come into textarea ($myTextarea) .
I wants to get selected values into a textarea.
$(document).ready(function() {
$('input.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: '/test/typehead/data.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
console.log(data);
process(data);

}
});
}

});
updater: function(item) {
    $myTextarea.append(item, ' ');
    return '';
}
});

Thanks,
Ashok

A: Solved....Some Syntax error
    $(document).ready(function() {
    var $myTextarea = $('#myTextarea');
$('input.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: '/test/typehead/data.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
console.log(data);
process(data);

}
});
},
updater: function(item) {
$myTextarea.append(item, ' ');
return '';
}

});
});

A: jQuery(function ($) {
            $('.typeahead').typeahead({
                source: function (query, process) {

                    return $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "url",
                        data: '{ "query": "' + query + '"}',
                        dataType: "json",
                        success: function (data) {
                            //use data.d in case of asp.net
                            return process(data);
                        },
                        failure: function (response) {
                            alert("Failure");
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            alert("There seems to be an error");
                        }
                    });
                },
              updater: function(item) {
              $myTextarea.append(item, ' ');
               return item;
             }
            });
        });

This should help you out,
For further reading read this
Cheers!!!


text:
Q: ansible-container build error - dockers I am working on ansible container example as mentioned in http://docs.ansible.com/ansible-container/getting_started.html and getting error while doing ansible-container build.
Container Type is dockers.
I am new to Ansible containers module and any help is much appreciated. Thank you!!
[user@hostname hello-world]$ sudo pip install ansible-container[docker]
Collecting ansible-container[docker]
  Using cached ansible-container-0.9.2.tar.gz
Requirement already satisfied: Jinja2>=2.9 in /usr/lib64/python2.7/site-packages (from ansible-container[docker])
Requirement already satisfied: pip>=6.0 in /usr/lib/python2.7/site-packages (from ansible-container[docker])
Requirement already satisfied: PyYAML>=3.12 in /usr/lib64/python2.7/site-packages (from ansible-container[docker])
Requirement already satisfied: requests>=2 in /usr/lib/python2.7/site-packages (from ansible-container[docker])
Requirement already satisfied: ruamel.yaml>=0.14.2 in /usr/lib64/python2.7/site-packages (from ansible-container[docker])
Requirement already satisfied: six>=1.10 in /usr/lib/python2.7/site-packages (from ansible-container[docker])
Requirement already satisfied: structlog[dev]>=16.1 in /usr/lib/python2.7/site-packages (from ansible-container[docker])
# These are the python requirements for your Ansible Container builder.
Requirement already satisfied: docker>=2.4.0 in /usr/lib/python2.7/site-packages (from ansible-container[docker])
Requirement already satisfied: MarkupSafe>=0.23 in /usr/lib/python2.7/site-packages (from Jinja2>=2.9->ansible-container[docker])
Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python2.7/site-packages (from requests>=2->ansible-container[docker])
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/lib/python2.7/site-packages (from requests>=2->ansible-container[docker])
Requirement already satisfied: idna<2.7,>=2.5 in /usr/lib/python2.7/site-packages (from requests>=2->ansible-container[docker])
Requirement already satisfied: urllib3<1.23,>=1.21.1 in /usr/lib/python2.7/site-packages (from requests>=2->ansible-container[docker])
Requirement already satisfied: ruamel.ordereddict; platform_python_implementation == "CPython" and python_version <= "2.7" in /usr/lib64/python2.7/site-packages (from ruamel.yaml>=0.14.2->ans
ible-container[docker])
Requirement already satisfied: colorama; extra == "dev" in /usr/lib/python2.7/site-packages (from structlog[dev]>=16.1->ansible-container[docker])
Requirement already satisfied: backports.ssl-match-hostname>=3.5; python_version < "3.5" in /usr/lib/python2.7/site-packages (from docker>=2.4.0->ansible-container[docker])
Requirement already satisfied: ipaddress>=1.0.16; python_version < "3.3" in /usr/lib/python2.7/site-packages (from docker>=2.4.0->ansible-container[docker])
Requirement already satisfied: docker-pycreds>=0.2.2 in /usr/lib/python2.7/site-packages (from docker>=2.4.0->ansible-container[docker])
Requirement already satisfied: websocket-client>=0.32.0 in /usr/lib/python2.7/site-packages (from docker>=2.4.0->ansible-container[docker])
Installing collected packages: ansible-container
  Running setup.py install for ansible-container ... done
Successfully installed ansible-container-0.9.2
[user@ hello-world]$

[user@hostname hello-world]$ ls -alrt
    total 40
    -rw-rw-r--.  1 user user  144 Mar 31 00:28 ansible.cfg
    -rw-rw-r--.  1 user user 1181 Mar 31 00:28 meta.yml
    -rw-rw-r--.  1 user user  298 Mar 31 00:28 requirements.yml
    -rw-rw-r--.  1 user user   31 Mar 31 00:29 requirements.txt
    -rw-rw-r--.  1 user user  108 Mar 31 00:29 helloworld.py
    drwxrwxr-x.  3 user user   18 Mar 31 00:33 roles
    -rw-rw-r--.  1 user user 2706 Mar 31 00:35 container.yml
    -rw-rw-r--.  1 user user  130 Mar 31 00:59 ansible-requirements.txt
    drwx------. 12 user user 4096 Mar 31 00:59 ..
    drwxrwxr-x.  3 user user 4096 Mar 31 01:00 .
    -rw-rw-r--.  1 user user   78 Mar 31 01:00 =36.2.7
    [user@hostname hello-world]$

[user@hostname hello-world]$ sudo ansible-container build
ERROR   Unknown exception
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/container/cli.py", line 299, in __call__
    getattr(core, u'hostcmd_{}'.format(args.subcommand))(**vars(args))
  File "/usr/lib/python2.7/site-packages/container/__init__.py", line 28, in __wrapped__
    return fn(*args, **kwargs)
  File "/usr/lib/python2.7/site-packages/container/core.py", line 156, in hostcmd_build
    config['services'], **kwargs)
  File "/usr/lib/python2.7/site-packages/container/utils/loader.py", line 16, in load_engine
    package='container')
  File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/usr/lib/python2.7/site-packages/container/docker/engine.py", line 51, in <module>
    container.__version__
ImportError: You must install Ansible Container with Docker(tm) support. Try:
pip install ansible-container[docker]==0.9.2
[user@sudo hello-world]$

A: I suggest to use virtualenv.
Take a look here for a full sample. First, install virtualenv and ansible inside it
$ sudo pip install virtualenv
$ virtualenv venv
$ source venv/bin/activate
$ pip install ansible
$ pip install ansible-container[docker]
$ pip install docker==2.7.0

Then, clone the sample and build it
$ git clone https://github.com/mkowsiak/ansible-with-big-file.git
$ cd ansible-with-big-file
$ git checkout smaller-file-that-works
$ ansible-container build


text:
Q: Programming in a batch script Hey all I have a simple problem I was hoping someone can give me assistance with. I'm trying to get WMIC to return output however on different machines, the executable is in different directories. Is there a method to check all directories I list to get it to run, e.g.:
IF EXIST
wmic=c:\checkhere\
ELSE
wmic=c:\checkthisone\
CONTINUE

A: The following is a simple way of setting an environment variable to some path that has a file you are looking for.  A rather brain dead way but easy to understand/change:
if exist c:\path1\some.exe set asdf=c:\path1\
if exist c:\path2\some.exe set asdf=c:\path2\
if exist c:\path3\some.exe set asdf=c:\path3\
if %asdf%x=x goto couldnotfindit
set path=%path%;%asdf%

A: As an option You could add all of them to the PATH variable and simply run wmic.


text:
Q: AWS CloudFormation - Stack name list as Parameter Is there a way to specify a list of Stack Names as a parameter in a CloudFormation template?
I've tried:
"Parameters": {
  "NetworkStackName": {
    "Type": "List<AWS::CloudFormation::Stack>"
  }
}

Also:
"Type": "List<AWS::CloudFormation::Stack::Id>"
[...]
"Type": "List<AWS::CloudFormation::Stack::StackName>"
[...]
"Type": "List<AWS::CloudFormation::Stack::StackName>"
[...]
"Type": "List<AWS::Stack>"

But no luck ... And can't find any documentation for anything other than listing AWS::Ec2 resources.

A: You can't use any of AWS::CloudFormation::Stack, AWS::CloudFormation::Stack::Id, CloudFormation::Stack::StackName, AWS::Stack as such a parameter types do not exist. You can find the available parameter types here (under "AWS-Specific Parameter Types").
Your parameter could be a CommaDelimitedList:
"Parameters": {
  "NetworkStackName": {
    "Type": "CommaDelimitedList"
  }
}

so that you can inject your stack names as a comma separated list string, e.g.
"stackName1,stackName2,stackName3"

Using this method, NetworkStackName will result in
["stackName1", "stackName2", "stackName3"]


text:
Q: ControlLoaded event I know there is no such event, but is there something similar I can use?
I have ASP.NET usercontrols which are loaded dynamically into a container, which gives a very smooth effect.
The downside of doing this is that I want to run some client-side javascript when a control has finished loading, and I don't know how.
It took me a while to figure out why my jQuery scripts weren't running, then I realised they only ran on $(document).ready() and that only occurs when the entire page loads! (Duh!)
Can anyone think of a way of doing this?
Thanks :)

Getting more complicated now!
I'm trying to use a DOM Mutation Observer to watch the container so I can run a script when it changes.
But I'm getting an error: An attempt was made to reference a Node in a context where it does not exist.
The DOM element does exist, but I'm not sure I understand the error correctly.
Here is my observer code:
$(document).ready(function () {

    // select the target node
    var target = $('#contentPanel');

    if (typeof (target) != 'undefined') {
        // create an observer instance
        var observer = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                console.log(mutation.type);
                if (mutation.addedNodes) {
                    alert('New nodes');
                }
                //rememberMe();
            })
        });

        // configuration of the observer:
        var config = { attributes: false, childList: true, characterData: true }

        // pass in the target node, as well as the observer options
        observer.observe(target, config); // <== error occurs here
    }
});

The final observer code:
$(document).ready(function () {

    // select the target node
    var target = $('#contentPanel');

    if (typeof (target) != 'undefined') {
        // create an observer instance
        var observer = new MutationObserver(function (mutations) {
            var doRememberMe = false;
            mutations.forEach(function (mutation) {
                if (mutation.addedNodes) {
                    doRememberMe = true;
                }
            })
            if (doRememberMe) rememberMe();
        });

        // configuration of the observer:
        var config = { attributes: false, childList: true, characterData: true }

        // pass in the target node, as well as the observer options
        //observer.observe(target, config);
        observer.observe(document.body, config); // <== apply observer to whole document! (could be done nicer)
    }
});

A: Got it, in that case try this at the end of your container (you can define CallLoadedEvent in a separate JS file):
<asp:Panel id="Container" runat="server">
   <!-- controls dynamically load here -->
   <script>
      CallLoadedEvent();
   </script>
</asp:Panel>

A: I was eventually able to get it working using the DOM Mutation code added above.
However the only way it would work was if I applied the listener to the whole document.
For some reason I wasn't able to apply it just to the element that was being modified; perhaps for some reason it was going out of scope, even though I was able to test it existed first! Oh well.


text:
Q: not authorized to use function: current_timestamp I am trying to compare date time in WEBSQL with CURRENT_TIMESTAMP and i am getting error :
not authorized to use function: current_timestamp

I retrieve datetime from server and store in websql ! And display the entries which are more or less then CURRENT_TIMESTAMP ! How to solve this error?


text:
Q: Write-Output Failing Inside Foreach Loop - Powershell I am new to Powershell and I am wondering why this function doesn't work the way I want it too.  The following function uncomments line in the hosts file of the computer specified. It works great!  But I want the ability to output each line to the screen using a Write-Output and get the variable and store it in another array.  This Write-Output doesn't do anything and I cannot add it to the array.  Why?  The above Write-Output works just fine.
function UnCommentHostsFile($ip){

   Write-Output "This Write-Output Works!"

   $hosts = $hosts | Foreach {

       #This part of the function works great!
       if ($_ -match $regex + $ip){
           $_.replace("#", "")

           #This is where I want to add it to an array and write-output but I can't.
       }
       else {
           $_
       }

       #This does not output!
       Write-Output $_
   }
}

Any help would be greatly appreciated!  Thanks! :)

A: To answer your question, when you do this:
$hosts = $hosts | Foreach {...}

everything that is output to the pipeline within that foreach script block is going to get re-directed to the variable $hosts.
Write-Output writes to the pipeline, and you're doing it within that script block.
If you want to explicitly write to the screen, use Write-Host, or Write-Verbose.

A: You don't really need the Write-Output. Leave it as an object, and you can format that object however you want outside the function. I updated it so that for each line if it matches your regex it replaces # with nothing as you already had it, but I removed the Else clause because it was pointless. I changed $_.replace("#", "") to $_ = $_.replace("#", "") so that it actually updates the line in $Hosts instead of just echoing it. Then when all is said and done it outputs the entire $hosts updated lines and all.
function UnCommentHostsFile($ip){

   $hosts = $hosts | Foreach {

       #This part of the function works great!
       if ($_ -match $regex + $ip){
           $_ = $_.replace("#", "")

           #This is where I want to add it to an array and write-output but I can't.
       }

       #This does not output!
   }
   $Hosts
}

Edit: When you call the function it should spit back whatever is in $Hosts, so it should output to the screen. No need to write-output or anything. It will show up on screen for the user, unless you are redirecting the output to something, in which case just add a bit to the pipe that prints it to the screen.


text:
Q: Xcode Server CI Bot Test Session exited(-1) I am getting an error when trying to run tests on XcodeServer against simulator devices. The tests sometimes pass for one device and fail for another, but the failing device is not always the same one. This can happen in a single session.
The log file error is as follows:
2015-03-23 10:44:11.029 Initializing test infrastructure.
2015-03-23 10:44:11.029 Writing testing status log to /Library/Developer/XcodeServer/Integrations/Integration-7e6e54f21a2fd25cddc9df0436cb3688/Session-2015-03-23_10:44:10-tH1BD4.log.
2015-03-23 10:44:28.676 Launch session started, setting a disallow-finish-token on the run operation.
2015-03-23 10:44:30.352 Adding console adaptor for test process.
2015-03-23 10:44:39.566 Creating the connection.
2015-03-23 10:44:39.567 Listening for proxy connection request from the test bundle (all platforms)
2015-03-23 10:44:39.567 Resuming the connection.
2015-03-23 10:44:39.567 Test connection requires daemon assistance.
2015-03-23 10:44:39.568 Checking test manager availability..., will wait up to 120s
2015-03-23 10:45:05.253 testmanagerd handled session request.
2015-03-23 10:45:05.254 Waiting for test process to check in..., will wait up to 120s
2015-03-23 10:46:47.578 Test operation failure: Test session exited(-1) without checking in.
2015-03-23 10:46:47.645 _finishWithError:Error Domain=IDEUnitTestsOperationsObserverErrorDomain Code=3 "Test session exited(-1) without checking in." UserInfo=0x7f8be43e40c0 {NSLocalizedDescription=Test session exited(-1) without checking in.} didCancel: 1

Any ideas would be really helpful.

A: The simulator requires a user GUI context to run. If the server is launched from /Library/LaunchDaemons then it's running in the system (root) context and doesn't have a GUI context. This is a problem if using Atlassian Bamboo as well as Jenkins for CI. Facebook devs have also encountered this problem with xctool.
You may need to launch the XcodeServer from a user context, i.e. create a plist file in ~/Library/LaunchAgents, and have that user continuously logged in. I would think Apple would have that problem solved during installation.

A: Try launching this command on the server:
sudo /usr/sbin/DevToolsSecurity --enable

some more details in this answer


text:
Q: TSQL - Do you calculate values then sum, or sum first then calculate values? I feel stupid asking this - there is probably a math rule I am forgetting.
I am trying to calculate a gross profit based on net sales, cost, and billbacks.
I get two different values based on how I do the calculation:
(sum(netsales) - sum(cost)) + sum(billbackdollars) as CalculateOutsideSum,
sum((netsales - cost) + BillBackDollars) as CalculateWithinSum

This is coming off of a basic transaction fact table.
In this particular example, there are about 90 records being summed, and I get the following results
CalculateOutsideSum: 234.77
CalculateWithinSum:  247.70

I imagined this would be some sort of transitive property and both results would be the same considering it's just summation.
Which method is correct?

A: From a mathematical point of view, you should get exactly the same value with both your formulas.
Anyway in this cases it's better to performs sum after any calculation.
EDIT AFTER OPENER RESPONSE:
And treat your data with isnull function or other casting function which increases data precision.
Rounding, formatting and castings which decreases data precision should be applied after sums.

A: Just figured it out...
Problem was Net Sales was null for 3 rows, causing the calculation to become null, and incorrectly summing. After adding an isnull, both sums come out the same.


text:
Q: How to share private data between multiple apps by same developer I am facing a problem where I need to store sensitive data where it will accessible to all of my apps, but not to the other apps. I know one way where we set same "SharedUSerId" to all the apps. But this is not possible now because one of our app, which does not have any SharedUSerId set, is already in production. If I change the SharedUserId now, the users won't be able to update the app.
Is there any way to have a private storage which is accessible to only the apps signed with same signature?

A: You can use your own custom designed Intent filters. So your other apps may send a broadcast on which you are listening to.
https://developer.android.com/guide/components/intents-filters


text:
Q: How to install the pthreads PHP extension on Debian 9 Surprisingly, I can't find an answer anywhere. I need help to install the pthreads PHP extension on Debian 9 with PHP 7.3 installed.
If I write php -v, I get the following:
PHP 7.3.6-1+0~20190531112735.39+stretch~1.gbp6131b7 (cli) (built: May 31 2019 11:27:35) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.6, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.6-1+0~20190531112735.39+stretch~1.gbp6131b7, Copyright (c) 1999-2018, by Zend Technologies

I tried to download the .tgz file form pecl.php.net, extract it, put it in /etc/php/7.3/fpm/ext (I created the ext directory) and define the extension_dir as that directory in php.ini.
Then I wrote in the php.ini file extension=/etc/php/7.3/fpm/ext/pthreads-3.1.6 and I rebooted my server.
If I write php -m, I still not see the pthreads extension.


text:
Q: Interpretation of the Weil algebra Cartan introduced the Weil algebra $W(\mathfrak{g})$ associated to a Lie algebra $\mathfrak{g}$ over a field $k$ of characteristic $0$. This consists of a dga whose underlying graded abelian group is given by $Sym(\mathfrak{g}^*)\otimes \Lambda^* \mathfrak{g}^*$ with a differential which can be constructed as follows.
We first define the graded derivation $h \colon W(\mathfrak{g}) \rightarrow W(\mathfrak{g})$ giveny by
\begin{equation}
h(V \otimes x_1\wedge \dots \wedge x_n)=\sum_{i=1}^n(-1)^{i-1} (x \otimes V) \otimes x_1 \wedge \dots \wedge \hat{x_i} \wedge \dots \wedge x_n \qquad h(V \otimes 1)=0
\end{equation}
where $V \in Sym(\mathfrak{g}^*)$ and $x_1\wedge \dots \wedge x_n \in \Lambda^n \mathfrak{g}^*$. Then we add this $h$ to the usual differential defined on the Chevalley-Eilenberg complex of $\mathfrak{g}$ where we consider $Sym(\mathfrak{g}^*)$ as coefficient module. The wiki page gives a detailed formula https://en.wikipedia.org/wiki/Lie_algebra_cohomology.
It is a core result that the cohomology of this complex reduces to the base field $k$ in degree $0$. From this we can produce the Cartan map, which is a function going from the invariant elements of $Sym(\mathfrak{g}^*)$ to the space of primitive elements of $H^*(\mathfrak{g}; k)$. If the Lie algebra is reductive it can be see this is a bijection.
I found a complete reference in "Cohomology of principal bundle and homogeneous" by Greub, Halperin and Vanstone, so I am not asking for clarification about a particular point of this theory. What I am looking for is some kind of explanation of what's the idea behind this cochain complex. Everything in this formulas and constructions works but I have no idea why or how these came to be.
I read somewhere that the Weil algebra is some kind of link between the "connections" (I do not know what these should be) and the cohomology of $\mathfrak{g}$. If someone could explain this I would really be grateful.

A: I am personally not quite sure on the precise history, but the earliest paper mentioning the Weil algebra seems to be "Cohomologie réelle d'un espace fibré principal différentiable." by Cartan. I am going to present to you the story that convinced me that it is a very natural concept that one could reasonably come up with oneself, if you accept that certain other geometric concepts are worthwhile studying. I also believe this is closely related to what Cartan originally did in his paper.
I'm not going to say anything new, all of this is contained in the book by Greub, Halperin and Vanstone that you cite, but I'll try to streamline the idea. I just hope you're comfortable with some differential geometry :)

Let $P$ and $M$ be smooth manifolds, and $P \to M$ a principal $G$-bundle. Recall that that means that you have a free and transitive action of the Lie group $G$ on the fibres of the bundle. This allows you to define, for every $\xi \in \mathfrak{g}$, the fundamental vector field $\xi_P \in \Gamma(TP)$
Then a $\mathfrak{g}$-valued differential form $\omega \in \Omega^1(P,\mathfrak{g}) = \Omega^1(P) \otimes \mathfrak{g} = \Gamma(T^* P) \otimes \mathfrak{g}$ is called a connection form for the principal bundle if we have:

*

*It is equivariant with respect to the induced action of $G$ on vector fields $\Gamma(TP)$ and the adjoint action of $G$ on $\mathfrak{g}$, viewing $\omega$ as a map $\Gamma(TP) \to \mathfrak{g}$,

*It maps fundamental vector fields to its generators, meaning that for every $\xi \in \mathfrak{g}$, it fulfils $\omega(\xi_P) = \xi$.

Geometrically, this notion allows one to split up the principal bundle $P$ into vertical and horizontal directions with respect to the bundle structure, so it is definitely useful, but it may be a bit tricky to remember the precise definition.

We can see such a $\mathfrak{g}$-valued differential form as an element of $\Gamma(T^*P) \otimes \mathfrak{g}$, as a map $\Gamma(TP) \to C^\infty(P,\mathfrak{g})$, but to understand the connection to the Weil algebra, let us take on the perspective that $\omega$ is a $G$-equivariant map $$\omega: \mathfrak{g}^* \to \Omega^1(P).$$
Now, naively, both sides of this map could be understood as naturally sitting inside two well-known cochain complexes, the left-hand side $\mathfrak{g}^*$ sitting in the first degree of the Chevalley-Eilenberg complex $C^\bullet_{\text{CE}}(\mathfrak{g})$, and $\Omega^1(P)$ in the first degree of the de Rham complex $\Omega^\bullet(P)$. An instinctive reaction should then be to extend this map to a map of complexes $C^\bullet_{\text{CE}}(\mathfrak{g}) \to \Omega^\bullet(P)$ by setting for all $\alpha_1,\dots,\alpha_n \in \mathfrak{g}^*$:
$$\omega (\alpha_1 \wedge \dots \wedge \alpha_n) := \omega(\alpha_1) \wedge \dots \wedge \omega(\alpha_n) \in \Omega^n(P).$$

Turns out: This cannot be done in general! This map does not always respect the differential on both sides. The failure to do so is characterized by what geometers call the curvature $\Omega$ of the connection $\omega$, which, without going into too much detail, can be defined as the difference "$(\omega \wedge \omega) \circ d_{\text{CE}} - d_{\text{dR}} \circ \omega$", and turns out to just be a $\mathfrak{g}$-valued 2-form $\Omega \in \Omega^2(P, \mathfrak{g})$, or, equivalently, a map
$ \Omega : \mathfrak{g}^* \to \Omega^2(P)$. If this curvature is zero, we call $\omega$ a flat connection, and your map of complexes does indeed extend to a map between the Chevalley-Eilenberg and the de Rham complex, but this is not always the case.
This is now why the Weil algebra appears to be a natural concept: What ends up being possible, even when your connection is not flat, is to extend the connection to a map from the Weil algebra to the de Rham complex, by including the curvature of your connection in your considerations: If $W(\mathfrak{g}) = S^\bullet \mathfrak{g}^* \otimes \Lambda^\bullet \mathfrak{g}^*$, then define
$$\zeta: W(\mathfrak{g}) \to \Omega^\bullet(P)$$
by setting for $\alpha \in \mathfrak{g}^*$:
$$\zeta (1 \otimes \alpha) := \omega(\alpha), \quad \zeta (\alpha \otimes 1) := \Omega(\alpha),$$
and extending in a natural, graded manner to all of $W(\mathfrak{g})$.

From this point of view, giving a connection on a principal fibre bundle $P \to M$ is equivalent to giving a morphism $\zeta : W(\mathfrak{g}) \to \Omega^\bullet(P)$ intertwining the $G$-action, cochain differential and insertion of Lie algebra elements/fundamental vector fields on both sides. The paper that inspired me to learn about this, "The cohomology of vector fields on a manifold" by Bott & Segal (Section 3), calls such a $\zeta$ a "morphism of $G$-cochain algebras". The name for this structure in the Greub/Halperin/Vanstone book is "operation of a Lie algebra".
No matter what you call it, I personally find it quite impressive that a simple morphism like this encodes so much geometric information about a bundle. And all it takes to come up with it is the acknowledgment of curvature, and the extension of $C^\bullet_{\text{CE}}(\mathfrak{g})$ to a complex that can deal with curvature. Perhaps this is a standard story to a lot of people, if they are more familiar with this whole Chern-Weil theory business, but I hadn't seen it up until very recently, and found it too cool not to post. :) Okay, I'm done now!


text:
Q: Android Q - Wifi connectionproblem with WifiNetworkSpecifier On Android 10 (Q) I try to connect to a wifi without internet access with WifiNetworkSpecifier.
The first connection work without any problem. After that first connection I can't connect anymore.
Then I have to switch Off/On the wifi network again and than it works one time again.
This problem I have with a Xiaomi Mi 9 SE, with a Samsung Galaxy S10e the error does not exist.
How can I solve this problem, because I can't switch off/on the wifi programmatically on Android Q.
Has anyone a workaround for this problem?
My workaround is to inform the user to do a switch off/on by him self and start a panelIntent. But this is not a fine solution for me.
Here is my code:
On the init():
if (Build.VERSION.SDK_INT >= LOLLIPOP)
{
    NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
    networkRequestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
    networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED);
    networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
    networkRequestBuilder.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);

    if (SDK_INT >= Q)
    {
        WifiNetworkSpecifier.Builder wifiNetworkSpecifierBuilder = new WifiNetworkSpecifier.Builder();
        wifiNetworkSpecifierBuilder.setSsid(ssid);
        wifiNetworkSpecifierBuilder.setWpa2Passphrase(password);

        WifiNetworkSpecifier wifiNetworkSpecifier = wifiNetworkSpecifierBuilder.build();
        networkRequestBuilder.setNetworkSpecifier(wifiNetworkSpecifier);
    }

    networkRequest = networkRequestBuilder.build();
    networkCallback = new NetworkCallback()
    {

        @Override
        public void onAvailable(Network network)
        ...

    };
}

if (SDK_INT < Q)
{...}

... when the thread is running:
@Override
public void run()
{
    NetworkBinding();

    while (runSendThread)
    {...}

    NetworkUnbinding();
}

... and the bindingMethodes:
public void NetworkBinding()
{
    try
    {
        if (SDK_INT >= VERSION_CODES.LOLLIPOP)
        {
            mConManager.requestNetwork(networkRequest, networkCallback);
        }
    }
    catch (Exception e)
    {
        HandleException(e);
    }
}

public void NetworkUnbinding()
{
    try
    {
        if (Build.VERSION.SDK_INT >= VERSION_CODES.M)
        {
            mConManager.bindProcessToNetwork(null);
        }
        if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP)
        {
            mConManager.unregisterNetworkCallback(networkCallback);
            android.net.ConnectivityManager.setProcessDefaultNetwork(null);
        }
    }
    catch (Exception e)
    {
        HandleException(e);
    }
}

A: For others who have similar situations:
I have found out, that the problem was on the router which needed a firmware-update.
I think some newer phones try to find out if the network is ok and if they do not get the right response they mark the network as corrupt.
After the firmware-update, the connections work with every phone.


text:
Q: Do neural networks make assumptions about data and when to use standardization? I was reading about when to use standardization vs normalization and what I could understand was that standardization should be used when the model in use makes some assumptions about the data (I don't know why this assumption). Also I have read that standardization retains the original distribution of data only if it was Gaussian.
Many people on the internet seem to believe that neural nets don't make any assumptions.
Now, I do not see how neural networks don't make any assumptions because-
Few months back I had gone through the derivation of mean squared error function and how for normally distributed error term, MSE is the maximum likelihood estimator. This assumption for error term is stated as assumption for linear regression. So, the assumptions depend on the choice of our cost function, I believe? Wouldn't that mean neural network also make assumptions based on choice of cost function, otherwise the estimates wouldn't be that good?
Also, does it mean that I should standardize when data is normally distributed or distribution doesn't matter?

A: They don't. Moreover, normality is not among core assumptions of linear regression either. It is true that minimizing squared error is equivalent to maximizing Gaussian likelihood, but this doesn't mean that you need to make such assumption when minimizing squared errors. You can use linear regression when the assumption is broken. For linear regression we need the assumption to hold mostly for hypothesis testing and confidence intervals, both are not used, and would be hard to do, in case of neutral networks.

A: This is a common but misleading wording. Models don't make assumptions. People who use them do! For example, when you decide on using a nearest neighbor classifier, you implicitly assume that points which are close are likely to belong to a same class (or, maybe, you have no idea what you're doing and it's pure luck how your model will perform).
So, when you think about using linear regression, you should consider what can be assumed about the data and what do you want your model to capture. If you just want a line through the data that minimizes the sum of square errors, you don't need normality. But, if you want your line at the same time to represent the most likely process which generated the data, then normality, independence, homoskedasticity etc. are an issue.
Regarding data scaling ("standardization"), it's again a question of assumptions and objectives. Imagine a two-dimensional data set, having a large spread along one axis (say, $x$) and a small one along $y$. Whether scaling them to the same span or standardizing them makes sense depends on the underlying cause of the spread. If $x$ is measured in millimeters and $y$ in light years, scaling will likely make sense. On the other hand, if the spread along the $x$-axis is due different classes having distinctively different $x$-values, scaling can lead to an information loss, at least if you use a distance measure-based algorithm, like nearest neighbor.


text:
Q: @Autowired SessionFactory returning null spring in Java configuration I m having null pointer exception in sessionFactory when i try to use DI in sessionFactory I have to turn spring 3 project into Spring 4 with no xml. I dont know what the problem i m facing, SessionFactory doesnot autowired at all. when i try to test case generic doa Add Method
here is my Configuration File for bean
@Configuration
@EnableTransactionManagement
@EnableWebMvc
@ComponentScan(basePackages = "io.github.bibekshakya35.ehealth")
public class EhealthCofiguration {

@Bean
public ViewResolver getViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/view/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

@Bean(name = "dataSource")
public javax.sql.DataSource getDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.postgresql.Driver");
    dataSource.setUrl("jdbc:postgresql://localhost:5432/ehealth");
    dataSource.setUsername("test");
    dataSource.setPassword("test123");
    return dataSource;
}

@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(javax.sql.DataSource dataSource) {
    LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
    sessionBuilder.scanPackages("io.github.bibekshakya35.ehealth.model");
    sessionBuilder.addProperties(getHibernateProperties());
    return sessionBuilder.buildSessionFactory();
}

private Properties getHibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.show_sql", "true");
    properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    properties.put("hibernate.hbm2ddl.auto", "update");
    return properties;
}

@Autowired
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(
        SessionFactory sessionFactory) {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager(
            sessionFactory);

    return transactionManager;
}
}

to load this class i have created
public class EhealthWebAppIntializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.register(EhealthCofiguration.class);
    ServletRegistration.Dynamic dispatcher =servletContext.addServlet("SpringDispatcher", new DispatcherServlet(applicationContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}

}

this is my generic doa class where i m injecting SessionFactory when it try to access sessionFactory.getCurrentSession(); NPE is occur,
@Repository
@Transactional
public class HibernateDAO<T extends Serializable> implements IGenericDao<T> {

private Class<T> clazz;

Session session;

@Autowired
SessionFactory sessionFactory;

private static final Logger LOG = Logger.getLogger(HibernateDAO.class.getName());

@Override
public void setClazz(Class<T> clazzToSet) {
    this.clazz = clazzToSet;
}

@Override
public void create(T entity) {
    session = getCurrentSession();
    LOG.log(Level.INFO, "inside create entity and you just bind your session to the current one{0}", session.toString());
    session.saveOrUpdate(entity);
    LOG.info("saved");
    session.flush();
    session.refresh(entity);
}

protected Session getCurrentSession() {
    return sessionFactory.getCurrentSession();
}
}

Here is my stack trace for NPE
Exception in thread "main" java.lang.NullPointerException
at io.github.bibekshakya35.ehealth.DAO.genericdao.HibernateDAO.getCurrentSession(HibernateDAO.java:115)
at io.github.bibekshakya35.ehealth.DAO.genericdao.HibernateDAO.create(HibernateDAO.java:85)
at io.github.bibekshakya35.ehealth.service.impl.user.main(user.java:46)

here is my user entity
@Entity
@Table(name = "users")
public class User implements Serializable, AbstractEntity {

@Id
@Column(name = "username",unique = true)
private String userName;

@NotNull(message = "password cannot be empty")
@Column(name = "users_password")
private String userPassword;

@Embedded
private UserProfile userProfile;

@Embedded
private AuditInfo auditInfo;

@Enumerated(EnumType.STRING)
private UserType userType;

@Column(name = "is_active")
private boolean active = true;

//getter n setter

}

A: In chat, You provided me with this code :
 public static void main(String[] args) {
     User user = new User();
     IGenericDao<User> iGenericDao = new HibernateDAO<>();
     user.setUserName("bibekshakya35");
     user.setUserPassword("ros3");
     user.setUserType(UserType.GUEST);
     user.setActive(true);
     UserProfile userProfile = new UserProfile();
     userProfile.setAge(21);
     userProfile.setBasicInfo("kdhsa");
     userProfile.setEmailId("dsadas@gmail.com");
     userProfile.setUserGender(UserGender.Male);
     userProfile.setFullname("bibek shakya");
     userProfile.setMobileNumber("45454545");
     userProfile.setLandLineNumber("445444");
     userProfile.setUserProfilePic("index.jsp");
     user.setUserProfile(userProfile);
     AuditInfo auditInfo = new AuditInfo();
     auditInfo.setCreatedOn(new Date());
     auditInfo.setModifiedOn(new Date());
     auditInfo.setVerifiedOn(new Date());
     user.setAuditInfo(auditInfo);
     iGenericDao.create(user);
   }

Cause of error:
As You are creating the new HibernateDAO instance like this IGenericDao<User> iGenericDao = new HibernateDAO<>(); This is creating the problem.

In the case where You are using annotations, creating new instance manually ,usually causes the above mentioned error.
 Reason of error:
Spring can only autowire beans that it manages; if you call new to create a bean yourself, @Autowired fields don't get filled in (and methods like @PostConstruct aren't called).
Solution:
You need to add @autowired to the HibernateDAO which will instantiate it with the exact class which includes the real @Autowired SessionFactory.
Example:
Usually we do it in the class which is itself annotated with annotations like @Controller or @Service.
Like this
@Controller
@RequestMapping(value="/someURL")
public class mainClass {
    @Autowired
    HibernateDAO abc;
    //Code (methods) to test Your CRUD Operations
}


text:
Q: R - dblyr optionaly filter I load data from database this way.
dt <-
  data.frame(
    id = seq(1, 100, 1)
  )

getdt <-
  tb("db", "table") %>%
  filter(id %in% !!dt$id) %>%
  collect()

Sometimes could happen that dt object is not present at all. Is it possible to call query without this ugly if else? I'd like to keep only simple select above.
if (exists("dt")) {
  getdt <-
    tb("db", "table") %>%
    filter(id %in% !!dt$id) %>%
    collect()
} else {
  getdt <-
    tb("db", "table") %>%
    collect()
}

A: Assuming your code breaks if dt is not available, you can use try catch:

tryCatch({
    getdt <-
    tb("db", "table") %>%
    filter(id %in% !!dt$id) %>%
    collect()

}, error = function(e) {
     getdt <-
    tb("db", "table") %>%
    collect()
}


text:
Q: Run a JS Userscript through Tampermonkey on a Chrome Extension I have a working JS Userscript intended for running an action when clicking on any word in a webpage.  This works fine when installed either with Greasemonkey in Firefox or Tampermonkey in Chrome on all webpages.
However, I would like for the script to be able to be run (or perhaps have access to run) on a Chrome Extension, specifically the open-source EPUB reader Readium.  This is a type of Chrome extension that installs with an icon, and opens up a new tab with a URL starting with "chrome-extension://...".
Userscripts have the ability to include and exclude websites with a set of tags at the top of the page, and I've attempted to include all websites, all sites beginning with :chrome-extension", all anything, etc., and not only is the code not working, Tampermonkey is not showing that the script is running and the console is not logging any test examples.
So my question is, is there any way to run Chrome Extension/app A, downloaded from the Chrome store, and have Userscript B, running through Tampermonkey, inject JS code into the chrome extension A?


text:
Q: What encoding are Ruby Strings in? Is it true that Ruby Strings are just a sequence of Unicode characters? If so, what specific encoding e.g. is it UTF-8, etc.?

A: The default encoding of a String is the same as the source file.
The default encoding of the source file is UTF-8 in Ruby 2.0 or later, or US-ASCII in Ruby 1.9 or earlier. You can specify the encoding by adding
# encoding: utf-8

in the beginning of a source file.

A: By default, Ruby strings are indeed UTF-8, as can be verified by the String#encoding method:
llama@llama:~$ irb
irb(main):001:0> 'foo'.encoding
=> #<Encoding:UTF-8>

You can get a list of available encodings via Encoding::list:
irb(main):002:0> Encoding.list
=> [#<Encoding:ASCII-8BIT>, #<Encoding:UTF-8>, #<Encoding:US-ASCII>, (etc...)]

And change the encoding of a string with String#force_encoding:
irb(main):003:0> 'foo'.force_encoding(Encoding::US_ASCII).encoding
=> #<Encoding:US-ASCII>


text:
Q: ESLint: Unsafe assignment of an `any` value with @react-google-maps/api and TypeSscript I'm implementing a draggable marker with @react-google-maps/api, so I create a controllable state using useState. However, when I create a handleMarkerDrag function, TypeScript complains about the any type, despite all params and returns being typed. Please advise.
...
const [markerLoc, setMarkerLoc] = useState({
    lat: 40.730155,
    lng: -74.00451,
});

const handleMarkerDrag = (e: google.maps.MapMouseEvent) => {
    const lat: number = e.latLng!.lat();
    const lng: number = e.latLng!.lng();
    setMarkerLoc({ lat, lng });
  };
...

The errors thrown:


text:
Q: Iterate members of a bitfield We have this example:
struct X {
  int e0 : 6;
  int e1 : 6;
  int e2 : 6;
  ...
  int e10 : 6;
};

struct X c;

How can I access the members "automatically", something like that:
c.e{0-10} ?
Say if I want to read c.e0, then c.e1 ...
If my struct would have 1000 elements, I do not think that I should write so much code, right ?
Can you help me with a workaround, an idea ?
I mention that I already read other posts related somehow to this problem, but I did not find a solution.
Thank you very much !

A: As others have said, you cannot do exactly what you want with bit fields. It looks like you want to store a large number of 6 bit integers with maximum space efficiency. I will not argue whether this is a good idea or not. Instead I will present an old-school C like way of doing exactly that, using C++ features for encapsulation (untested). The idea is that 4 6 bit integers require 24 bits, or 3 characters.
// In each group of 3 chars store 4 6 bit ints
const int nbr_elements = 1000;
struct X
{
    // 1,2,3 or 4 elements require 3 chars, 5,6,7,8 require 6 chars etc.
    char[ 3*((nbr_elements-1)/4) + 3 ] storage;
    int get( int idx );
};

int X::get( int idx )
{
    int dat;
    int offset = 3*(idx/4);      // eg idx=0,1,2,3 -> 0 idx=4,5,6,7 -> 3 etc.
    char a = storage[offset++];
    char b = storage[offset++];
    char c = storage[offset];
    switch( idx%4)  // bits lie like this; 00000011:11112222:22333333
    {
        case 0: dat = (a>>2)&0x3f;                    break;
        case 1: dat = ((a<<4)&0x30) + ((b>>4)&0x0f);  break;
        case 2: dat = ((b<<2)&0x3c) + ((c>>6)&0x03);  break;
        case 3: dat = c&0x3f;                         break;
    }
    return dat;
}

I will leave the companion put() function as an exercise.

A: It sounds like a struct isn't the right tool for what you're trying to do.  You need either an array or a vector.  Arrays are used for storing a number of the same type of data.  Vectors are array wrappers that manage the addition and removal of items automatically.
If you need a list of the same data, and some other data (say a string) you can make an array or a vector part of your struct.
struct X {
   int[10] numbs;
   string name;
};

X c;

A: You can't. To do this would require some form of reflection, which is not supported in either C or C++.

A: How about something like this:
char getByte(char *startPos, int index) {

    int i = (index*6) / 8;

    if (index % 4 == 0)
        return 0b11111100 & startPos[i] >> 2;
    else if (index % 4 == 3)
        return 0b00111111 & startPos[i];
    else if (index % 4 == 2)
        return (0b00001111 & startPos[i] << 2) | (0b11000000 & startPos[i+1] >> 6);
    else
        return (0b00000011 & startPos[i] << 4) | (0b11110000 & startPos[i+1] >> 4);
}

A: Since your bitfields are of the same size, you could encapsulate std::bitset (or vector<bool>, gulp...) and provide your own iterators (each increment moving the bookmark six bits) and operator[] (etc) to allow your code to be more simple to write.
I am sure performance would suck compared to the bitfields though.


text:
Q: postgresql xpath explode one row into N Word of notice: I'm completely new to xml data type and methods in Postresql.
I have a table, one single row, one single column, with this content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Major Version</key><integer>1</integer>
    <key>Minor Version</key><integer>1</integer>
    <key>Date</key><date>2022-07-20T15:03:30Z</date>
    <key>Application Version</key><string>11.1.5</string>
    <key>Features</key><integer>5</integer>
    <key>Show Content Ratings</key><true/>
    <key>Music Folder</key><string>file://localhost/C:/Users/user/Music/iTunes/iTunes%20Media/</string>
    <key>Library Persistent ID</key><string>23CE8FD285020EA7</string>
    <key>Tracks</key>
    <dict>
        <key>2517</key>
        <dict>
            <key>Track ID</key><integer>2517</integer>
            <key>Name</key><string>Your Sweet Six Six Six</string>
            <key>Artist</key><string>HIM</string>
            <key>Album</key><string>Greatest Lovesongs Vol. 666 </string>
        </dict>
        <key>2519</key>
        <dict>
            <key>Track ID</key><integer>2519</integer>
            <key>Name</key><string>Wicked Game</string>
            <key>Artist</key><string>HIM</string>
            <key>Album</key><string>Greatest Lovesongs Vol. 666 </string>
        </dict>
    </dict>
    <key>Playlists</key>
    <array>
        <dict>
            <key>Name</key><string>Library</string>
            <key>Master</key><true/>
            <key>Playlist ID</key><integer>52895</integer>
            <key>Playlist Persistent ID</key><string>37B8BC84B0503164</string>
            <key>Visible</key><false/>
            <key>All Items</key><true/>
            <key>Playlist Items</key>
            <array>
                <dict>
                    <key>Track ID</key><integer>2517</integer>
                    <key>Track ID</key><integer>2519</integer>
                </dict>
            </array>
        </dict>
    </array>
</dict>
</plist>

Sorry for the extension, but for the sake of completeness.
I'd like to extract, in a SELECT, from that single row containing all that xml in a xml data type, the following content:
+------------------------+--------+-----------------------------+
|          Name          | Artist |            Album            |
+------------------------+--------+-----------------------------+
| Your Sweet Six Six Six | HIM    | Greatest Lovesongs Vol. 666 |
| Wicked Game            | HIM    | Greatest Lovesongs Vol. 666 |
+------------------------+--------+-----------------------------+

Any idea how can I achieve it?
Thanks so much!

A: Quite tricky XML to parse. Assuming that the order of the keys Name, Artist and Album never change, the following query might help you:
SELECT
 (xpath('/dict[key/text()="Name"]/string/text()',j))[1],
 (xpath('/dict[key/text()="Name"]/string/text()',j))[2],
 (xpath('/dict[key/text()="Name"]/string/text()',j))[3]
FROM mytable
CROSS JOIN LATERAL unnest((xpath('//dict/dict/dict',xmlcol))) j;


text:
Q: How to pass an array in formData I am using formData and trying to pass an array that receives it in .Net Core backend
this is my array that i try to send truck.StateTruck:
{
  0: {StaId: 6}
  1: {StaId: 7}
  2: {StaId: 8}
  3: {StaId: 9}
}

this is my method to send my data that I try to send only the StaId and its value:
let formData = new FormData();
formData.set('DriId',truck.DriId);
formData.set('TruExdate',truck.TruExdate);
formData.set('TruAddress',truck.TruAddress);
formData.set('TruCity',truck.TruCity);
formData.set('TraId',truck.TraId);
formData.set('TruZip',truck.TruZip);
formData.set('TruYear',truck.TruYear);
formData.set('TruMake',truck.TruMake);
formData.set('TruType',truck.TruType);
formData.set('TruFuel',truck.TruFuel);
formData.set('TruAxles',truck.TruAxles);
formData.set('TruVin',truck.TruVin);
formData.set('TruDocurl',truck.TruDocurl);
formData.set('TraUnit',truck.TraUnit);
formData.set('TraMake',truck.TraMake);
formData.set('TraYear',truck.TraYear);
formData.set('TtyId',truck.TtyId);
formData.set('TraIntmaterial',truck.TraIntmaterial);
formData.set('TraEquipament',truck.TraEquipament);
formData.set('TraOption',truck.TraOption);
formData.set('Fichero',truck.Fichero);
formData.append('StateTruck',JSON.stringify(truck.StateTruck));

when printing to the console using the console.log (formData.getAll ('StateTruck')); I see
["[{"StaId":6},{"StaId":7},{"StaId":8},{"StaId":9}]"]

and my backend expects this structure:
public class TruckRequest
    {
        public int TruId { get; set; }
        public int? DriId { get; set; }
        public DateTime? TruExdate { get; set; }
        public string TruAddress { get; set; }
        public string TruCity { get; set; }
        public int? TraId { get; set; }
        public string TruZip { get; set; }
        public string TruYear { get; set; }
        public string TruMake { get; set; }
        public string TruType { get; set; }
        public string TruFuel { get; set; }
        public string TruAxles { get; set; }
        public string TruVin { get; set; }
        public string TruDocurl { get; set; }

        public string TraUnit { get; set; }
        public string TraMake { get; set; }
        public string TraYear { get; set; }
        public int? TtyId { get; set; }
        public string TraIntmaterial { get; set; }
        public string TraEquipament { get; set; }
        public string TraOption { get; set; }

        public IFormFile Fichero { get; set; }
        public string TruUregistro { get; set; }
        public DateTime? TruUfecha { get; set; }
        public string TruUupdate { get; set; }
        public DateTime? TruUupdatefecha { get; set; }
        public string TruEstado { get; set; }

        public virtual ICollection<StateTruck> StateTruck { get; set; }
}

public partial class StateTruck
{
    public int SruId { get; set; }
    public int? StaId { get; set; }
    public string SruUregistro { get; set; }
    public DateTime? SruUfecha { get; set; }
    public string SruUupdate { get; set; }
    public DateTime? SruUupdatefecha { get; set; }
    public string SruEstado { get; set; }
    public int? TruId { get; set; }

}

How can I give it the correct format so that it can be received?

A: if you need the value converted to string, you may use
e.g.
formData.set('TruYear', truck.TruYear.toString());

for integer, e.g.
formData.set('TruYear', parseInt(truck.TruYear));

All these are passed as formData to your backend, your server should create the parser to convert to the right format, and to validate it is the right format.
Never, trust, anything submitted from frontend.

A: When console logging out the data you need to parse the first element in the array received from formData.getAll ('StateTruck'). The following should help in your scenario:
console.log(JSON.parse(formData.getAll("StateTruck")[0]))

A: According to your description, I assume you want to use FormData to pass value (include the object array) from client side to server side (Web API). If that is the case, you could refer to the following sample code:
Client side (using JQuery Ajax to call the web API method):
    $(function () {
        //Submit Main Form.
        $("#btnCreate").click(function (event) {
            //Prevent Default Region.
            event.preventDefault();
            //define an array to store the StateTruck
            var statetruce = new Array();

            for (var i = 0; i < 5; i++) {

                statetruce.push({ StaId: i });
            }

            let formData = new FormData();
            formData.set('DriId', 101);
            formData.set('TruAddress', "Address 1");
            formData.set('TruCity', "city A");
            formData.set('TraId', 1011);
            formData.set('TruZip', "zip12");
            formData.set('TruYear', "years ");
            formData.append('StateTruck', JSON.stringify(statetruce));
            $.ajax({
                url: '/api/TestAPI',
                type: "post",
                async: true,
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    // window.location.href = response;
                }
            });
        });
    });

Based on the Array Object's property to create a View Model, it is used to Deserialize the  array object.
Code in the Web API method:
    [HttpPost]
    public async Task<IActionResult> Post(IFormCollection collection)
    {

        var DriId = collection["DriId"].ToString();
        var TruAddress = collection["TruAddress"].ToString();

        var StateTruck = collection["StateTruck"].ToString();
        //deserialize the object
        var result = System.Text.Json.JsonSerializer.Deserialize<List<StateTruckViewModel>>(StateTruck);

        //do something
        return Ok("success");
    }

Then debug screenshot as below:


text:
Q: Why does OutputStream returned by DriveContents.getOutputStream() not act as expected? I have been playing with Google Drive API for Android and I have stumbled across a bit of a problem. In particula I am interested in App Folder fro saving and synchronizing app data across devices.
I can query if a file with certain filename exists in app folder.
I can get file via
driveFile = metadata.getDriveId().asDriveFile();

I can open file via
driveFile.open( mGoogleApiClient,
                DriveFile.MODE_WRITE_ONLY,
                new DownloadProgressListener() {...} )
.setResultCallback(...);

And in the later callback I can get OutputStream with:
OutputStream outputStream = dcr.getDriveContents().getOutputStream();

But the problem is that if I try to write to that OutpustStream nothing is written to file. I have used code like that:
OutputStream outputStream = result.getDriveContents().getOutputStream();
OutputStreamWriter writer = new      OutputStreamWriter(outputStream);
try {
    writer.write("Just some strinh I want to save to Google Drive.");
} catch (IOException e) {
    throw new RuntimeException(e);
}
Status status = dcr.getDriveContents().commit(mGoogleApiClient, null).await();

Using this OutputStream nothing is ever written to GoogleDrive. But if I use code from https://developers.google.com/drive/android/files#making_modifications it works as expected.
A copied snippet of that code from google for reference:
try {
    ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();

    FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
        .getFileDescriptor());
    Writer writer = new OutputStreamWriter(fileOutputStream);
    writer.write("hello world");
} catch (IOException e) {
    e.printStackTrace();
}

Why does OutputStream accesible by DriveContents.getOutputStream() not work as expected? Why is it even provided? Or am I missing something?
Version of Google Play Services Library is r29.

A: Close the OutputStreamWriter - writer.close() to commit the output.


text:
Q: How can I fix 'integrity constraint (PROD_SUP_FK) violated - parent key not found'? I did this
INSERT INTO product (prod_id, prod_price, prod_avail, prod_mdate, prod_edate, cust_id, sto_id, sup_id)
Values('RBL01001',4.50,'Available',TO_DATE('29-MAR-21','DD-MON-YY'),TO_DATE('29-APR-21','DD-MON-YY'),0001,'Kapar1','SUPP-001');

and this is the result

ORA-02291: integrity constraint (PROD_SUP_FK) violated - parent key not found

ORA-02291: integrity constraint (PROD_SUP_FK) violated - parent key not found

ORA-06512: at "SYS.DBMS_SQL", line 1721

INSERT INTO product (prod_id, prod_price, prod_avail, prod_mdate, prod_edate, cust_id, sto_id, sup_id)
Values('RBL01001',4.50,'Available',TO_DATE('29-MAR-21','DD-MON-YY'),TO_DATE('29-APR-21','DD-MON-YY'),0001,'Kapar1','SUPP-001');

Table product
CREATE TABLE product
 (
   prod_id      VARCHAR2 (10) CONSTRAINT prod_id_nn NOT NULL ENABLE,
   prod_price   NUMBER (3, 2) CONSTRAINT prod_price_nn NOT NULL ENABLE,
   prod_avail   VARCHAR2 (20) CONSTRAINT prod_avail_nn NOT NULL ENABLE,
   prod_mdate   DATE CONSTRAINT prod_mdate_nn NOT NULL ENABLE,
   prod_edate   DATE CONSTRAINT prod_edate_nn NOT NULL ENABLE,
   cust_id      NUMBER (4, 0),
   sto_id       VARCHAR (8) CONSTRAINT sto_id_nn NOT NULL ENABLE,
   sup_id       VARCHAR (10),
   CONSTRAINT prod_id_pk PRIMARY KEY (prod_id) USING INDEX ENABLE,
   CONSTRAINT prod_date_interval CHECK (prod_edate > prod_mdate) ENABLE
 );

table supplier
CREATE TABLE  supplier
(
  sup_id VARCHAR2(10) CONSTRAINT sup_id_nn NOT NULL ENABLE,
  sup_name VARCHAR2(500) CONSTRAINT sup_name_NN NOT NULL ENABLE,
  sup_add VARCHAR2(500) CONSTRAINT sup_add_nn NOT NULL ENABLE,
  CONSTRAINT sup_id_pk PRIMARY KEY (sup_id) USING INDEX  ENABLE
);

Alter table product
ALTER TABLE  product ADD CONSTRAINT prod_cust_fk FOREIGN KEY (cust_id)
        REFERENCES  customer (cust_id) ENABLE;
ALTER TABLE  product ADD CONSTRAINT prod_sto_fk FOREIGN KEY (sto_id)
        REFERENCES  bakery / store (sto_id) ENABLE;
ALTER TABLE  product ADD CONSTRAINT prod_sup_fk FOREIGN KEY (sup_id)
        REFERENCES  supplier (sup_id) ENABLE;

CREATE INDEX  prod_cust_ix ON  product (cust_id);
CREATE INDEX  prod_sto_ix ON  product (sto_id);
CREATE INDEX  prod_sup_ix ON  product (sup_id);

using Oracle APEX 21.2.0

A: First you have to insert rows into "master" tables (customer, supplier, bakery/store), then into their "child" table (product).

By the way, what is this bakery / store thing supposed to do? Such a syntax is invalid:
ALTER TABLE  product ADD CONSTRAINT prod_sto_fk FOREIGN KEY (sto_id)
    REFERENCES  bakery / store (sto_id) ENABLE;
                --------------
                this


text:
Q: Any way to batch resize png's canvas size keeping the image top left, but making the size divisible by 12 We need to have huge amounts of png's resized to be divisible by 12, each png is variable in size and the image needs to stay 1:1 in the top left.
At the moment were having to manually bring in each file into Photoshop and enlarge the canvas on the x+y to be divisible by 12 and keep the image in the top left corner. With the amount of png's we need doing now and in future we need an automated process.

A: I would do this with ImageMagick, which is free and installed on most Linux distros and also available for OSX and Windows from here.
This little bash script will resize all the PNG files in the current directory and save them with the original name in the subdirectory called output. It is pretty easy to read - it basically loops through all the PNG files in the directory. It then uses ImageMagick's built-in calculator to work out the size of your output file as nearest multiple of 12. Then it loads the image and extends the background using transparent pixels (-background none) to that size (using -extent) and leaves the original image in the top-left corner (-gravity NorthWest).
#!/bin/bash
# Make output directory - ignore errors
mkdir output 2> /dev/null

# Make sure we don't barf if there are no files
shopt -s nullglob

# Make sure we process *.png, *.PNG, *.pNg etc
shopt -s nocaseglob

# Loop through all pngs in current directory
for f in *.png; do

    # Calculate new extent as nearest multiple of 12
    # In general, to round x to nearest n, you do ((x+n-1)/n)*n
    extent=$(convert "$f" -format "%[fx:12*round(((w+11)/12)-0.5)]x%[fx:12*round(((h+11)/12)-0.5)]" info: )

    # Now extend canvas transparently to new size and leave original image in top-left
    convert "$f" -background none -gravity northwest -extent $extent output/"$f"
done

P.S. If installing ImageMagick on OSX, please ask for advice before trying.
P.P.S. If you have 10,000+ images to resize, and you do it often, and you are on OSX or Linux (probably not Windows), I would recommend GNU Parallel. If that is likely, please ask.

A: Never mind, this is a possible solution for your problem. This script will run in MATLAB or Octave (Octave is an open-source alternative to MATLAB, so you might want to use that.)
Copy the following function into a file and call it resizeIm.m. Then start Octave and call this function for every image you have.
function resizeIm(fileName)
    % Read image
    origIm = imread(fileName);

    % Get size and calculate new size
    origSize = size(origIm);
    div = ceil(origSize ./ 12);

    % Create new, padded image
    newIm = zeros(12*div,class(origIm));
    newIm(1:origSize(1),1:origSize(2)) = origIm;

    % Write image to new file
    [dir, name, ext] = fileparts(fileName);
    newFileName = [dir,name,"_resized",ext];
    imwrite(newIm,newFileName);
end

The function can be called by
resizeIm("C:\path\to\file\myimage.png")


text:
Q: jQuery rounded corners with border in IE I have a problem with my website in IE8 (6 and 7 also I guess).
My main div has rounded corners. I did that with jQuery.corners - this works fine in Firefox en also IE!
The problem is: in IE I don't see the (white) borders... Does someone know why? Or is it nog supported?
The site is: http://77.243.237.196/~ksaatom/newsite
It would be great if the border would work! Thanks in advance!

A: Try using the LiquidCanvas jQuery plugin instead.  It is a fully cross-browser (IE6/7/8, FF, etc) library that lets you do rounded-corners and borders.  I've had similar problems with jQuery Corners in IE, but everything's worked for me since I switched to it.
There is a write-up on how to use it for both corners and borders at http://www.caffeinedi.com/2009/11/02/using-jquery-and-liquidcanvas-to-add-drop-shadows-borders-rounded-corners-and-other-effects-to-your-website-even-in-ie6-and-ie7/

A: Curvycorners is my favorite rounded corner plug-in so far.  It gracefully degrades if the browser natively supports rounding corners (most modern browsers can do this through CSS).
Another huge bonus is there is no JavaScript required (except for including a reference to the curvycorner file itself).  All you have to do is add the appropriate CSS to your element and if it's not natively supported to do it automatically then curvycorners steps in.


text:
Q: Падает приложение на андроид телефоне, Unity/ Unity.
Сбилдил апку для Андроид телефона (Meizy m6 note 7.1 Android)
Устанавливаю на телефоне
Запускаю на телефоне.
Падает через 10 секунд.
Логи вот:
03-04 02:10:09.915 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.915 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.915 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.915 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.915 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.915 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.915 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.915 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.915 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.915 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.915 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.915 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.915 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : The referenced script on this Behaviour (Game Object '<null>') is missing!
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.916 18468 18556 W Unity   : (Filename: /Users/builduser/buildslave/unity/build/Runtime/Mono/MonoBehaviour.cpp Line: 1758)
03-04 02:10:09.916 18468 18556 W Unity   :
03-04 02:10:09.932 18468 18556 F libc    : Fatal signal 11 (SIGSEGV), code 1, fault addr 0xe5219970 in tid 18556 (UnityPreload)
03-04 02:10:09.933 10102 10102 W         : debuggerd: handling request: pid=18468 uid=10163 gid=10163 tid=18556
03-04 02:10:10.125 18566 18566 F DEBUG   : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
03-04 02:10:10.125 18566 18566 F DEBUG   : Build fingerprint: 'Meizu/meizu_M6Note/M6Note:7.1.2/N2G47H/m1721.Flyme_6.0.1511941566:user/release-keys'
03-04 02:10:10.126 18566 18566 F DEBUG   : Revision: '0'
03-04 02:10:10.126 18566 18566 F DEBUG   : ABI: 'arm'
03-04 02:10:10.126 18566 18566 F DEBUG   : pid: 18468, tid: 18556, name: UnityPreload  >>> ru.ninbous.game <<<
03-04 02:10:10.126 18566 18566 F DEBUG   : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0xe5219970
03-04 02:10:10.126 18566 18566 F DEBUG   :     r0 e52199c8  r1 00000400  r2 000000ff  r3 00000000
03-04 02:10:10.126 18566 18566 F DEBUG   :     r4 cc6f3010  r5 00000004  r6 cc6f3010  r7 00000004
03-04 02:10:10.127 18566 18566 F DEBUG   :     r8 00000144  r9 00000010  sl e5236ea4  fp 6b839cb4
03-04 02:10:10.127 18566 18566 F DEBUG   :     ip d703de2c  sp e5219968  lr d61871ac  pc d6185ccc  cpsr 80010010
03-04 02:10:10.215 18566 18566 F DEBUG   :
03-04 02:10:10.215 18566 18566 F DEBUG   : backtrace:
03-04 02:10:10.216 18566 18566 F DEBUG   :     #00 pc 00822ccc  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_Z34construct_block_size_descriptor_2diiP21block_size_descriptor+44)
03-04 02:10:10.216 18566 18566 F DEBUG   :     #01 pc 008241a8  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_Z25get_block_size_descriptoriii+92)
03-04 02:10:10.216 18566 18566 F DEBUG   :     #02 pc 00827f50  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_Z20physical_to_symboliciii25physical_compressed_blockP25symbolic_compressed_block+80)
03-04 02:10:10.216 18566 18566 F DEBUG   :     #03 pc 003fdbdc  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZL14DecompressASTCPKjiiiiPjii+292)
03-04 02:10:10.216 18566 18566 F DEBUG   :     #04 pc 003fc524  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_Z29DecompressNativeTextureFormat13TextureFormatS_iiPKjiiPj+448)
03-04 02:10:10.216 18566 18566 F DEBUG   :     #05 pc 003f0edc  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZNK9Texture2D11GetPixels32EiP11ColorRGBA32i+1264)
03-04 02:10:10.216 18566 18566 F DEBUG   :     #06 pc 00d12ee4  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZN13SplatDatabase18RecalculateBasemapEb+1892)
03-04 02:10:10.216 18566 18566 F DEBUG   :     #07 pc 00d169e4  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZN11TerrainData21AwakeFromLoadThreadedEv+20)
03-04 02:10:10.217 18566 18566 F DEBUG   :     #08 pc 007fdbac  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZN17PersistentManager23PostReadActivationQueueEiPK8TypeTreeb+144)
03-04 02:10:10.217 18566 18566 F DEBUG   :     #09 pc 007fe798  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZN17PersistentManager29ReadAndActivateObjectThreadedEiRK26SerializedObjectIdentifierP14SerializedFilebb+236)
03-04 02:10:10.217 18566 18566 F DEBUG   :     #10 pc 007ff030  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZN17PersistentManager26LoadFileCompletelyThreadedERKN4core12basic_stringIcNS0_20StringStorageDefaultIcEEEEPxPiibR12LoadProgress+904)
03-04 02:10:10.217 18566 18566 F DEBUG   :     #11 pc 005ba9a0  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZN18LoadSceneOperation7PerformEv+1476)
03-04 02:10:10.217 18566 18566 F DEBUG   :     #12 pc 005bc748  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZN14PreloadManager22ProcessSingleOperationEv+124)
03-04 02:10:10.217 18566 18566 F DEBUG   :     #13 pc 005bc550  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZN14PreloadManager3RunEv+104)
03-04 02:10:10.217 18566 18566 F DEBUG   :     #14 pc 005bc3ec  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZN14PreloadManager3RunEPv+44)
03-04 02:10:10.217 18566 18566 F DEBUG   :     #15 pc 0063c8b8  /data/app/ru.ninbous.game-1/lib/arm/libunity.so (_ZN6Thread16RunThreadWrapperEPv+84)
03-04 02:10:10.217 18566 18566 F DEBUG   :     #16 pc 00046fe3  /system/lib/libc.so (_ZL15__pthread_startPv+22)
03-04 02:10:10.217 18566 18566 F DEBUG   :     #17 pc 00019ced  /system/lib/libc.so (__start_thread+6)
03-04 02:10:10.289   751   751 I zygoteRunOnce: runOnce 00
03-04 02:10:10.289   751   751 I zygoteRunOnce: forkAndSpecialize 00  niceName:com.qualcomm.telephony
03-04 02:10:10.291   751   751 I Zygote  : ForkAndSpecializeCommon: Begin to fork a new process
03-04 02:10:10.305   751   751 I Zygote  : ForkAndSpecializeCommon: fork is finished, pid=18568
03-04 02:10:10.305 18568 18568 I Zygote  : ForkAndSpecializeCommon: fork is finished, pid=0
03-04 02:10:10.306 18568 18568 W Zygote  : mz_is_rooted false
03-04 02:10:10.308   751   751 I zygoteRunOnce: forkAndSpecialize 01 pid:18568
03-04 02:10:10.308   751   751 I zygoteRunOnce: parent closeQuietly before
03-04 02:10:10.308   751   751 I zygoteRunOnce: handleParentProc before
03-04 02:10:10.308   751   751 I zygoteRunOnce: handleParentProc 00 pid:18568
03-04 02:10:10.308   751   751 I zygoteRunOnce: handleParentProc 01
03-04 02:10:10.308   751   751 I zygoteRunOnce: handleParentProc 02
03-04 02:10:10.308   751   751 I zygoteRunOnce: handleParentProc 05
03-04 02:10:10.308   751   751 I zygoteRunOnce: handleParentProc 15 pid:18568
03-04 02:10:10.308 18568 18568 I Zygote  : ForkAndSpecializeCommon: Beginning of SetGids
03-04 02:10:10.309 18568 18568 I Zygote  : ForkAndSpecializeCommon: End of SetGids
03-04 02:10:10.309   751   751 I zygoteRunOnce: handleParentProc 16 usingWrapper:false
03-04 02:10:10.309   751   751 I zygoteRunOnce: handleParentProc 17
03-04 02:10:10.309   751   751 I zygoteRunOnce: handleParentProc end
03-04 02:10:10.309  1547  1607 I ActivityManager: Start proc 18568:com.qualcomm.telephony/1000 for service com.qualcomm.simcontacts/.SimContactsService
03-04 02:10:10.317 18568 18568 I zygoteRunOnce: forkAndSpecialize 01 pid:0
03-04 02:10:10.317 18568 18568 I zygoteRunOnce: child closeQuietly before
03-04 02:10:10.317 18568 18568 I zygoteRunOnce: handleChildProc before
03-04 02:10:10.336 18568 18568 I art     : IsDexFileNeededDisableVerify for /system/app/SimContacts/SimContacts.apk
03-04 02:10:10.336 18568 18568 I art     : Do disableVerify for /system/app/SimContacts/SimContacts.apk
03-04 02:10:10.342 18568 18568 W System  : ClassLoader referenced unknown path: /system/app/SimContacts/lib/arm64
03-04 02:10:10.479  1547  2403 E ConnectivityService: getActiveNetworkInfo callingUid = 10065
03-04 02:10:10.489 18224 18243 W Settings: Setting android_id has moved from android.provider.Settings.System to android.provider.Settings.Secure, returning read-only value.
03-04 02:10:10.492  1547  7528 E ConnectivityService: getActiveNetworkInfo callingUid = 10065
03-04 02:10:10.624   735 18028 I [GF_HAL][gf_hal_milan_an_series]: [gf_log_level] ret = 0, g_hal_log_level_flag = 0
03-04 02:10:10.624   735 18028 I [GF_HAL][gf_hal_common]: [gf_debug_info_flag] ret = 0, g_debug_info_flag = 0
03-04 02:10:10.655 18042 18250 I QQPimSecure: wup request: 1
03-04 02:10:10.666  1547  7428 E ConnectivityService: getActiveNetworkInfo callingUid = 1000
03-04 02:10:10.691  1547  2879 E ConnectivityService: getActiveNetworkInfo callingUid = 1000
03-04 02:10:10.693   586   586 E SELinux : avc:  denied  { find } for service=netd_listener pid=795 uid=0 scontext=u:r:netd:s0 tcontext=u:object_r:netd_service:s0 tclass=service_manager permissive=0
03-04 02:10:10.715   795 18585 W DnsProxyListener: Netd event listener is not available; skipping.
03-04 02:10:10.717 18042 18250 I DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
03-04 02:10:10.719 18042 18250 I HttpConnection: initConnection() openTimeMillis: 4
03-04 02:10:10.724   586   586 E SELinux : avc:  denied  { find } for service=netd_listener pid=795 uid=0 scontext=u:r:netd:s0 tcontext=u:object_r:netd_service:s0 tclass=service_manager permissive=0
03-04 02:10:10.990 18042 18250 I HttpConnection: sendRequest() connectTimeMillis: 269
03-04 02:10:11.066   753  1083 I AudioFlinger: BUFFER TIMEOUT: remove(4096) from active list on thread 0xe7c03f40
03-04 02:10:11.273 18042 18250 I ThreadPool: shrink core pool size: 0
03-04 02:10:11.419 17428 17634 I EventLogSendingHelper: Sending log events.
03-04 02:10:11.562 17428 17428 I MemoryTrimmer: Trimming objects from memory, since app is in the background.
03-04 02:10:11.739  1547 10899 I ActivityManager: Process com.meizu.net.search (pid 18334) has died
03-04 02:10:11.744  1547  1547 I OpenGLRenderer: SignalingRenderTask signal:0x7fa18552c0
03-04 02:10:11.744 17990 17990 I SafeApplication: onTrimMemory(15) foreground : false
03-04 02:10:11.744  1547  1547 I OpenGLRenderer: SignalingRenderTask signal:0x7fa18552c0
03-04 02:10:12.417  1547  7529 E ConnectivityService: getActiveNetworkInfo callingUid = 10051
03-04 02:10:12.429  1547  2931 E ConnectivityService: getActiveNetworkInfo callingUid = 10051
03-04 02:10:12.449 18421 18589 I DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
03-04 02:10:12.456   586   586 E SELinux : avc:  denied  { find } for service=netd_listener pid=795 uid=0 scontext=u:r:netd:s0 tcontext=u:object_r:netd_service:s0 tclass=service_manager permissive=0
03-04 02:10:12.481   795 18592 W DnsProxyListener: Netd event listener is not available; skipping.
03-04 02:10:12.485   586   586 E SELinux : avc:  denied  { find } for service=netd_listener pid=795 uid=0 scontext=u:r:netd:s0 tcontext=u:object_r:netd_service:s0 tclass=service_manager permissive=0
03-04 02:10:12.624   735 18028 I [GF_HAL][gf_hal_milan_an_series]: [gf_log_level] ret = 0, g_hal_log_level_flag = 0
03-04 02:10:12.624   735 18028 I [GF_HAL][gf_hal_common]: [gf_debug_info_flag] ret = 0, g_debug_info_flag = 0
03-04 02:10:12.939  1404  1473 W XTCC-5.1.0.23-d: [CS-RIL-LISTENER] timerCallback fired for ril update registering, re-register
03-04 02:10:12.940 10102 10102 E         : debuggerd: worker process 18566 timed out
03-04 02:10:12.943   883   883 I MSM-irqbalance: Decided to move IRQ5 from CPU2 [P:0] to CPU5 [P:1] (banned)
03-04 02:10:12.944   883   883 I MSM-irqbalance: Decided to move IRQ3 from CPU2 [P:0] to CPU6 [P:1] (banned)
03-04 02:10:12.944   883   883 I MSM-irqbalance: Decided to move IRQ5 from CPU0 [P:0] to CPU7 [P:1] (banned)
03-04 02:10:12.944   883   883 I MSM-irqbalance: Decided to move IRQ3 from CPU0 [P:0] to CPU4 [P:1] (banned)
03-04 02:10:12.945   883   883 I MSM-irqbalance: Decided to move IRQ5 from CPU3 [P:0] to CPU5 [P:1] (banned)
03-04 02:10:12.945   883   883 I MSM-irqbalance: Decided to move IRQ3 from CPU3 [P:0] to CPU6 [P:1] (banned)
03-04 02:10:12.945   883   883 I MSM-irqbalance: Decided to move IRQ5 from CPU1 [P:0] to CPU7 [P:1] (banned)
03-04 02:10:12.945   883   883 I MSM-irqbalance: Decided to move IRQ3 from CPU1 [P:0] to CPU4 [P:1] (banned)
03-04 02:10:12.948  1547  1996 E NativeCrashListener: Unable to read from debuggerd
03-04 02:10:12.948 10102 10102 E         : debuggerd: killing target 18468
03-04 02:10:12.950  1547  1637 I BootReceiver: Copying /data/tombstones/tombstone_09 to DropBox (SYSTEM_TOMBSTONE)
03-04 02:10:13.022  1547  2899 I WindowManager: WIN DEATH: Window{6a350cc u0 ru.ninbous.game/com.unity3d.player.UnityPlayerActivity}
03-04 02:10:13.023  1547  2899 W WindowManager: Force-removing child win Window{5813e0b u0 SurfaceView - ru.ninbous.game/com.unity3d.player.UnityPlayerActivity} from container Window{6a350cc u0 ru.ninbous.game/com.unity3d.player.UnityPlayerActivity}
03-04 02:10:13.024  1547  2984 I ActivityManager: Process ru.ninbous.game (pid 18468) has died

A: По этому логу видно, что у вас на объектах висят скрипты, которых уже не существует.  "The referenced script on this Behaviour (Game Object '') is missing!" это не ошибка, а Warning, он предупреждает, что на каких-то объектах остались ссылки на удалённые скрипты. К падению это может привести только если вы попытаетесь к этим скриптам обратиться и получите где-то "NullReference".
Ещё совет. Не знаю, каким образом вы дебажете, но там явно можно отфильтровать значения по тегу. Используйте тег "Unity" и из этой простыни исчезнут левые сообщения от самого телефона.


text:
Q: Count the number of email sent and received in android I am new to android development.I have a requirement to count the number of email sent and received.
I have tried the code given in the link  How to get the number of unread gmail mails (on android). I am running the code in android 2.2. But I am getting Security exception even though i have mention permission in manifest file.
java.lang.SecurityException: Permission Denial: opening provider com.google.android.gm.provider.MailProvider from ProcessRecord{40a44ec8 8832:com.android.gmailexample/10090} (pid=8832, uid=10090) requires com.google.android.gm.permission.READ_GMAIL or com.google.android.gm.permission.WRITE_GMAIL
Here is my code
package com.android.gmailexample;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class GmailCountActivity extends Activity {
 public void onCreate(Bundle savedInstanceState) {
        Log.d("Activity","Inside Oncrete");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        queryLabels();
    }

    public static final class LabelColumns {
        public static final String CANONICAL_NAME = "canonicalName";
        public static final String NAME = "name";
        public static final String NUM_CONVERSATIONS = "numConversations";
        public static final String NUM_UNREAD_CONVERSATIONS = "numUnreadConversations";
    }

    public void queryLabels(){
        Log.d("Activity","Inside query label");
        String account="email@company.com";
        Uri LABELS_URI = Uri.parse("content://gmail-ls/unread/");
        Uri ACCOUNT_URI = Uri.withAppendedPath(LABELS_URI, account);
        ContentResolver contentResolver= this.getContentResolver();
        Cursor cursor = contentResolver.query(ACCOUNT_URI, null, null, null, null);

        //iterate over all labels in the account
        if (cursor.moveToFirst()) {
            int unreadColumn = cursor.getColumnIndex(LabelColumns.NUM_UNREAD_CONVERSATIONS);
            int nameColumn = cursor.getColumnIndex(LabelColumns.NAME);
            do {
                String name = cursor.getString(nameColumn);
                String unread = cursor.getString(unreadColumn);//here's the value you need
                Log.d("Name", name);
                Log.d("Unread ", unread);
            } while (cursor.moveToNext());
            Log.d("Unread count", String.valueOf(unreadColumn));
        }
    }
   }

and my manifest file is
<uses-sdk android:minSdkVersion="10" />
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:label="@string/app_name"
        android:name=".GmailCountActivity" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
<uses-permission android:name="com.google.android.googleapps.permission.GOOGLE_AUTH"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="com.google.android.providers.gmail.permission.READ_GMAIL"/>
<uses-permission android:name="com.google.android.gm.permission.READ_GMAIL"/>
<uses-permission android:name="com.google.android.gm.permission.WRITE_GMAIL"/>

I am not able to locate the error. Any help will be appreciated.
Regards
Pushpa

A: Unfortunately mail applications do not expose their content and data, and most of them are third part (closed source including gmail)
Thus, the thing you want is not approachable.

A: We need ContentProvider to retrieve label data. We can use this to access up-to-date unread counts for specific accounts' inboxes and labels.
http://android-developers.blogspot.in/2012/04/gmail-public-labels-api.html


text:
Q: Remove dead code in JSP I have a big project with a lot of code (most in JSP) and I like to find a tool that can remove dead code from all the JSP. Do you know or recommended me a good tool?
I've looked into lots of tools that do this well for pure Java projects, but nothing seems to really handle projects with JSP and JavaScript.

A: Theoretically ProGuard can process WAR files, how about running you code through that selecting the options to remove redundant code?


text:
Q: Regex to match MediaWiki template without certain named parameter I'll get to the point: I need a regex that matches any template out of a list that have a date parameter - so assuming that my (singleton for now) list of templates is "stub", the things below that are in bold should be matched:

*

*{{stub}}

*{{stub|param}}

*{{stub|date=a}}

*{{stub|param|date=a}}

*{{stub|date=a|param}}

*{{stub|param|date=a|param}}
Note: "param" means any number of parameters there.

Additionally, it would be nice if it could also match if the date parameter is blank, but this is not required.
The current regex I have so far is
{{((?:stub|inaccurate)(?!(?:\|.*?\|)*?\|date=.*?(?:\|.*?)*?)(?:\|.*?)*?)}}

However it matches the fourth and sixth items in the list above.
Note: (?:stub|inaccurate) is just to make sure the template is either a stub or inaccurate template.
Note 2: the flavor of regex here is Python 2.7 module RE.

A: Since you are using Python, you have the luxury of an actual parser:
import mwparserfromhell
wikicode = mwparserfromhell.parse('{{stub|param|date=a|param}}')
for template in wikicode.filter_templates():
    if template.get('date')...

That will remain accurate even if the template contains something you would not have expected ({{stub| date=a}}, {{stub|<!--<newline>-->date=a}}, {{stub|foo={{bar}}|date=a}} etc.). The classic answer on the dangers of using regular expressions to parse complex markup applies to wikitext as well.

A: I think it's enough to have a negative look-ahead, which tries to match date at any position?
{{((?:stub|inaccurate)(?!.*\|date=).*)}}
If empty date parameters have a | following the equals sign, then use
{{((?:stub|inaccurate)(?!.*\|date=[^|}]).*)}}


text:
Q: How can i avoid the getimage() warning message in php Recently i worked in project. there i need to a resize a picture and i use the following class.
class SimpleImage
{
   var $image;
   var $image_type;
   function load($filename)
   {
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if($this->image_type == IMAGETYPE_JPEG)
      {
         $this->image = imagecreatefromjpeg($filename);
      }
      elseif( $this->image_type == IMAGETYPE_GIF )
      {
         $this->image = imagecreatefromgif($filename);
      }
      elseif( $this->image_type == IMAGETYPE_PNG )
      {
         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null)
   {
      if( $image_type == IMAGETYPE_JPEG )
      {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF )
      {
         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG )
      {
         imagepng($this->image,$filename);
      }
      if( $permissions != null)
      {
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG)
   {
      if( $image_type == IMAGETYPE_JPEG )
      {
         imagejpeg($this->image);
      }
      elseif( $image_type == IMAGETYPE_GIF )
      {
         imagegif($this->image);
      }
      elseif( $image_type == IMAGETYPE_PNG )
      {
         imagepng($this->image);
      }
   }
   function getWidth()
   {
      return imagesx($this->image);
   }
   function getHeight()
   {
      return imagesy($this->image);
   }
   function resizeToHeight($height)
   {
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
   function resizeToWidth($width)
   {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
   function scale($scale)
   {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }
   function resize($width,$height)
   {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }
}

when i use the class it show a warning message like bellow

Warning:
  getimagesize(seeker/SeekerPhoto/so.jpg)
  [function.getimagesize]: failed to
  open stream: No such file or directory
  in C:\xampp\htdocs\job\insphoto.php on
  line 11
Warning: images): supplied argument is
  not a valid Image resource in
  C:\xampp\htdocs\job\insphoto.php on
  line 60
Warning: imagesy(): supplied argument
  is not a valid Image resource in
  C:\xampp\htdocs\job\insphoto.php on
  line 64
Warning: imagecopyresampled():
  supplied argument is not a valid Image
  resource in
  C:\xampp\htdocs\job\insphoto.php on
  line 87

How can i avoid this kind of warning message. Thank you Arif..

A: You should check first if the file exists (is_file function) and is readable (is_readable function).

A: Your methods have no error handling what so ever.
E.g. the load() method. If the file doesn't exist in the first place it makes little sense to get information from it via getimagesize(). And if getimagesize() fails it makes even less sense to use its return value to test for certain image types, and so on and on.
an (untested) example:function load($filename) {
    if ( !is_readable($filename) ) {
        throw new ErrorException("file not readable");
    }
    else if ( false===($image_info=getimagesize($filename)) ) {
        throw new ErrorException("unable to get informations from image file");
    }
    //
    switch( $image_info[2] ) {
        case IMAGETYPE_JPEG:
            $fn = 'imagecreatefromjpeg';
            break;
        case IMAGETYPE_GIF:
            $fn = 'imagecreatefromgif';
            break;
        case IMAGETYPE_PNG:
            $fn = 'imagecreatefrompng';
            break;
        default:
            throw new ErrorException("unknown image type");
    }
    $this->image = $fn($filename);
    if ( false===$this->image ) {
        throw new ErrorException("$fn failed");
    }
    $this->image_type = $image_info[2];
    return $this->image_type;
}

A: Simple and working solution based on Handle error when getimagesize can't find a file :
$img_url = "not-existing.jpg";

if ( is_file($img_url) && is_array($img_size = getimagesize($img_url)) ) {
  print_r($img_size);
  echo "OK";
} else {
  echo "NOT OK";
}