text:
Q: Apache2 stopped working after upgrade to v2.4 ((38)Function not implemented: AH00141) I was happily running apache2 and mysql on a Ubuntu 16.04 server with no problems, but yesterday I noticed that there were a bunch of updates available and I installed them using apt-get.
One of the updates was apache2, upgraded to 2.4.46. Since then, apache stopped working. It returns this error when I try to start it: (38)Function not implemented: AH00141: Could not initialize random number generator. After reading some post online, I decided to upgrade my Ubuntu version to 18.04, the process just finished, but the situation didn't change, apache is still not working with the same error.
I read to check if /dev/random or /dev/urandom are present on the system, and they are there.
I do not know what to do to have apache working again. Can someone help me? Maybe give me some direction on how to downgrade it, I don't know, I really have no idea.
Thank in advance,
S.
UPDATE
I think the problem is the kernel, too old to work with the latest Apache version. I see that I have a 3.13.xxx and a 5.4.xxx kernel available, but I cannot switch to the latest. Neither update-grub nor update-grub2 seem to be able to change the kernel. I think I need some help with grub config to solve this problem.
I tried to edit grub.cfg and point GRUB_DEFAULT=1 but it didn't work. I was wondering if changing it to
GRUB_DEFAULT="Ubuntu, with Linux 5.4.0-67-generic"
(I can see that entry in grub.cfg) might work.


text:
Q: Is XLINQ available with .NET 2.0SP1 I was pleasantly surprised a few months ago to learn that I could use many C# 3.x constructs (anonymous types, lambdas, automatic properties) in .NET 2.0, due to the fact that they all compile to the same IL...in effect, syntactic sugar.
Is this also the case of LINQ and XLINQ?  Can i use these constructs while still targeting .NET 2.0 runtimes?

A: LINQ is a set of extension methods defined in the System.Core assembly which is part of .NET Framework 3.5. So in order to use LINQ and LINQ to XML you will need to have .NET Framework 3.5 installed on the target machine because your application will have a static dependency on this assembly.
There's a nice diagram showing what's included in different versions of the framework.

A: For info, much of the core of LINQ is available in .NET 2.0 (with C# 3.0) via (for example) LINQBridge. This gives you most of LINQ-to-Objects (allowing query syntax against in-memory collections/iterators), but it doesn't provide the new assemblies required for LINQ-to-XML or LINQ-to-SQL etc.
So no; you can't use XDocument without the new assemblies from .NET 3.5; but you can do many LINQ things.

A: yes @miguel it is syntactic sugar, but it is really helpful and tasty. The Linq came to scene with C# 3 so per se you cannot use LINQ things in 2.0 version.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Insert into Oracle table from excel I am trying to read the data from excel and insert into existing Oracle table. The file size is 15MB. I have to map the excel column name to table column name. Before that I need to truncate the table.
The excel has
            Name
            Number
             Age

The Oracle table has
         EMPLOYEE{
              ID
              EMP_NAME
              EMP_AGE
              EMP_ADDRESS
              CREATED_DATE
             }

Now I need to map the columns
NAME=> EMP_NAME, AGE=> EMP_AGE
      TRUNCATE TABLE EMPLOYEE;
      LOAD DATA{ EXCEL}
       INSERT INTO EMPLOYEE(  )//THIS SHOULD ALSO CREATE ID AND ADD THE CURRDATE() AS CREATED DATE;
       COMMIT;

I am actually stuck here and need to some help to proceed further. I HAVE AROUND 300000 ROWS IN EXCEL
Thanks in advance


text:
Q: 403 Forbidden Error when trying to view localhost on Apache I think my Apache must be all screwed up. I don't know if it ever worked. I just upgraded to Snow Leopard, and the first step on this tutorial is to start apache and check that it's working by opening http://localhost. It starts fine but when I go to localhost I get a 403 forbidden error.
I don't know where to start figuring out how to fix it, so I wonder if a fresh install of Apache would do the trick.
What do you think?
Update: I found some error logs in /private/var/log/apache2/. Found this in one of the logs. Not sure what it means:
[Tue Nov 10 17:53:08 2009] [notice] caught SIGTERM, shutting down
[Tue Nov 10 21:49:17 2009] [warn] Init: Session Cache is not configured [hint: SSLSessionCache]
Warning: DocumentRoot [/usr/docs/dummy-host.example.com] does not exist
Warning: DocumentRoot [/usr/docs/dummy-host2.example.com] does not exist
httpd: Could not reliably determine the server's fully qualified domain name, using Andrews-Mac-Pro.local for ServerName
mod_bonjour: Skipping user 'andrew' - cannot read index file '/Users/andrew/Sites/index.html'.
[Tue Nov 10 21:49:19 2009] [notice] Digest: generating secret for digest authentication ...
[Tue Nov 10 21:49:19 2009] [notice] Digest: done
[Tue Nov 10 21:49:19 2009] [notice] Apache/2.2.11 (Unix) mod_ssl/2.2.11 OpenSSL/0.9.8k DAV/2 PHP/5.3.0 configured -- resuming normal operations

Update: I also found something in the dummy-host.example.com-error_log file. I didn't set these dummy-host things by the way. Is this the default configuration?
[Tue Nov 10 21:59:57 2009] [error] [client ::1] client denied by server configuration: /usr/docs

Update: Woohoo! I found the file that had the virtual host definitions. It was in /etc/apache2/extra/httpd-vhosts.conf. It had those two dummy virtual host settings in there. I added a localhost virtual host. Not sure if this is necessary, but since it wasn't working before, decided to do it anyway. After removing the old virtual hosts, adding my new localhost virtual host, and restarting apache, it seems to work. So I guess whenever I want to add a virtual host, I only need to add them to this file? Or is there a hosts file somewhere, like there is on Linux?
Update: Yes, there is an /etc/hosts file that need to be changed to. Add the virtual host name to that file.

A: If you're getting a 403 error it probably means the directory does not exist, or the privileges on that directory won't let you see it.
My problem was that the default virtual host settings were pointing to a directory that didn't exist.
So here's what you should do: (assuming you're on Snow Leopard)

*

*Find and open your virtual hosts configuration file.
pico /etc/apache2/extra/httpd-vhosts.conf

*Check that your virtual host definitions are in there, otherwise create them
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot "/Users/yourusername/Sites/mysite"
ServerName mysite.local
ErrorLog "/private/var/log/apache2/mysite-error_log"
CustomLog "/private/var/log/apache2/mysite-access_log" common
</VirtualHost>

*Open up /etc/hosts file and add your virtual host name. This is what's in mine:
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1          localhost
255.255.255.255    broadcasthost
::1                localhost
fe80::1%lo0        localhost

# VIRTUAL HOST START
127.0.0.1          localhost
127.0.0.1          mysite.local
# VIRTUAL HOST STOP

*Now restart Apache and you should be good to go!
sudo apachectl restart

A: Also it is labeled as a warning, it is really the critical line in your error log:
Warning: DocumentRoot [/usr/docs/dummy-host.example.com] does not exist

Apache is searching for a directory that will hold the files that will be solved when you talk to it. Apparently, this directory doesn't exist and thus Apache is not able to solve you anything. Create the directory and place some index.html file in there or edit your config file to point Apache to another directory.


text:
Q: How do I Call PropertyChanged if I have a Binding to the Current DataItem (Path=.) In my XAML code, I have a binding to the current dataitem like this:
Background="{Binding Path=., Converter={StaticResource ResourceKey=kBackground}}"

My converter uses several properties of the dataitem to determine the background.  When any of those properties change, the background color could change.  I want to send a notification to the target so that the background will change appropriately.  My question is that I don't know how to send such a notification when the binding path is ".".
If my converter uses PropertyA and PropertyB, calling:
PropertyChanged(this, new PropertyChangedEventArgs("PropertyA"))

and/or
PropertyChanged(this, new PropertyChangedEventArgs("PropertyB"))

doesn't trigger the binding.  I tried calling this:
PropertyChanged(this, new PropertyChangedEventArgs("."))

but it didn't trigger the binding either.
How do I call PropertyChanged in such a way that my "Path=." bindings get notifications that they need to update?
This may be a duplicate question, but I couldn't find one.  I don't know the terminology very well.

A: Try using an IMultiValueConverter instead, and passing it the properties it needs
<Grid.Background>
    <MultiBinding Converter="{StaticResource MyMultiValueConverter}">
        <Binding Path="PropertyA"/>
        <Binding Path="PropertyB"/>
    </MultiBinding>
</Grid.Background>

This should get re-evaluated anytime a PropertyChange notification is raised for either PropertyA or PropertyB
The alternative using your current binding syntax would be to raise a PropertyChange notification of your parent data item anytime PropertyA or PropertyB changes.
For example, assuming your current data item is SomeObject:
SomeObject.PropertyChanged += SomeObject_PropertyChanged;

...

void SomeObject_PropertyChanged(object src, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "PropertyA" || e.PropertyName == "PropertyB")
    {
        RaisePropertyChanged("SomeObject");
    }
}


text:
Q: SQL insert Or update times out if large date in loop i have some data with userid and date.
Sometimes there is large datas i need to loop through and update the sql database but the database times out.
is there any better way i can do this please, sample code below.
foreach($time[$re->userid][$today] as $t){

                if(($re->time >= $t->in_from) && ($re->time < $t->in_to)
                    && md5($t->WorkDay."_in".$re->date) != $in){//in

                    $tble = tools::sd("{$t->WorkDay} in");
                }

                if(($re->time >= $t->out_from) && ($re->time < $t->out_to)
                    && md5($t->WorkDay."_out".$re->date) != $out){//out

                    $tble = tools::sd("{$t->WorkDay} out");

                    if($tble =='nout'){
                        $re->date2 = tools::ndate($re->date . "- 1");
                    }
                }

                if(!empty($tble)){
                    $q = array(
                         "id" => $re->userid
                        , "dt" => $re->date2
                        , "{$tble}" => $re->time
                    );

                    dump($q); // insert into sql
                }
            }

dump function:::
function dump($d ='')
{
    if(!empty($d)){
    end($d);
    $tble = key($d);
    $d['ld'] = "{$d['dt']} {$d[$tble]}";

        $r = $GLOBALS['mssqldb']->get_results("
            IF NOT EXISTS (select id,ld,dt,{$tble} from clockL
                WHERE id = '{$d['id']}'
                AND dt ='{$d['dt']}')
                INSERT INTO clockL (id,ld,dt,{$tble})
                VALUES ('{$d['id']}','{$d['ld']}','{$d['dt']}'
                ,'{$d[$tble]}')
            ELSE IF EXISTS (select id,{$tble} from clockL
                WHERE id = '{$d['id']}'
                AND dt ='{$d['dt']}'
                AND {$tble} = 'NOC'
                )
                update clockL SET {$tble} ='{$d[$tble]}', ld ='{$d['ld']}' WHERE id = '{$d['id']}'
                AND dt ='{$d['dt']}' AND {$tble} ='NOC'
            ");

            //print_r($GLOBALS['mssqldb']);
    }
}

Thank You.

A: Are you aware of a PHP function called set_time_limit()? You can find the detailed documentation here.
This can manipulate the execution time, which is 30 seconds default. If you set it to 0, eg set_time_limit(0), there will be no execution time limit.

A: Do the insert/update outside of the loop. Enclose it in a transaction so that you don't get an inconsistent database state if the script dies prematurely. Using one big query is usually faster than making lots of small queries. You might also set higher values for time and memory limits, but be aware of the consequencies.

A: May be looping is the reason for time out.
Because when your performing the insert/update operations in side the loop, the connection to the database will be in open state until the loop is terminated which may cause the time out problem.
Try doing the insert/update operation outside of the loop.


text:
Q: Comparing values from two tables in a nested where clause. This is a rather specific question. I'm working to create row restrictions in Business Objects and the customer wants records to fall within a certain range from another table. The problem is, you can only select one table. A work around I found was that I can select other tables in the WHERE clause.
For Example:
a.RE_UID = b.RE_UID

I have to use:
a.RE_UID IN
      (select A.RE_UID
       from
        TABLE1 A
        join
        TABLE2 B
        ON
        A.RE_UID = B.RE_UID
      )

Where I'm stumped is that I need compare off another table with a BETWEEN. Something like:
A.CL_FROM_SVC_DTE BETWEEN B.EFF_DTE AND B.END_DTE

If I just try like I did above I get errors that it expected another character after WHERE:
SELECT *
FROM
  TABLE2
WHERE IN
(select A.CL_FROM_SVC_DTE
FROM TABLE1 A
JOIN TABLE2 B ON A.RE_UID = B.RE_UID
)
BETWEEN B.EFF_DTE AND B.END_DTE

A: If you are selecting everything from Table2 with the condition on Table1, what you could do is this:
SELECT T2.* FROM TABLE2 T2
INNER JOIN TABLE1 T1 ON T2.RE_UID = T1.RE_UID
WHERE T1.CL_FROM_SVC_DTE BETWEEN T2.EFF_DTE AND T2.END_DTE

I hope it helps.

A: Not sure I understood neither the problem nor the restriction to select from one table alone, so this is an educated guess at best:
SELECT B.*
FROM
TABLE2 B
WHERE b.RE_UID IN (
    select a.RE_UID
    FROM TABLE1 A
    WHERE A.CL_FROM_SVC_DTE BETWEEN B.EFF_DTE
                                AND B.END_DTE A.RE_UID
);


text:
Q: Autofac Null reference error web api 2 i am getting "An exception of type 'System.NullReferenceException' occurred in AutoFac Practice.dll but was not handled in user code"
My code and configuration for Autofac is:
Autofac Configuration:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var builder = new ContainerBuilder();

        // Register your Web API controllers.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // OPTIONAL: Register the Autofac filter provider.
        builder.RegisterWebApiFilterProvider(config);

        builder.RegisterType<SqlServerRepository>().As<IDBRepository>().InstancePerRequest();

        // Set the dependency resolver to be Autofac.
        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }
}

Controller Code:
 public class HomeController : ApiController
{
    IDBRepository _repository;

    void Home(IDBRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public string Print()
    {
        return _repository.Print();
    }
}

Repository
interface IDBRepository
{
    //void Select();
    //void Insert();
    //void Update();
    //void Delete();

    string Print();
}

public class SqlServerRepository : IDBRepository
{
    public string Print()
    {
        return "hello there, i am Sql Server";
    }
}

In Controller i am getting error on this line: return _repository.Print(); saying object reference not set.
_repository is not getting referenced i don't know what i am missing for the configuration.

A: You must set the dependency (IDBRepository) in the controller's constructor.
So instead of this:
void Home(IDBRepository repository)
{
    _repository = repository;
}

you'll have to do:
public HomeController(IDBRepository repository)
{
    _repository = repository;
}


text:
Q: Understanding difference between "intense" and "intensive" "Intense" and "intensive" are two different words:

If you are putting forth an intense effort, your work is "intense":
  "My intense study of Plato convinced me that I would make a good
  leader." But when the intensity stems not so much from your effort as
  it does from outside forces, the usual word is "intensive": "the
  village endured intensive bombing."

Is there any way to understand why the word ending in "se" has one meaning, and the word ending in "sive" has another meaning?

A: The reason these two words have different endings is because they grew from two different root words in Old French, which helped form Old (and Modern) English.
Intense came from the French word intensus, meaning "stretched, strained, tight".
Intensive came from the English word intend, which in turn came from the French words entendre and intendre (essentially the same word), which means "to direct one's attention to".
Interestingly, both of these French words have the same Latin root word intendere, which is literally "to stretch tight", but entendre took a separate path in terms of connotation and meaning and developed into the word we have now.

A: Intensive is something that is intense. Simply put intensive is used to talk about something that is sustained, where as intense is more linked to feelings. Intensive is usually used to talk about something outside of you, whereas intense commonly refers to something you felt, or did.
Sourced From  here on Dictionary.com

A: BAD: The government has embarked on an intense industrialization programme.
GOOD: The government has embarked on an intensive industrialization programme.
intense = strong or very great; extreme: 'intense heat', 'intense pleasure', 'intense pain', 'intense competition'
intensive = concentrated: 'an intensive English course', 'a period of intensive training'


text:
Q: How to parse this I'm experimenting with googles url shortener goo.gl and at the moment it send the url to goo.gl and returns this:
{
 "kind": "urlshortener#url",
 "id": "http://goo.gl/kyPI",
 "longUrl": "http://dsfsd.com/"
}

I think it's JSON but I'm having trouble with that because of ARC. Is there anyway else I could parse the string with key "id"?

A: It's JSON, you can use a framework like SBJson to parse it. See http://stig.github.com/json-framework/

A: If your app targets iOS 5 you can use NSJSONSeralization class of Apple.
(Let's assume youryour received is called theData)
NSError *error=nil;
    id result=[NSJSONSerialization JSONObjectWithData:theData options:
               NSJSONReadingMutableContainers error:&error];

//to retrieve the 'kind' value of the object
    NSLog("Kind: %@",[result objectForKey:@"kind"]);


text:
Q: How do I find multiple items in a field with mongodb? I have the following type of occurrence in my Mongo documents.
"tags" : [ [ "narnia" ], [ "aslan" ], [ "winter" ], [ "heaven" ] ]

I need to know how to find this document by matching all of any number of the tags. I.e. Narnia AND Aslan (but not Narnia OR Aslan).
The query needs to be made with in PHP.
So far I only have it working for a single tag. I.e.
$filter['tags'] = array('$in' => array(array('Narnia')));

A: As Hussain mentioned in comments - you might want to revise that document structure as seems like you're storing unnecessary arrays.
Otherwise, what you're trying to do could be done with an $and statement (example without the nested arrays):
PRIMARY> db.wardrobe.find({ $and: [ { tags: "narnia" }, { tags: "tugboat" } ] })
//returns nothing

PRIMARY> db.wardrobe.find({ $and: [ { tags: "narnia" }, { tags: "winter" } ] })
//returns { "_id" : ObjectId("521067a48202463b88c2a0c9"), "tags" : [ "narnia", "aslan", "winter", "heaven" ] }

In PHP:
//With your nested arrays:
$filter = array(
   '$and' => array(
      array('tags' => array('narnia') ),
      array('tags' => array('aslan') )
   )
);

//With a simple array:
$filter = array(
   '$and' => array(
      array('tags' => 'narnia'),
      array('tags' => 'aslan')
   )
);

$mongoClient->selectCollection('cwlewis', 'wardrobe')->find( $filter );


text:
Q: How do I change the default webcam? I'm using ubuntu 18.10, and my laptop's (ThinkPad 25) built-in webcam image is distorted and pink. I tried in google hangouts and in cheese, and they both show the same kind of image.

Cheese doesn't show any errors on command line, just says this:
(cheese:5930): Gtk-WARNING **: 09:00:44.808: Theme parsing error: cheese.css:7:35: The style property GtkScrollbar:min-slider-length is deprecated and shouldn't be used anymore. It will be removed in a future version

which I imagine is not relevant(?).
I found this page: https://help.ubuntu.com/community/Webcam/Troubleshooting but it is very old and talks about Skype, and starting Skype with different options, but I can't use Skype, I need Google Hangouts to work.
I believe this may be what my webcam is:
product: Integrated Camera [4F2:B5AB]
vendor: SunplusIT Inc [4F2]
bus info: usb@1:8
version: 0.10
capabilities:
    USB 2.0
configuration:
    driver: uvcvideo
    maxpower: 500mA
    speed: 480Mbit/s

Any ideas what to do? Thanks!

Edit.
Ok, it appears that my laptop actually has 2 different webcams, and the camera that is showing the bad image is actually named Integrated IR Camera.
I found a webpage about it, too: https://blogs.gnome.org/jamesh/2017/10/22/thinkpad-infrared-camera/
I was randomly clicking on buttons in cheese, and there is a button that changes which camera it is using, and the other camera is showing picture just fine. The default camera seems to be the infrared camera -- how do I get rid of it in all programs, since it is not doing anything useful?

A: The OPs solution didn't work for me, but has given me a push to the right direction. Indeed, if the IR cam is separate from the main one, it can be detached by removing power from it.
Quick google for "ubuntu disable usb device" has shown this page - https://karlcode.owtelse.com/blog/2017/01/09/disabling-usb-ports-on-linux/
In short - find the USB port to which the camera is connected (1-1.6 in the example below, but it for 1-5 for my laptop):
$ for device in $(ls /sys/bus/usb/devices/*/product); do echo $device;cat $device;done
/sys/bus/usb/devices/1-1.2/product
Dell USB Entry Keyboard
/sys/bus/usb/devices/1-1.6/product
Webcam SC-13HDL11624N
/sys/bus/usb/devices/2-1/product
Amazon Kindle
/sys/bus/usb/devices/2-2/product
USB Receiver
/sys/bus/usb/devices/usb1/product
EHCI Host Controller
/sys/bus/usb/devices/usb2/product
xHCI Host Controller
/sys/bus/usb/devices/usb3/product
xHCI Host Controller

Then power it down:
echo '1-1.6' | sudo tee /sys/bus/usb/drivers/usb/unbind

Or do this on reboot via cron:
sudo crontab -e

and add the following there:
@reboot echo '1-1.6' > /sys/bus/usb/drivers/usb/unbind

(of course, replacing "1-1.6" with "1-5" or whatever port your camera is connected)
Similar question and solution is - Is it possible to turn off a specific USB port so it doesn't accept any device?

A: So I'll write this here if anyone else runs into this problem and needs my solution.
I ended up disabling the Integrated IR Camera with usb_modeswitch.
First I checked the vendor and product of the Integrated IR Camera with dmesg:
karl@penguin:~$ dmesg |grep "Integrated IR Camera"
[    1.341836] usb 1-5: Product: Integrated IR Camera
[    3.741357] uvcvideo: Found UVC 1.00 device Integrated IR Camera (04f2:b5ac)
[    3.767724] input: Integrated IR Camera: Integrate as /devices/pci0000:00/0000:00:14.0/usb1/1-5/1-5:1.0/input/input12

This 04f2:b5ac shows the vendor and product.
So I created a customized config file for this device, that will detach the driver from this usb device (the file name contains the vendor and product ids):
karl@penguin:~$ echo "echo DetachStorageOnly=1 > /etc/usb_modeswitch.d/04f2:b5ac" | sudo bash

And then I added a couple of lines into usb_modeswitch udev rules right before the 'LABEL="modeswitch_rules_end"' at the end of the file, so that the config is applied on startup:
karl@penguin:~$ sudo gedit /lib/udev/rules.d/40-usb_modeswitch.rules

(Note that the vendor id and product id still match the ones from dmesg.)
# TP25 IR Camera
ATTR{idVendor}=="04f2", ATTR{idProduct}=="b5ac", RUN+="usb_modeswitch '/%k'"

Rebooted, and now the default Integrated IR Camera is gone for good.


text:
Q: How to delete old commits in Git without conflicts Right now I have a very large repository with the following commits:

*

*Latest commit

*A lot of commits here

*First commit

What I want to do is to squash commits 2 and 3 into a single one. I tried interactive rebase, but there are many conflicts and it would take unreasonable amount of time to fix those. And it doesn't make any sense to resolve those conflicts since eventually they will become one commit.
The result would look like this:

*

*Latest commit

*Initial commit (includes 2 and 3)

A: I solved the problem using grafts.
To squash using grafts
Add a file .git/info/grafts, put there the commit hash you want to become your root
git log will now start from that commit
To make it 'real' run git filter-branch
original answer

A: How were you doing an interactive rebase?
If you're dealing with squashing a single branch you shouldn't have conflicts like that.
git rebase -i HEAD~3

Then in vim/editor
pick commit 3
pick commit 2
pick commit 1

Change that to
pick commit 3
squash commit 2
pick commit 1

With 3 being the oldest and 1 being the most recent


text:
Q: Question on sums of multiplicative functions twisted by the Mobius function Let $\mu(\cdot)$ be the Mobius function, defined on the natural numbers by
$$\displaystyle \mu(n) = \begin{cases} (-1)^{\omega(n)} & \text{if } n \text{ is square-free} \\ 0 & \text{otherwise}.\end{cases}$$
Here $\omega(n)$ is the number of distinct prime divisors of $n$. It is well-known that the Mertens function $M(x)$ defined by
$$\displaystyle M(x) = \sum_{n \leq x} \mu(n)$$
satisfies the asymptotic
$$\displaystyle M(x) = O\left(x \exp(-c \sqrt{\log x}) \right)$$
for some positive number $c$; this is a consequence of the prime number theorem. The Riemann hypothesis is equivalent to the assertion that for any $\varepsilon > 0$ the Mertens function satisfies $M(x) = O_\varepsilon \left(x^{1/2 + \varepsilon}\right)$.
Let $a, q$ be co-prime positive integers, and let $P_{a,q}$ denote the set of primes $p \equiv a \pmod{q}$. Let $N_{a,q}$ be the set of positive integers such that $p | n \Rightarrow p \in P_{a,q}$. Let
$$M_{a,q}(x) = \sum_{\substack{n \leq x \\ n \in N_{a,b}}} \mu(n).$$
Does $M_{a,q}(x)$ satisfy a similar asymptotic as $M(x)$?
Next, let $f \in \mathbb{Z}[x]$. Put $\rho_f(n) = \# \{m \in \mathbb{Z}/n \mathbb{Z} : f(m) \equiv 0 \pmod{n}\}$. Define
$$\displaystyle M_f(x) = \sum_{n \leq x} \mu(n) \rho_f(n).$$
Does $M_f(x)$ satisfy a similar asymptotic upper bound as $M(x)$?


text:
Q: SQL query works fine in TOAD , but not when placed in java code The following sql query executes fine when ran in TOAD editor and shows results,but does not fail or
show results when placed in java code.
CREATE TABLE CDRRD.C31820_ADHOCM AS
    SELECT A.REC_ID A_REC_ID, A.NORM_DUR A_DUR, A.NORM_STDT A_STDT, A.TOTAL_TYPE A_TT, B.REC_ID B_REC_ID, B.NORM_DUR B_DUR,  B.NORM_STDT B_STDT,
           B.TOTAL_TYPE B_TT, 2180 SCENARIO_ID,3324 PAIR_ID,1 RECURSIVE_STAGE_ID FROM
           (SELECT D.* FROM CDRRD.C31820_3445 D WHERE EXISTS (
                      SELECT E.* AS FROM CDRRD.C31820L E WHERE E.A_TT = 473 AND E.RECURSIVE_STAGE_ID = 1 AND E.A_REC_ID = D.REC_ID)) A ,
           (SELECT F.* FROM CDRRD.C31820_3440 F WHERE EXISTS (
                      SELECT G.* AS FROM CDRRD.C31820R G WHERE G.B_TT = 300 AND G.RECURSIVE_STAGE_ID = 1 AND G.B_REC_ID = F.REC_ID)) B
    WHERE EXISTS (SELECT * FROM CDRRD.C31820_ADHOC C WHERE  A.NORM_A = C.NORM_B AND C.NORM_A = B.NORM_A AND B.PAY_TYPE = C.PAY_TYPE AND A.PAY_TYPE = C.PAY_TYPE )
     AND TO_NUMBER ((a.norm_stdt - b.norm_stdt) * 86400) BETWEEN -90 AND 90 AND (b.norm_dur - a.norm_dur) BETWEEN -1 AND 2

A: It's a create statement, what results do you expect?

A: You should check if you commit the transaction after the command is executed.
it would help to see the java code.


text:
Q: Converting longitude and latitude data from JSON for Google Maps API I've been attempting to dynamically generate a Polyline on an embedded map via Google Maps API based on some data through JSON.
The example Google has given for a static set of coordinates to be passed to their API is:
    var flightPlanCoordinates_static = [
      {lat: 51.470544, lng: -2.588658},
      {lat: 51.867286, lng: -2.238049},
      {lat: 52.531292, lng: -1.899454}
    ];

However, I want to dynamically change the coordinates, so created the following Javascript code to read the JSON and, I'd hope, convert it into the correct format of the array to work with the API. However, something must be wrong because the dynamic list doesn't display the line on the map.
    var flightPlanCoordinates_dynamic = [];
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            for (var i = 0; i < myObj.lat.length; i++) {
                flightPlanCoordinates_dynamic[i] = {'lat' : myObj.lat[i], 'lng' : myObj.lng[i]};
            }

        }
    };
    xmlhttp.open("GET", "myJSONfile.py", true);
    xmlhttp.send();

My JSON output looks like this (and is read by the Javascript without error):
{"lng": [-2.588658, -2.238049, -1.899454], "lat": [51.470544, 51.867286, 52.531292]}

If I print both variables to the console, I get similar results but it's clearly different enough for the API to ignore (no error) my dynamically generated content.
Screenshot of the Console Output
Any help will be greatly appreciated.
EDIT:
Posting entire code, without body HTML tags, in its non-working form:

A: As mentioned in my comment, it looks like the issue here is that Google is expecting an array of objects:
var flightPlanCoordinates_static = [
  {lat: 51.470544, lng: -2.588658},
  {lat: 51.867286, lng: -2.238049},
  {lat: 52.531292, lng: -1.899454}
];

but is being provided an object of arrays:
{"lng": [-2.588658, -2.238049, -1.899454], "lat": [51.470544, 51.867286, 52.531292]}


text:
Q: Using curl in a Windows Universal App I want to use curl in a Windows Universal App (x64).
I managed to get it working, but I had to use a workaround that seems hackish, and I want to confirm that it is needed.
TL;DR - I had to add an #include <winsock2.h> statement before the #include <curl\curl.h> statement, to get it to work. I want to know if it's truly needed on UWP.
I built curl with openssl by following the curl install guide here. I created a blank universal app in Visual Studio 2015 update 3, and added curl and openssl binaries and includes in the appropriate places. Then added a #include <curl\curl.h> at the top of the file and got the following error:
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int for the line typedef SOCKET curl_socket_t; in curl.h.
At the top of curl.h I saw that the following preprocessor macros prevent the inclusion of winsock2.h which defines SOCKET:
#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || \
      defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H))
/* The check above prevents the winsock2 inclusion if winsock.h already was
   included, since they can't co-exist without problems */
    #include <winsock2.h>
    #include <ws2tcpip.h>
#endif

Removing the defined(_WINSOCKAPI_) condition restores the statement and everything compiles fine, meaning that somewhere winsock.h is included and that on UWP it does not defined SOCKET.
Indeed, looking at winsock.h I can see that the typedef which defines SOCKET is wrapped with
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)

which does not hold for a universal app.
However, in winsock2.h there's an equivalent typedef for SOCKET which is not dropped by the preprocessor.
Adding #include <winsock2.h> before the #include <curl\curl.h> statement makes everything work, but I suspect this is not the best way to solve this issue.
So my question is, is this the proper way to use curl on UWP or has anyone found a better solution?
Thanks!

A: Generally it should be no problem to include <winsock2.h> before <curl/curl.h>. But you're also right that it should work without that, because curl.h should include that file if necessary.
As it does not in your case, _WINSOCKAPI_ must be defined somewhere else. Perhaps it's defined in the preprocessor area of the project settings, i.e. it is provided via /D compiler flag. Did you already look there? Also look at the compiler command line, that is used to compile your file, is there a flag that defines _WINSOCKAPI_?
BTW, the reason why curl includes <winsock2.h> conditionally is as follows: Windows has two different socket libraries, winsock and winsock2 (which is to prefer). Both cannot coexistent with each other.
If you need to use winsock instead of winsock2 for some reason you may include <winsock.h> before <curl/curl.h>, and it will work as well.

A: I confirmed that winsock.h is being included by the following include chain: pch.h > collection.h > agile.h > wrl\client.h > unknwn.h > rpc.h > windows.h > winsock.h. pch.h is generated by Visual Studio, and is part of the Universal blank app template.
My workaround is not ideal because this will get winsock.h and winsock2.h both included, and the comment in curl.h says they can't co-exist.
However, I did find that in windows.h, the inclusion of winsock.h is wrapped with #ifndef WIN32_LEAN_AND_MEAN, i.e., I can prevent winsock.h from being included by adding the WIN32_LEAN_AND_MEAN define.
I tried it and successfully issued a simple https request from a UWP app.
So to summarize - when using curl in a UWP app, you must add the preprocessor definition WIN32_LEAN_AND_MEAN.


text:
Q: Working on bitwise operators - And + LeftShift - A reverse calculate Take a look at these codes :
    const int a = 1 << 0;  // = 1
    const int b = 1 << 1;  // = 2
    const int c = 1 << 2;  // = 4
    const int d = 1 << 3;  // = 8

    int flag = 15;  // = 1 + 2 + 4 + 8

    int e1 = flag & a;  // = 1
    int e2 = flag & b;  // = 2
    int e3 = flag & c;  // = 4
    int e4 = flag & d;  // = 8

    bool b1 = e1 != 0;  // = true
    bool b2 = e2 != 0;  // = true
    bool b3 = e3 != 0;  // = true
    bool b4 = e4 != 0;  // = true

Upper Codes in other way(simpler) :
    const int a = 1 << 0;  // = 1
    const int b = 1 << 1;  // = 2
    const int c = 1 << 2;  // = 4
    const int d = 1 << 3;  // = 8

    int flag = 15;  // = 1 + 2 + 4 + 8

    bool b1 = (flag & a) != 0;  // = true
    bool b2 = (flag & b) != 0;  // = true
    bool b3 = (flag & c) != 0;  // = true
    bool b4 = (flag & d) != 0;  // = true

I need a Reverse Formula to return flag value when we set :
b1 , b2 , b3 , b4 variables and make them constant.
So we have 2*2*2*2 = 16 different situations. mean (true|flase)*(true|flase)*(true|flase)*(true|flase) = 16 for setting b variables.
With which method we can figure out what should flag be?
Mean :
    const int a = 1 << 0;  // = 1
    const int b = 1 << 1;  // = 2
    const int c = 1 << 2;  // = 4
    const int d = 1 << 3;  // = 8

    int flag = ?;

    bool b1 = (? & a) != 0;  // = true > I WANT b1 True
    bool b2 = (? & b) != 0;  // = false > I WANT b2 False
    bool b3 = (? & c) != 0;  // = true > I WANT b3 True
    bool b4 = (? & d) != 0;  // = false > I WANT b4 False

For example i want b1 True , b2 False , b3 True , b4 False. So What is the flag?
Or
I want  b1 False, b2 False , b3 True , b4 False. So What is the flag?
How did you find it and give me a method to calculate it!

In my example flag is 15 (sum of a+b+c+d) and in this way all b variables are true.

Related:  Bitwise operations | And | Which situation is true or false in c#

A: Make flag variable using bitwise-or (|) operations with the values you want to be set:
if you want b1 and b4 be true and b2 y b3 be false:
int flag = a | d;

bool b1 = (flag & a) != 0;  // = true
bool b2 = (flag & b) != 0;  // = false
bool b3 = (flag & c) != 0;  // = false
bool b4 = (flag & d) != 0;  // = true

If you want only b3 to be true:
int flag = c;

bool b1 = (flag & a) != 0;  // = false
bool b2 = (flag & b) != 0;  // = false
bool b3 = (flag & c) != 0;  // = true
bool b4 = (flag & d) != 0;  // = false

If you have bs values and want the flag:
int flag = (b1 ? a : 0) | (b2 ? b : 0) | (b3 ? c : 0) | (b4 ? d : 0);


text:
Q: woocommerce assign roles in registration form We are building a website for our project and using Wordpress/Woocommerce.
What we want is for the registration form to allow selection of the various user types (individual, SME, etc.) or roles and then offer the appropriate pricing options depending upon the choice when a product is selected.
I've been trying to research various plugins and there are quite a few it would seem, but am new to Woocommerce and am very unsure whether they can do that exactly as required.
Can anyone point me in the right direction?
Much appreciated,
Jim.

A: Here is a plugin WP Roles at Registration ,this plugin asks the user to choose his role in the website during registration from a list of selected roles.
And for pricing the products according to there roles you can use the plugins like
Woocommerce Role Pricing
Woocommerce Role Based Price
WooCommerce user specific pricing extension
Check these plugins and user which fits your requirement.
Let me know if this solves your issue.


text:
Q: Combining multiple rows into one row where the data in only one column changes and adding the data for the varied column onto the end of the row I was hoping you could help me as my sql is very basic. Below is my query:
I have data that looks like this:
Policy Number | Commission Amount | Relationship | PersonLinked
50422         | 1000.00           | Owner        | John Smith
50422         | 1000.00           | Advisor      | Richard Bass
50422         | 1000.00           | Port Man     | Craig Thomson
74857         | 500.00            | Owner        | Karen Jones
98765         | 20000.00          | Owner        | Tim Crosby
98765         | 20000.00          | Port Man     | Josh Bishop

BUT I want to display all of the data in one row so it looks like this:
Policy Number | Commission Amount | Owner          | Advisor        | Port Man
50422         | 1000.00           | John Smith     | Richard Bass   | Craig Thomson
74857         | 500.00            | Karen Jones    |                |
98765         | 20000.00          | Tim Crosby     |                | Josh Bishop

If it is possible to manipulate the data in this way, please let me know what the SQL would be.  I am really stuck. Please help.

A: Unless there is a fixed, static number of relationships, known from the beginning, then the answer is: NO. You cannot make SQL queries that return variable number of columns.
Your chances are:
 - if you are using a proprietary SQL rdbms, there might be some pivoting functionality
 - if you are using any kind of language (like PHP, VBA) to create the query - then you can create it in a dynamically, after querying for possible relationships.

A: This is assuming that you have one of each role per policy number, and that the only roles that you need to show are these three.
Select [own].[Policy Number],
       [own].[Commission Amount],
       [own].[PersonLinked] as [Owner],
       [adv].[PersonLinked] as [Advisor],
       [port].[PersonLinked] as [Port Man]
From   PolicyRoles as [own]
Join   PolicyRoles as [adv] on [own].[Policy Number] = [adv].[Policy Number]
                            and [adv].[Relationship] = 'Advisor'
Join   PolicyRoles as [port] on [own].[Policy Number] = [port].[Policy Number]
                             and [port].[Relationship] = 'Port Man'
Where  [own].[Relationship] = 'Owner'

A: Try this query
Select a.Policy Number, a.Commission Amount, a.PersonLinked as 'Owner', b.PersonLinked 'Advisor', c.PersonLinked as 'Port Man'
FROM tbl a, tbl b, tbl c
WHERE a.Policy Number = b.Policy Number AND a.Policy Number = c.Policy Number AND
b.Policy Number = c.Policy Number AND a.Relationship = 'Owner' AND
b.Relationship = 'Advisor' AND c.Relationship = 'Port Man';

A: First, your answer depends on the version of SQL, which you did not specify. There are functions in every version that allow you to concat. values, e.g. convert table data to string. In Oracle - LISTAGG(), MY SQL - GROUP_CONCAT() etc... Creating dynamic columns in SQL is not possible unless you create a view or table for each of your cases. You can create table as select all columns you need and add more columns from your_table, you can also create views with different number of column. You need to research this in your version of SQL. All those examples with CASE expressions are good, but I'd do research and see what is available in your version of SQL beacause LISTAGG() or GROUP_CONCAT() are what you are really looking for, not CASE. Here's Oracle example of creating "dynamic" columns. The emp table is existing table used by Oracle:
CREATE TABLE test_tab AS
 SELECT empno
      , ename
      , ename "OWNER" -- This column name is OWNER and datatype is the same as ename
  FROM scott.emp
 WHERE 1=2 -- False - empty table is created, no data...
/

-- Describe newly created table:

SQL> desc test_tab

Column Name  Data Type
--------------------------------
EMPNO    NUMBER (4)
ENAME    VARCHAR2 (10 Byte)
OWNER    VARCHAR2 (10 Byte)


text:
Q: Can someone help me answer to this question An application is used to take 1 second to generate one invoice file. A new code is launched 4 threads in parallel and is executed on a dual-core machine.
How much would it take to finish the generation of 100 invoices?

A: Depending on hardware with Hyperthreading 1 core would support 2 threads. So you will have a total of 4 threads supported by your cpu. Probably the answer will be aproximaty 25(even with hyperthreading it does not run exactly 2 times faster).
Without hyperthreading 50

A: To run, a program or thread must be "on" a core.  On means that core is actively processing the instructions of that program or thread.
So, a program that launches with 4 threads on a 2 core machine can only see two of its threads advanced (being run) at any point in time.  This means you can't run all 4 threads at the same time.
This should be enough for you to figure out the timing, because you've been told that one thread (or program) can craete one invoice in one second if it runs on one core (threads and processes can jump from core to core; but, they cannot run on two cores at the same time)


text:
Q: How to Create a stored procedure in phpmyadmin which inserts data taken from the contact page of a website? I am working on creating my portfolio website. As a part of it, I created a contact form that is connected to MySQL. I want the data from the contact form to be inserted into my table. Now when I just do it normally (I will post the code below), it is working fine but when I try to create a stored procedure it is not working.
My code which is working:
<?php
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

//Database connection
$conn = new mysqli('localhost', 'root', '', 'portfolio');
if($conn->connect_error){
    die('Connection Failed: '.$conn->connect_error);
}
else{
    $stmt = $conn->prepare("insert into contact_info(email, subject, message) values(?, ?, ?)");
    $stmt->bind_param("sss", $email, $subject, $message);
    $stmt->execute();
    echo "Message Received! Karthik will get back to you shortly!!";
    $stmt->close();
    $conn->close();
}
?>

Now when I try it using a procedure it is not working. Here is the code I used in my php file:
<?php
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

//Database connection
$conn = new mysqli('localhost', 'root', '', 'portfolio');
if($conn->connect_error){
    die('Connection Failed: '.$conn->connect_error);
}
else{
    $stmt = $conn->prepare("CALL putInfo(:email,:subject,:message);");
    $stmt->bind_param("sss", $email, $subject, $message); //problem area not able to figure out how to do this.
    $stmt->execute();
    echo "Message Received! Karthik will get back to you shortly!!";
    $stmt->close();
    $conn->close();
}
?>

The error message I am receiving:

Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':email,:subject,:message)' at line 1 in C:\xampp\htdocs\portfolio\connect.php:12 Stack trace: #0 C:\xampp\htdocs\portfolio\connect.php(12): mysqli->prepare('CALL putInfo(:e...') #1 {main} thrown in C:\xampp\htdocs\portfolio\connect.php on line 12

My table schema:


text:
Q: input color value not updating So I am trying to change color in <input type=color>

<html lang="en">
    <body>
        <div>
            Color: <input type="color" id="color">
        </div>

        <!-- jQuery -->
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

        <script>
            $("#color").val("#000080"); // Initial setup

            $("#color").change(function () {
                console.log($("#color").val())
            });
        </script>
    </body>
    </html>

However, when I pick a color in the color picker, $("#color").val() keeps outputting the initial value of #000080 instead of the updated color value.
Is there any fix for this?


text:
Q: Is there a way of getting a file name and inserting into Matlab script? In a folder, I have both my .m file that contains the script and one imaging .dcm file that is the target of my analysis.
Folder structure:
Folder1/analysis.m
Folder1/meas_dynamic_123.dcm
Folder1/meas_123.dcm
Folder1/meas_345.dcm

My script (analysis.m) begins as follows:
target     =''; <== here should go only the filename that contains 'dynamic'
                    example: meas_dynamic_123.dcm

txt        = dir(target);

// etc

So I'm wondering if there is a way of when running analysis.m it will:

*

*automatically search the folder it's in,

*grab the filename of file containing string dynamic in the name,

*insert its name into target variable

*continue running the script
Does anyone have any pointers on how to achieve this? Using ffpath?

A: you should do:
f=dir('*dynamic*');
target=f(1).name;

A: Assume you are not in Folder1 and you need to find it:
script_name = 'analysis';
script_full_path = which(script_name);      % get full path of the script
script_dir = fileparts( script_full_path ); % get the directory of the script
file_list = dir( [script_dir '/*dynamic*']);
name_list = {file_list.name};

name_list will be a cell array containing the file names with the keyword 'dynamic'.

A: Instead of which(scriptname), consider using mfilename('fullpath'), which will directly give you the full path of the running m-file. Using which might break if you had multiple commands of the same name shadowed on the path.


text:
Q: Spring Data MongoDB - model classes without annotations  This question is related to Spring Data MongoDB model classes without annotations.
I have a situation where I need to store my domain classes either in RDBMS store or NoSQL store. Say for example my domain classes are User, Feature, PaymentRequest, Order, OrderLine, OrderHeader etc.
I cannot use any annotation on my domain classes for various reasons.
Application team will specify in which persistent store they like to store. They might configure to store it in MongoDB or in MySQL or in Oracle etc.
My requirement is when I am storing in MongoDB say using spring-data-mongodb I want to leverage the DBRefs for associated objects in my domain object.
How can I achieve with spring-data-mongodb without using annotations in my model classes.
class Role
{

    String id;
    String roleName;

}

class User {

    String id;
    String firstName;
    String lastName;

    List<Role> userRoles;
}

When I save User object I want to ensure that in MongoDB Role objects are stored as DBRefs instead of actual Role object graph.
My question is ─ without using annotations in my User and Role classes ─ how can I achieve this?
I searched the user's forums and could not find a way. That's why I'm posting my question here.
Thanks,
Kishore Veleti A.V.K.

A: Not sure if you ever figured this out, but you can use AspectJ to create an ITD (inter-type declaration) to weave in the annotations into the class without having to actually modify the original code.
For example, to turn your userRoles into a DBRef, you just need this aspect:
import org.springframework.data.mongodb.core.mapping.DBRef;
privileged aspect User_Mongo {
    declare @field: * User.userRoles : @DBRef;
}

This simply adds the @DBRef annotation to any fields within User named userRoles.  You can look at the AspectJ documentation for more information on field patterns and ITDs.


text:
Q: Kafka multiple tenancy consumer Hello we are starting to work with kafka with donetnet, we need to set up a multi tenancy environment. We've been looking at the references in the main github (confluent-kafka-dotnet). We noticed that the continuous consumer implementation is done using a backgroundservice, we would like to understand how we can use a model where we have one consumer per tenant.
Our questions are:

*

*If we adopt the model mentioned above, creating a backgroundservice per consumer, what problems are we subject to?

*If we have a structure of a backgroundservice and multiple tasks for each consumer, what problems are we subject to?
If you can help us, or have any suggestion/example of how we can do it, we would be very grateful for your support.


text:
Q: Using Open, Write and Close System Calls in C I'm having problems with very basic use of Open, Write and Close system calls in C, the following code is compiling but showing 0 bytes written to the file and no content being output into the file. What am I doing wrong?!
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

int main(void)
{
    int fd;
    ssize_t numWritten;

    if(fd = open("test.txt", O_RDWR | O_CREAT | O_APPEND) == - 1)
        printf("There has been an error opening the file\n");
    else
    {
        if(numWritten = write(fd, "Test Text\n", 10) == -1)
            printf("There has been an error writing to the file!\n");
        else
            printf("You have written %ld bytes\n", (long)numWritten);
    }

    close(fd);

    return 0;
}


text:
Q: Плавный ползунок прокрутке в слайдере Slick Slider Всегда использовал плагин http://kenwheeler.github.io/slick/ для создания слайдеров, но сейчас столкнулся с такой задачей - нужно сделать плавный ползуноок скролинга слайдов, как на скрине.

Подскажите пожалуйста, как это реализовать. Если покажите примером - будет вообще идеально.
У меня была мысль связать https://jqueryui.com/slider/ , но не знаю, как это сделать.


text:
Q: vscode json formatter: do not wrap json objects I'm working with avro .avsc schemas now and I like formatting in samples:
{
 "namespace": "example.avro",
 "type": "record",
 "name": "User",
 "fields": [
     {"name": "name", "type": "string"},
     {"name": "favorite_number",  "type": ["int", "null"]},
     {"name": "favorite_color", "type": ["string", "null"]}
 ]
}

I mean one-line field definitions {"name": "name", "type": "string"} specifically.
I'd like to edit and format my schemas in vscode, but it keeps wrapping fields like
 {
   "name": "name",
   "type": "string"
 }

I tried to configure default json formatter and with beautify extension in setting.json, but got no luck
   "[json]": {
        "editor.tabSize": 2,
        "editor.wordWrap": "off",
        "editor.defaultFormatter": "vscode.json-language-features",
        // "editor.defaultFormatter": "HookyQR.beautify"
    },
    "html.format.wrapAttributes": "preserve",

    "beautify.config": {
        "indent_size": 2,
        "indent_char": " ",
        "preserve_newlines": true,
        "space_in_paren": true,
        "space_in_empty_paren": true,
        "wrap_attributes": "preserve",
    },

A: The FracturedJson VSCode extension might be useful for you.  (I'm the author. It's open source under the MIT license.)
The basic idea is that objects and arrays are written on single lines, as long as they're not too long and not too deeply nested.
There's a browser version if you'd like to play around with the capabilities before downloading the extension.


text:
Q: How can I generate a signed URL for a file in cloud storage that uses the static site URL? Say I have a domain, media.coolsite.com. Also say I have a bucket in Google Cloud Storage with the same name. I also have the cname setup properly, so that when I visit media.coolsite.com in the browser, it renders index.html in the bucket.
The bucket also contains a file 01.mp3 that I am trying to get a signed URL for. I can do this with the following code:
gcloud = Gcloud.new
storage = gcloud.storage
bucket = storage.bucket 'media.coolsite.com'
file = bucket.file '01.mp3'
signed_url = file.signed_url

This returns a URL like so:
https://storage.googleapis.com/media.coolstuff.com/01.mp3?GoogleAccessId=...&Expires=...etc...
But what I would like is a URL like this:
http://media.coolstuff.com/01.mp3?GoogleAccessId=...&Expires=...etc...
Note the different host: media.coolstuff.com instead of storage.googleapis.com.
How can I do this using the gcloud gem?


text:
Q: How to use an Azure Key Vault rolling certificate with OpenIddict? IdentityServer allows you to register a ISigningCredentialStore and a IValidationKeysStore, which in turn enables dynamic loading of certificates from, for example, Azure Key Vault because the certificate store is called each time which handles lifetime, caching, updating etc.
What is the equivalent to achieve the same in OpenIddict?


text:
Q: RxJava2 compile error "cannot find symbol method body()" I got an compile error in that part of code
mCompositeDisposable.add(
            Flowable.just(Boolean.TRUE)
                .flatMap( ignored ->
                        service.getPosts(offset,limit, PreferencesUtils.getAccessTokenKey()) )
                .subscribeOn(Schedulers.io())
                .doOnNext(response -> {
                    if (!response.isSuccessful()) throw new IllegalAccessException();
                })
                .retryWhen( error -> error.flatMap( f -> {
                    if(f instanceof IllegalAccessException)
                        return Helper.refreshToken();
                    else
                        return Flowable.error(f);
                }))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        successResponse -> {
                            if (!successResponse.body().isEmpty()) {
                                mView.showNewsFeedItems(successResponse.body());
                            }
                        },
                        failResponse -> { mView.showError(); }
            ));

This line of code IDE recognize well and doesn't give any exceptions or warnings
successResponse has type Response<List<Object>> but compiler doesn't think as well and give me error: cannot find symbol method body() i can't find alike questions & answers how to solve this problem. I will be very grateful for any information about this problem!
if (!successResponse.body().isEmpty()) {
                                mView.showNewsFeedItems(successResponse.body());
                            }
Update:
Everything works fine when i use Observer (with Observable), but it's costly
 .subscribe(new Observer<Response<List<NewsFeed>>>() { // lambda doesnt work properly here (in progress)
                @Override public void onSubscribe(Disposable s) {}
                @Override public void onNext(Response<List<NewsFeed>> feeds) {if(!feeds.body().isEmpty()) mView.showNewsFeedItems(feeds.body());}
                @Override public void onError(Throwable e) {}
                @Override public void onComplete() {}
            });

A: Try to use Single.just() if you guaranty need this emission. It will bring you back Disposable which can be added inside of CompositeDisposable. Subscribe to Flowable returns Subscription, not Disposable.


text:
Q: EDI conversion using mule I would like to know if there is a way to convert EDI files to other format in mule. I have a requirement to convert from EDI to XML . I am able to do it using smooks plugin withing Mule. Wondering if there is more cleaner way to do it inside Mule, something like using datamapper. Please suggest.

A: I'm afraid the smooks comunity extension looks pretty much abandoned, however you could easily transform using a Java transformer like this:
public abstract class EdiSmooksTransformer extends AbstractTransformer
{
    private Smooks smooks;

    public EdiSmooksTransformer() throws IOException, SAXException
    {
        smooks = new Smooks();
        smooks.setReaderConfig(new EDIReaderConfigurator("MY_EDI_CONFIG_FILE_PATH_HERE"));
    }

    @Override
    protected Object doTransform(Object src, String enc) throws TransformerException
    {
        StringResult stringResult = new StringResult();
        smooks.filterSource(new StreamSource((BufferedReader) src), stringResult);
        return stringResult.getResult();
    }

}


text:
Q: When I display image, I can't use colors anymore openGL When I open and display an image in openGL, all colors on screen (except image's) suddenly turn into black and I can't use another color to draw anymore.
It's my colorful button on screen
    void drawButton(int x1,int y1,int x2,int y2,int r,int g,int b)
{
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    glColor3f(r,g,b);
    glBegin(GL_QUADS);
    glVertex2f(x1,y1);
    glVertex2f(x2,y1);
    glVertex2f(x2,y2);
    glVertex2f(x1,y2);
    glEnd();
    glFlush();
    glutSwapBuffers();
}

And here's display image function
void display_image(char* file_name)
{
    GLuint texture_id=loadIm(file_name);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture_id);
glLoadIdentity();
glColor3f(1, 1, 1);
glFrontFace(GL_CCW);
glCullFace(GL_FRONT);
glBindTexture(GL_TEXTURE_2D, texture_id);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glBegin(GL_QUADS);
glTexCoord2f(0,1); glVertex2f(0,    0.0);
glTexCoord2f(0,0); glVertex2f(0,  wh);
glTexCoord2f(1,0); glVertex2f(ww,wh);
glTexCoord2f(1,1); glVertex2f(ww, 0.0);
glEnd();
glFlush();
glutSwapBuffers();
drawArea();

}

EDIT: glDisable(GL_TEXTURE_2D)

A: OpenGL is a state machine. This means when one enables GL_TEXTURE_2D to draw with textures, this has to be disabled afterwards to render with colors only. Calling glDisable(GL_TEXTURE_2D); before starting to render the colored polygon should fix the problem.


text:
Q: Using JOIN on three tables - MySQL My tables are arranged as follows. I am only showing one value in each of them for simplicity.
Table: Events
Event_ID   Event_Title
1          Broad Street Gathering

Table: EventUserTags
User_ID  Event_ID
10092    1

Table: UserLinks
User_1  User_2
10092   29809

If the ID of the current user is 10092:
1) Select ID's from UserLinks where User_1 or User_2 is 10092, (if User_1 is 10092, then select User_2)
2) Select the Event_ID's from EventUserTags using the User_ID's (obtained above)
3) Select the Event_Title from Events using the Event_ID's (obtained above)
So, for example:
If the logged-in user has an ID of 10092, this query will obtain the Event_Title "Broad Street Gathering"
So far, I have not had any luck. Any help whatsoever is appreciated
A user from this website recommended using:
SELECT
   Event_Title,
   Event_ID,
   User_1,
   User_2
    FROM
   Events
   NATURAL JOIN EventUserTags
   JOIN UserLinks ON (
          User_ID = User_1 AND User_2 = $id
          OR User_ID = User_2 AND User_1 = $id
       )

A: The problem here is that sometimes you're joining tables using User_1 and sometimes User_2, which is not an easy concept to express in a join condition.
Instead, you can do two separate SELECTs and then UNION them together to get a single result set.
 SELECT UL.User_1 AS User_ID, EUT.Event_ID, E.Event_Title
 FROM UserLinks UL
      INNER JOIN EventUserTags EUT ON UL.User_1 = EUT.User_ID
      INNER JOIN Events E ON E.Event_ID = EUT_Event_ID
 WHERE UL.User_1 = :user_id
 UNION ALL
 SELECT UL.User_2 AS User_ID, EUT.Event_ID, E.Event_Title
 FROM UserLinks UL
      INNER JOIN EventUserTags EUT ON UL.User_2 = EUT.User_ID
      INNER JOIN Events E ON E.Event_ID = EUT_Event_ID
 WHERE UL.User_2 = :user_id

A: I really don't understand the setup of your UserLinks table.
You really should have:
user_id  link
1        10092
2        29809

Then you could very easily use:
SELECT e.* tags.*, user.*
FROM Events e
JOIN EventUserTags tags
ON tags.event_id=e.event_id
JOIN UserLinks user
ON user.user_id=tags.user_id
WHERE user.user_id=$id

A: SELECT e.Event_Title, e.Event_ID,
       COALESCE(ul1.User_1, ul2.User_1) AS User_1,
       COALESCE(ul1.User_2, ul2.User_2) AS User_2
    FROM EventUserTags eut
        INNER JOIN Events e
            ON eut.Event_ID = e.Event_ID
        LEFT JOIN UserLinks ul1
            ON eut.User_ID = ul1.User_1
        LEFT JOIN UserLinks ul2
            ON eut.User_ID = ul2.User_2
    WHERE eut.User_ID = $id
        AND (ul1.User_1 IS NOT NULL OR ul2.User_2 IS NOT NULL)


text:
Q: Instantiating a queue as a class member in C++ Suppose I need to have a class which wraps a priority queue of other objects (meaning the queue is a member of the class), and additionally gives it some extra functions.
I am not quite sure what the best way is to define that vector and, mainly, how to instantiate it.
Currently I have something like this in the header file:
// in SomeClass.h:
class SomeClass
{
    public:
        SomeClass(); // constructor
            // other methods
    private:
        std::priority_queue<OtherClass> queue;
};

while the source file is something like this:
// in SomeClass.cpp
SomeClass::SomeClass():
    queue() // removed the constructor, no need to explicitly call it
    {}

// other methods

EDIT: removed the call, per Ray's answer.

A: Just write:
SomeClass::SomeClass():
    queue() { }

C++ knows to call the constructor automatically from there with no arguments.

A: Your member is an instance, but what you're doing is trying to initialize that instance with a pointer to a newly allocated instance.  Either leave the initialization empty (as Ray pointed out) or leave it out of the initialization list of the constructor completely.
SomeClass::SomeClass() {}

has the same queue initialized as
SomeClass::SomeClass() : queue() {}

If you really want to allocate it on the heap using new, then your member needs to be declared in the header as:
private:
            std::priority_queue<OtherClass>* queue;

But I would recommend against doing that, unless you plan to let some other class take over ownership of the same instance of queue later and don't want the destructor of SomeClass to free it.

A: Building on Michel's example, if you really want that pq allocated on heap you will be better off with
`boost::smart_ptr<std::priority_queue<OtherClass> > queue;`

or as a last resort if you don't have access to boost
`std::auto_ptr<std::priority_queue<OtherClass> > queue;`


text:
Q: GetAsyncKeyState(VK_RETURN) incorrectly evaluating to true I'm writing a simple program that records click positions and intervals between clicks. During the setup, the user presses 'ENTER' to add a new position to the list, and 'ESC' once they are done entering positions.
Some weird behavior I am getting is that other key presses cause else if (GetAsyncKeyState(VK_RETURN)) to evaluate as true incorrectly. My guess was that the 'ENTER' to end a std::cin was lingering in the buffer and causing that true, however I thought std::cin.get() and std::cin.ignore would have fixed that.
Why is it that keys other than 'ENTER' cause (GetAsyncKeyState(VK_RETURN)) to evaluate to true?
void initialSetup() {

    int temp = 0;
    char input;

    std::cout << "Unique sleep times? (y/n):  ";
    std::cin >> input;
    std::cin.get();
    std::cin.ignore(100, '\n'); // discards the input buffer

    // Ask the user for a sleep each time, or use the same
    if (input == 'y') {
        uniqueSleepBetweenClicks = true;
    }
    else {
        // Sleep times are constant after each click
        std::cout << "Constant sleep time between clicks in ms:  ";
        std::cin >> constSleepBetweenClicks;
        std::cin.get();
        std::cin.ignore(100, '\n'); // discards the input buffer
    }

    std::cout << endl;
    std::cout << "***********************************" << endl;
    std::cout << "* 'ENTER' to set new position     *" << endl;
    std::cout << "* 'ESC' when done                 *" << endl;
    std::cout << "***********************************" << endl << endl;

    // Add new clicks to the sequence
    while (_getch()){

        Click click;

        if (GetAsyncKeyState(VK_ESCAPE)) {
            // Escape keypress ends adding new clicks
            break;
        }
        else if (GetAsyncKeyState(VK_RETURN)) {

            // Set the click position
            GetCursorPos(&click.point);
            std::cout << "Position set to (" << click.point.x << "," << click.point.y << ") " << endl;

            if (uniqueSleepBetweenClicks) {
                std::cout << "Sleep time in ms: ";
                std::cin >> click.sleep;
                std::cin.get();
                std::cin.ignore(100, '\n'); // discards the input buffer
            }
            else {
                click.sleep = constSleepBetweenClicks;
            }

            // Add to the list
            clickList.push_back(click);

        }
    }
    return;
}

EDIT1: Replacing VK_RETURN with VK_SPACE makes the program work perfectly. The issue just seems to be with the ENTER key.

A: You are not checking the return value correctly, it does not return a BOOL! GetAsyncKeyState(VK_RETURN) < 0 or GetAsyncKeyState(VK_RETURN) > 0 depending on what you are checking for. Either way, GetAsyncKeyState is not the correct approach for a console application.
Use ReadConsoleInput to handle input in a console.
If you want to capture input even when the user is working in another application you should use hooks to capture mouse and keyboard events.


text:
Q: How to timeout a fuction in python I am calling a function named as func for each sentence in my corpus as follows in python.
count =0
for sentence in sentences:
   count += 1
   results.append(func(sentence))

I want to pass the sentences that takes too long to process by using timeout (e.g., timeout after 30 seconds and print the sentence number).
I tried to use the solution mentioned in: Timeout on a function call and timeout-decorator library as well.
However, both of the solutions returned me the same error mentioned below.
signal.signal(signal.SIGALRM, handler)

AttributeError: module 'signal' has no attribute 'SIGALRM'

Is there a way to perform timeout in python 3? Please let me know if further details are needed.

A: The signal package is part of UNIX/Linux package and needs to be installed.
If you are on windows check this out
https://github.com/Unity-Technologies/ml-agents/issues/7


text:
Q: Polymorphism thing about a member variable I always think I know the Polymorphism until I meet below example.
I have two classes, Father and Son. Code as follows:
Father:
public class Father
{
    public String name = "father";
    public virtual void dosth()
    {
        Console.WriteLine(name);
    }
}

Son:
public class Son : Father
{
     public String name = "son";
     public override void dosth()
     {
          Console.WriteLine(name);
     }
}

And I Call them:
static void Main(string[] args)
{
    Father p = new Son();
    Console.WriteLine(p.GetType()); //print son
    p.dosth();                      //print son
    Console.WriteLine(p.name);      //print father
}

As I think, variable p points to a son object, so first, Console will print "Son" Type. And I'm right.
Then p.dosth() will call the son's dosth(), So it will print "son". And I'm right again.
Last, p.name should be "son", too. But, this time, I'm wrong. It prints "father".
I can't understand that p variable's type is son, why it still use the father's member?


text:
Q: Error while deleting Netbeans, NetBeans leaves in windows 10
dear collegues.
while removing neatbeans, I got an exception like this. I don't know how to overcome with it. I I click on Yes, netBeans asks to uninstall the system, While clicking on Uninstall, the system removes, in actually the netbeans leaves.


text:
Q: RAR files not downloading correctly using requests module Recently, I was creating an installer for my project. It involves downloading a RAR file from my server, unRAR-ing it and putting those folders into the correct locations.
Once it's downloaded, the program is supposed to unRAR it, but instead it gives me an error in the console: Corrupt header of file.
I should note that this error is coming from the unRAR program bundled with WinRAR.
I also tried opening the file using the GUI of WinRAR, and it gave the same error.
I'm assuming while it's being downloaded, it's being corrupted somehow?
Also, when I download it manually using a web browser, it downloads fine.
I've tried this code:
KALI = "URL CENSORED"
kali_res = requests.get(KALI, stream=True)
for chunk in kali_res.iter_content(chunk_size=128):
  open(file_path, "wb").write(chunk)

..but it still gives the same error.
Could someone please help?

A: You keep re-opening the file for every chunk.
Not only does this leak file descriptors, it also means you keep overwriting the file.
Try this instead:
KALI = "URL CENSORED"
kali_res = requests.get(KALI, stream=True)
with open(file_path, "wb") as outfile:
    for chunk in kali_res.iter_content(chunk_size=128):
        outfile.write(chunk)


text:
Q: Is there a better way to count punctuation in a sentence? I want to count 'end sentences' e.g. full stops, exclamation marks, and question marks.
I have written a little loop to do this, but I was wondering if there is a better way. Not allowed to use built-in functions.
for line in textContent:
    numberOfFullStops += line.count(".")
    numberOfQuestionMarks += line.count("?")
    numberOfQuestionMarks += line.count("!")

numberOfSentences = numberOfFullStops + numberOfQuestionMarks + numberOfExclamationMarks

A: Assuming you want to count terminal punctuation in one sentence, we can produce a dictionary of (character, count) pairs by looping over the characters of each string and filtering the punctuations.
Demo
Here are three options presented top-down with intermediate- to beginner-level data structures:
import collections as ct

sentence = "Here is a sentence, and it has some exclamations!!"
terminals = ".?!"

# Option 1 - Counter and Dictionary Comprehension
cd = {c:val for c, val in ct.Counter(sentence).items() if c in terminals}
cd
# Out: {'!': 2}

# Option 2 - Default Dictionary
dd = ct.defaultdict(int)
for c in sentence:
    if c in terminals:
        dd[c] += 1
dd
# Out: defaultdict(int, {'!': 2})

# Option 3 - Regular Dictionary
d = {}
for c in sentence:
    if c in terminals:
        if c not in d:
            d[c] = 0
        d[c] += 1
d
# Out: {'!': 2}

To extend further, for a list of separate sentences, loop around one of the latter options.
for sentence in sentences:
    # add option here

Note: to sum the total punctuations per sentence, total the dict.values(), e.g. sum(cd.values()).

Update: assuming you want to split a sentence by terminal punctutation, use regular expressions:
import re

line = "Here is a string of sentences.  How do we split them up?  Try regular expressions!!!"

# Option - Regular Expression and List Comprehension
pattern = r"[.?!]"
sentences = [sentence for sentence in re.split(pattern, line) if sentence]
sentences
# Out: ['Here is a string of sentences', '  How do we split them up', '  Try regular expressions']

len(sentences)
# Out: 3

Notice line has 5 terminals, but only 3 sentences.  Thus regex is a more reliable approach.
References

*

*collections.Counter

*collections.defaultdict

*re.split

*List comprehension


text:
Q: Freeglut fgInitGL2: fghGenBuffers is NULL On the glutCreateWindow this message appears - what can cause such problem?
Here the code that i have:
#include "pch.h"
#include <stdio.h>
#include "include/glew.h"
#include "include/glut.h"
#include "include/freeglut.h"
#include "Mathematics.h"

GLuint VBO;

static void RenderSceneCB()
{
    glClear(GL_COLOR_BUFFER_BIT);

    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

    glDrawArrays(GL_TRIANGLES, 0, 1);

    glDisableVertexAttribArray(0);

    glutSwapBuffers();
}

static void InitializeGlutCallbacks()
{
    glutDisplayFunc(RenderSceneCB);
}

static void CreateVertexBuffer()
{
    Vector3f Vertices[1];
    Vertices[0] = Vector3f(-1.0f, -1.0f, 0.0f);

    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
    glutInitWindowSize(1024, 768);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("My");

    // Must be done after glut is initialized!
    GLenum res = glewInit();
    if (res != GLEW_OK) {
        fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));
        return 1;
    } else {
        printf("Glew Inited");
    }

    InitializeGlutCallbacks();

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    CreateVertexBuffer();

    glutMainLoop();

    return 0;
}

A: I just had the same problem, and i found this answer

It took me some time, but the cause of the problem was in the
  hardware. I was running on a virtual machine (VMware) and although the
  specifications said that it supported OpenGL up to 2.1 I found out
  that it doesn't support OpenGL at all.
My solution was to take an old machine, install Windows on it, and
  copy all files. It compiled and runs as smooth as a can.
If anyone else runs into the same problem I can advise to get it
  working on a native installation before virtualising. It can safe you
  a lot of time.

by martinvb
as fare as i know it's an hardware.


text:
Q: How to send google Appscript Error logs to slack I have different appscript projects which have triggers to run every hour.
I would like appscript to be sending the error logs to slack instead of email.
Any idea of how to achieve this?

A: The simplest way would be using a try ... catch on your code that calls the Slack API when it catches an exception.
Another (more complex) way would be by monitoring the logs using the Google Cloud Logging API or the Google Cloud Error Reporting API.


text:
Q: Update stats as default or with a sample value I have been reading many blogs on this and cannot come to a conclusion on update stats for VLDB;s
On SQL server 2012Sp4 and 2014Sp2 we have databases over 15 TB with 4-5 tables covering most of the sizes on avg 2-3 TB's
Now performing index maintenance is causing a lot of problems during the weekend window.

*

*We are not doing ant index rebuilds/re-organize as of now

*Update stats is done for those DB's every weekend once
For tables with over 10 billions of rows, we had update stats on indexes with sample of 20% and 30%. As per my knowledge, stats would not be going parallel operation unless its full scan or specified MAXDOP option which is available on higher versions of what i am currently on.
So the problem is update stats with that sample rate runs and almost increasing its run times on avg. 9-10 hours and that causes issues with other processes running due to window exceeding as assigned to DBA work for maintenance .
However if we just run update stats on index without any sample they will just complete in 10-20 mins. I see the rows sampled would be less here and can have some impact on performance.
So what are my best options as of now if i run without sample? Would that worse the performance of servers? Is there a better way of achieving this?
All databases have auto update stats ON [SYNC]
Thanks


text:
Q: How can I sort my array alphabetically? I'm using node.js. I want to sort this array by their names, it has the following format:
[["Kingston upon Thames",36.9],["Croydon",36.8],["Bromley",40.1],["Hounslow",35.4],["Ealing",35.9],["Havering",40.3],["Hillingdon",36.2],["Harrow",37.9],["Brent",35.4],["Barnet",37.1],["Lambeth",34.2],["Southwark",34.1],["Lewisham",34.8],["Greenwich",34.9],["Bexley",38.9],["Enfield",36.1],["Waltham Forest",34.7],["Redbridge",35.7],["Sutton",38.6],["Richmond upon Thames",38.5],["Merton",36.4],["Wandsworth",34.8],["Hammersmith and Fulham",35.4],["Kensington and Chelsea",38.9],["Westminster",37.4],["Camden",36],["Tower Hamlets",31.2],["Islington",34.6],["Hackney",32.8],["Haringey",34.8],["Newham",31.7],["Barking and Dagenham",32.9],["City of London",41.9]]

I want to sort it like ["Barking and Dagenham",32.9],["Barnet",37.1],["Bexley",38.9],etc

A: Just take the elements, on which you like to apply sort.
array.sort(function (a, b) {
    return a[0].localeCompare(b[0]);
});

Working example:

var array = [["Kingston upon Thames",36.9],["Croydon",36.8],["Bromley",40.1],["Hounslow",35.4],["Ealing",35.9],["Havering",40.3],["Hillingdon",36.2],["Harrow",37.9],["Brent",35.4],["Barnet",37.1],["Lambeth",34.2],["Southwark",34.1],["Lewisham",34.8],["Greenwich",34.9],["Bexley",38.9],["Enfield",36.1],["Waltham Forest",34.7],["Redbridge",35.7],["Sutton",38.6],["Richmond upon Thames",38.5],["Merton",36.4],["Wandsworth",34.8],["Hammersmith and Fulham",35.4],["Kensington and Chelsea",38.9],["Westminster",37.4],["Camden",36],["Tower Hamlets",31.2],["Islington",34.6],["Hackney",32.8],["Haringey",34.8],["Newham",31.7],["Barking and Dagenham",32.9],["City of London",41.9]];

array.sort(function (a, b) {
    return a[0].localeCompare(b[0]);
});

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

A: Use Array.prototype.sort().

a = [["Kingston upon Thames",36.9],["Croydon",36.8],["Bromley",40.1],["Hounslow",35.4],["Ealing",35.9],["Havering",40.3],["Hillingdon",36.2],["Harrow",37.9],["Brent",35.4],["Barnet",37.1],["Lambeth",34.2],["Southwark",34.1],["Lewisham",34.8],["Greenwich",34.9],["Bexley",38.9],["Enfield",36.1],["Waltham Forest",34.7],["Redbridge",35.7],["Sutton",38.6],["Richmond upon Thames",38.5],["Merton",36.4],["Wandsworth",34.8],["Hammersmith and Fulham",35.4],["Kensington and Chelsea",38.9],["Westminster",37.4],["Camden",36],["Tower Hamlets",31.2],["Islington",34.6],["Hackney",32.8],["Haringey",34.8],["Newham",31.7],["Barking and Dagenham",32.9],["City of London",41.9]];
a.sort(function(a, b){
  var aName = a[0].toLowerCase();
  var bName = b[0].toLowerCase();
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
});
console.log(a);

A: This way may not be efficient, but it will serve your purpose.
var myArray =[["Kingston upon Thames",36.9],["Croydon",36.8],["Bromley",40.1],["Hounslow",35.4],["Ealing",35.9],["Havering",40.3],["Hillingdon",36.2],["Harrow",37.9],["Brent",35.4],["Barnet",37.1],["Lambeth",34.2],["Southwark",34.1],["Lewisham",34.8],["Greenwich",34.9],["Bexley",38.9],["Enfield",36.1],["Waltham Forest",34.7],["Redbridge",35.7],["Sutton",38.6],["Richmond upon Thames",38.5],["Merton",36.4],["Wandsworth",34.8],["Hammersmith and Fulham",35.4],["Kensington and Chelsea",38.9],["Westminster",37.4],["Camden",36],["Tower Hamlets",31.2],["Islington",34.6],["Hackney",32.8],["Haringey",34.8],["Newham",31.7],["Barking and Dagenham",32.9],["City of London",41.9]]

// Convert array of arrays to single json object
var _tempArray = [];
for(var i =0;i<myArray.length;i++){
_tempArray.push({
    "name":myArray[i][0],
    "val":myArray[i][1]
  })
}

//sort it
var sortedArray = _tempArray.sort(function(a,b){
   return a.name >b.name?1:-1
})
console.log(sortedArray);

jsfiddle for working model


text:
Q: How is this asymptotic expansion of an integral calculated? I am strongly impressed by this example from New in 13
as =
  AsymptoticIntegrate[
    (t^10 + 3) Exp[I λ (t^5 + t + 1)],
    {t, -2, 2}, {λ, Infinity, 2}
  ]

(250400/(531441 λ^2) + (1027 I)/(81 λ)) Cos[33 λ] + (250400/(531441 λ^2) - (1027 I)/(81 λ)) Cos[35 λ] + (-((250400 I)/(531441 λ^2)) + 1027/(81 λ)) Sin[33 λ] + ((250400 I)/(531441 λ^2) + 1027/(81 λ)) Sin[35 λ]

Indeed,
N[as /. λ -> 20]

0.511368 + 1.14401 I

is in a good accordance with
NIntegrate[
  (t^10 + 3) Exp[I*λ (t^5 + t + 1)] /. λ -> 20,
  {t, -2, 2}
]

0.511551 + 1.14442 I

I am interested how AsymptoticIntegrate derives it. Usually the command works as Series@Integrate, but in the case under consideration
Integrate[
  (t^10 + 3) Exp[I*λ (t^5 + t + 1)],
  {t, -2, 2},
  Assumptions -> λ > 0
]

fails and returns the input.
Is the Laplace method (with generalizations) really implemented in Mathematica? I clearly understand that this is proprietary knowledge of Wolfram Research Inc, but I hope to see a general answer; I do not expect implementation details.

A: Too long for a comment. My play with modifications of the example under consideration,
e.g.
AsymptoticIntegrate[(t^2 + 2)*Sinh[t]*Cos[2 t]*
Exp[I \[Lambda] (t^12 + 2*t + 1)], {t, -2, Infinity}, {\[Lambda],Infinity, 1}]

-(((2 + 1/6^(2/11)) E^((I \[Pi])/4 +  I (1 - 2^(10/11)/3^(1/11) + 1/(6 6^(1/11))) \[Lambda]) Sqrt[\[Pi]/ 11] Cos[2^(10/11)/3^(1/11)] Sinh[1/6^(1/11)])/( 6^(1/22) Sqrt[\[Lambda]]))

and
AsymptoticIntegrate[(t^2 + 2)*Sinh[t]*Cos[2 t]*
Exp[I \[Lambda] (Pi*t^12 + 2*t + 1)], {t, -2, 5}, {\[Lambda],Infinity, 3}]

which output is too long to be quoted here,
suggests that the asymptitic expansion for the integral $$\int\limits_a^b Q(t)e^{i\lambda P(t)}\,dt $$ as $\lambda \to \infty$,
where $Q(t)$ is a quasi-polynomial over the reals (see Russian edition of Wiki
which is better on this topic than English one) and $P(t)$ is a polynomial over the reals and the range of the integration may be infinite,
is currently implemented in Mathematica. This is a special case of the method of stationary phase.


text:
Q: Android google map Api sha1 and package is error API_KEY I tried but sha-1;my package is not accepted
Error is [Your input was invalid].
This is my sha-1

AndroidManifest.xml
<meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyBxxa0zIyuP2OJXldb-FUoGSSDcfbryVbA"/>

A: I got Sha1 and packege
I got Api key


text:
Q: Is the irrationality measure function surjective? Let $\beta>2$ be a real number, is it always possible to construct a real number $x$ such that $\mu(x)=\beta$? where $\mu$ denotes the irrationality measure.

The problem as I see it is to find $(a_n)_n$ an unbounded sequence of positive integers such that $\limsup \ln_{q_n}(q_{n+1})=\beta-1$ where $q_n$ is the numerator of the $n$-th convergent of $[a_0;a_1,a_2,\dots]$. But I was not able to continue.

A: Of course it is possible. Irrationality measure more than 2 means having continued fraction with terms that grow mighty fast, so we'll have more than enough freedom for every next term.
Since $q_{n+1}=a_{n+1}q_n+q_{n-1}$, we might simply choose
$$a_{n+1}=\left\lceil\left(q_n^{\beta-1}-q_{n-1}\over q_n\right)^{1/(\beta-1)}\right\rceil$$
As $n$ and $q_n\to\infty$, so does $a_{n+1}$, which quickly makes the rounding error negligible.


text: Q: Is it possible to create .bak file of a database in sql server with the .mdf and .ldf file of the the database? Hi So I put myself in a situation where I can no longer access ms sql server in a vm that I have created. My question is if it is possible to create  a backup file(.bak) outside of the sql server by perhaps levering the databases .ldf and/or .mdf file?


text:
Q: How to search for endNodes, that are in one relationship, but not another in Neo4J Java I have a initial node of user, that can own multiple items and that items can be also organized into groups (each into multiple groups). Therefore the user can have two corresponding relationships — owning the group and owning the item. The items have an extra relationship to the groups.
I would like to find the items, that are owned by the user, but are not any group.
Is there a way how to select these item in one traversal method, or should I get all items owned by the user and then iterate over them to find out these without the relationship to groups?
Edit: I am sorry, that my question was not clear enough. By the traversal method I meant using the Neo4j Traversal Framework in Java. For example:
TraversalDescription td = db.traversalDescription()
    .breadthFirst()
    .relationships(OWNS, Direction.BOTH)
     //IS THERE A WAY HOW TO SAY THE NEXT RELATIONSHIP (EDGE) DOES NOT EXIST?
    .evaluator(Evaluators.excludeStartPosition())
    .uniqueness(Uniqueness.NODE_GLOBAL);

Traverser t = td.traverse(userNode);
    for (Path p : t) {
        //OR: SHOULD I LOOP TROUGH ALL THE RELATIONSHIPS OF THE END NODE - ITEM
        System.out.println(p.endNode().getProperty("name"));
    }

The two comments in the code are the places where I expected either a method for the traversalDescription or iterating through all relationships of the endNodes.

A: In Cypher:
MATCH (me:Person{name:'me'})-[:OWNS]->(i:Item)
WHERE NOT (i)-[:PART_OF]->()  // not part of a group
RETURN i

In Java API:
Node me = graphDb.findNode(Label.label("Person"), "name", "me");
Iterable<Relationship> owns = me.getRelationships(RelationshipType.withName("OWNS"), Direction.OUTGOING);
Stream<Node> nodes= StreamSupport.stream(owns.spliterator, false)
    .filter(r -> r.getEndNode().hasRelationship(RelationshipType.withName("PART_OF"),OUTGOING))
    .map(r -> r.getEndNode());


text:
Q: Reading a file from a developer controlled account I simply want to read a Google drive spreadsheet owned by a account controlled by the developer. So I don't want my users to have to login to anything. I just need to obtain this file from hard coded credentials and read it.
It used to work very easy with drive v1 but since that doesn't seem to work anymore we are forced to go to drive v2. I haven't even found where to start.

A: The answer to how to use a developer controlled account is documented here:
https://developers.google.com/drive/web/service-accounts


text:
Q: How to call a javascript function from code-behind of a partially loaded aspx page I have an asp.net application and I use jquery's .load function to load content into a specific div like so:
 $('#pnl').load('/Panel.aspx #panel', loadLogs());

From the Panel.aspx page I populate some dropdowns in the code-behind load event, and from there I have some javascript functions(in a separate javascript file) that display text files based on the content of the dropdowns, which is controlled by the change events on the dropdowns. I am having an issue of when the page is loaded, the dropdowns are populated but I need to actually click on one of them to get the files to display. I have tried to call the javascript functions from the load event of Panel.aspx with    Page.ClientScript.RegisterClientScriptBlock and they are not firing. I have also tried firing it from  window.onload or $(document).ready from the javascript file and it is still not working.
Any suggestions for how I can get this done?

A: try something like this
If you Used Update Panels Then You can Use:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "javascriptFunction();", true);

Other Wise You can Use
ClientScript.RegisterStartupScript
        (GetType(),Guid.NewGuid().ToString(), "javascriptFunction();",true);


text:
Q: How to find different size icon for a certain app on the itunes app store? I need to create a widget where different size of an apps icon is needed, how do I find them in different sizes? The only thing I have is the itunes app link like the following
http://itunes.apple.com/us/app/yelp/id284910350?mt=8

A: *

*Use a Regular Expression to find the
URL of the image, in this case,
http://a1.phobos.apple.com/us/r1000/012/Purple/42/80/fc/mzi.dqbtrgug.175x175-75.jpg.

*Download the data using NSURLConnection.

*Use UIImage to resize the image.


text:
Q: Union two tables with partially overlapping column and returning rows with non-null column values if exists I have following table in postgres 11. I am joining following two tables using 'union'
Table1
col1    col2        col3    col4
4894775 NCT00000172 drug    galantamine
4894772 NCT00000174 drug    rivastigmine
4895618 NCT00000241 drug    flupenthixol

Table2
col1    col2        col3    col4            col5            col6
4894775 NCT00000172 drug    galantamine     galantamine     {N06DA}
4895618 NCT00000241 drug    flupenthixol    flupenthixol    {N05AF}

I would like to have the two tables joined such that whenever col5 and col6 are not null then pick those rows else pick the null rows.
I have tried following query so far:
select distinct on (col1, col2, col3, col4, col5)
                    col1,
                    col2,
                    col3,
                    col4,
                    coalesce(b.col5, a.col5),
                    coalesce(b.col6, a.col6),
             from (
SELECT
                    col1,
                    col2,
                    col3,
                    col4,
                    null as col5,
                    null as col6
from table1 a

union

select              col1,
                    col2,
                    col3,
                    col4,
                    col5,
                    col6
from  table2 b
order by col1

The desired output is:
col1    col2        col3    col4            col5            col6
4894775 NCT00000172 drug    galantamine     galantamine     {N06DA}
4894772 NCT00000174 drug    rivastigmine    (null)          (null)
4895618 NCT00000241 drug    flupenthixol    flupenthixol    {N05AF}

A: It looks like you want a left join:
select col1, col2, col3, col4, t2.col5, t2.col6
from table1 t1
left join table2 t2 using(col1, col2, col3, col4)

If there may be "missing" rows in both tables, then you can just change the left join to a full join.


text:
Q: Does Wonder Woman need to use her bracers? Does Wonder Woman need to use her bracers to deflect attacks or could she simply withstand the attacks she normally deflects, e.g. bullets? Does she use the bracers just as a polite formality?

A: The characterization of Wonder Woman has varied widely over the decades since her creation. In the beginning of the character's existence, she was NOT bulletproof and her bracelets were necessary to deflect bullets.

Wonder Woman was created by the American psychologist and writer William Moulton Marston. The character first appeared in All Star Comics #8 in December 1941 and first cover-dated on Sensation Comics #1, January 1942. REF: Wikipedia - Wonder Woman

*

*In her second comic cover appearance she was seen deflecting bullets fired from machine guns... Since she was not bullet-proof in 1941 she absolutely needed to deflect bullets with her bracelets. Reading through many of her early adventures, Wonder Woman seemed to always be using this particular power to defend innocents from enemy fire in addition to herself.

*Note in this series of panels from a 1945 Wonder Woman Christmas tale from Sensation Comics #38! She deflects bullets to protect herself from being shot at. But later in the same page, a bomb is detonated and everyone except her is knocked down in the explosion. Her hands are tied behind her back with her lasso and she did not deflect anything. Even then she was a tough customer!

*In the initial character creation, the bracelets were used to deflect bullets as the ultimate sign of superior martial skill and hand-eye coordination. "Bullets and Bracelets" became a signature feat in the minds of the public at large when Wonder Woman was portrayed by Lynda Carter on television in the mid 1970s.

Diana is depicted as a masterful athlete, acrobat, fighter and strategist, trained and experienced in many ancient and modern forms of armed and unarmed combat, including exclusively Amazonian martial arts. In some versions, her mother trained her, as Wonder Girl, for a future career as Wonder Woman.
From the beginning, she is portrayed as highly skilled in using her Amazon bracelets to stop bullets and in wielding her golden lasso. Batman once called her the "best melee fighter in the world". The modern version of the character is known to use lethal force when she deems it necessary. In The New 52 continuity, her superior combat skills are the product of her training with Ares in her childhood.

*

*In her latest incarnations as an avatar/goddess of the Greek mythos in DC Comics New 52, able to fight Superman to a standstill, she may be simply tough enough to resist small arms fire outright.

*However, her bracelets are god-forged weapons, nigh-indestructible and as a result can be used to deflect far more powerful attacks as well.

A: In Justice League Unlimited she gets turned into a pig and Batman and Zatanna have to save her and she gets caught in a butchery where pigs are slaughtered and almost gets shot by a guy and barely manages to lift her now pig like bracers up to stop the bullet.

They make it look as if she would have been shot in this form if she didn't use her bracers.


text:
Q: Show hidden div when scrolled halfway through viewport EDIT Hopefully this is more clear. :)
Right now, as you scroll down, you'll notice that the pink colored div only appears when it touches the top of the viewport. How can I make it appear when it touches half way through the viewport?
https://jsfiddle.net/1p751fz5/

// constants
var BTN_CLS = 'owl-thumb-item',
  BTN_ANIMATION_MILLIS = 200,
  DIV_ANIMATION_MILLIS = 1000;

// document ready handler
$(document).ready(function() {

  // display buttons from first 'div'
  showBtns('one', BTN_CLS);

  // window scroll handler
  $(window).scroll(function() {
    $('.hidden').each(function(i, v) {
      if ($(window).scrollTop() > $(this).offset().top) {
       // show 'div' when scrolling
       showDiv($(this), onCompleteDivAnimation($(this)));
      }
    });
  });

});

/**
 * Used to show an animated 'div' and perform some actions.
 * @param {Function} completeCallback Action performed after animation.
 * @param {Object} div Target element.
 */
function showDiv(div, completeCallback) {
  // check if 'div' is currently animated and avoid animation queue
  if (!div.is(':animated')) {
    div.animate({
      opacity: 1
    }, {
      complete: completeCallback,
      duration: DIV_ANIMATION_MILLIS
    });
  }
};

/**
 * Used to perform actions after completing a 'div' animation.
 */
function onCompleteDivAnimation(div) {
 showBtns(div.prop('id'), BTN_CLS);
};

/**
 * Used to show button(s) from a 'div' element.
 * @param {String} divId Target element Id.
 * @param {String} btnCls Button(s) CSS class.
 */
function showBtns(divId, btnCls) {
  var btnGroup = getBtnGroup(divId, btnCls);

  animateBtn(btnGroup);
};

/**
 * Used for creating a group of button(s) from a 'div' element.
 * @param {String} divId Target element Id.
 * @param {String} btnCls Button(s) CSS class.
 * @returns {Array} btnGroup
 */
function getBtnGroup(divId, btnCls) {
  var domBtns = $('#' + divId + ' .' + btnCls),
    btnGroup = [];

  for (var i = 0; i < (domBtns || []).length; ++i) {
    btnGroup.push(domBtns[i]);
  }

  return btnGroup;
};

/**
 * Used to animate a button group that normally comes from a 'div' element.
 */
function animateBtn(btnGroup) {
 btnGroup = btnGroup || [];

  $(btnGroup.shift()).fadeIn(BTN_ANIMATION_MILLIS, function() {
    if (btnGroup.length > 0) {
      animateBtn(btnGroup);
    }
  });
};

A: This can be done with jquery. Here is a fiddle: https://jsfiddle.net/s13gjnwt/16/
On scroll, get the window height, the amount the user has scrolled, and the top position of the hidden div. (I set an offset of half the window height so the div won't appear until after it's in 50% in the viewport)
JS
$(window).on('scroll', function(){
  var scrollAmount = $(window).scrollTop();
  var windowHeight = $(window).height();
  var halfHeight = $(window).height() / 2;
  var topOfHiddenDiv = $('.hidden-div').offset().top;
  if(((scrollAmount + windowHeight) - halfHeight) >= topOfHiddenDiv && !$('.hidden-div').hasClass('show')) {
    $('.hidden-div').addClass('show');
  }
});

.content {
  padding-top: 1000px;
}
.hidden-div {
  background: lightblue;
  color: @white;
  padding: 30px;
  opacity: 0;
  transition: opacity 0.3s;
  margin-bottom: 300px;
}
.hidden-div.show {
  opacity: 1;
}

NOTE: Make sure to scroll down in the fiddle


text:
Q: Android: drawing path over Bitmap is very slow I am developing app which can give user ability to open picture in ImageView  and then draw lines on it and also erase them. But i have one big problem: when i am loading a big image the drawing  process becomes very slow. But when the image is small then drawing process is normal))).
This is an algorithm what i do to draw lines:
1. Open image from SD card (decode image size and rescale it if necessary).
2. Put Bitmap into ImageView by setImageBitmap(bitmap); method
3. Create transparent bitmap with width and height as the original bitmap has (to draw and erase lines on it).
4. Draw or erase lines on transparent bitmap (using Path class) in ImageView onDraw() method
This is my onDraw() method:
@Override
protected void onDraw(Canvas canvas) {
    super.setImageMatrix(mMatrix);
    super.onDraw(canvas);
    if (!mFragmentImage.inDrawMode()) return;
    canvas.save();
    if (mFragmentImage.mShape!=null){
        if (mFragmentImage.mShape.getType() == CustomShape.SHAPE_LINE) {
            mOverlayCanvas.drawPath(mFragmentImage.mShape.getPath(), mFragmentImage.mShape.getPaint());
        }
    }
    if (mOverlay!=null)    canvas.drawBitmap(mOverlay, mMatrix, null);
    canvas.restore();
}

Can anyone give some advices how to make drawing process faster.