text:
Q: How to INSERT getDate() into a column in a table which also has columns that have data inserted with OPENJSON and CROSSAPPLY I have a the following JSON that needs to get inserted into a table
{
    "Parent": {
            "level": "Ground",
        },
     "Items":[
              { "name" : "name1",
                "id" : "id1"
              },
              { "name" : "name2",
                "id" : "id2"
              },
           ]

}
This is the query i wrote for inserting into the table
Insert into table(name,id,level,dateInserted) Select(name,id,level,dateInserted)FROM OPENJSON((select
* from @json), N'$.Items')
    WITH (  id   nvarchar(max) N'$.id',
        name   nvarchar(max) N'$.name')
   CROSS APPLY OPENJSON((select * from @json), N'$.Parent')
        WITH( level nvarchar(max) N'$.level'))
 **CROSS APPLY dateInserted dateTime getDate()**

I am having issue inserting getDate() into the dateInserted column. As dateInserted is something that is not being read from the JSON itself, I am having trouble inserting it into the table. What is the right way to do it?

A: It was a silly mistake. It has nothing to do with the OPENJSON or CROSS APPLY
For anyone looking for an answer
Insert into table(name,id,level,dateInserted) Select(name,id,level,getDate())FROM
OPENJSON((select
* from @json), N'$.Items')
WITH (  id   nvarchar(max) N'$.id',
    name   nvarchar(max) N'$.name')
CROSS APPLY OPENJSON((select * from @json), N'$.Parent')
    WITH( level nvarchar(max) N'$.level'))

The getDate() has to be inside the Select clause


text:
Q: wanting normal text in window title but not chinese letters HWND hwnd;
void makeWindow() {
        const char* onlyOneWindowClass = "general";
        HINSTANCE moduleHandle = GetModuleHandle(0);
        WNDCLASSEXA wc;
        wc.cbSize = sizeof(WNDCLASSEXA);
        wc.style = 0;
        wc.lpfnWndProc = WndProc2;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = moduleHandle;
        wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
        wc.hCursor = LoadCursor(NULL, IDC_ARROW);
        wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
        wc.lpszMenuName = NULL;
        wc.lpszClassName = onlyOneWindowClass;
        wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
        RegisterClassExA(&wc);
        hwnd = CreateWindowExA(WS_EX_CLIENTEDGE, onlyOneWindowClass, "temp", WS_OVERLAPPEDWINDOW, 100, 100, 240, 120, NULL, NULL, moduleHandle, NULL);
}

I call above procedure like below:
   makeWindow();
    //some code here
    SetWindowTextA(hwnd, "want not chinese");
    ShowWindow(hwnd, SW_SHOW);
    UpdateWindow(hwnd);

Above is how I set window Text but I get only chinese letters. What is wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: File upload using AngularJS -> .NET Web Api 2 -> SQL server I'm looking for a solution where I can upload any file to SQL server from an AngularJS frontend to .Net Web Api 2 and straight to SQL Server Database. I've done some research and for angularjs i'm mainly looking at ng-file-upload. my problem is most of the solutions that i've looked at saves the file into a temp folder. I'm not sure if it's possible but I want it straight to an SQL server table.
I've seen some solutions where it converts the file into a byte array which can be saved to an SQL table but I'm not sure how to do this in a .NET web api 2 and from an angularjs front end. thank you in advance.

A: Don't save files to SQL server--that's not what it's for.  See this answer: In MVC4, how do I upload a file (an image) to SQL Server that's part of my domain model?  And this answer: Storing files in SQL Server

Uploading files in angular is easy.  Do it like this:
Controller
$scope.uploadFile = function() {
    //get the filename from the <input type='file'>
    //angular doesn't allow attaching ngModel to file input
    var fileInput = document.getElementById("myInputId");

    //check if there's a file
    if(fileInput.files.length === 0) return;

    //you cannot send a file as JSON because json is in the string format
    //for fileuploads, you must send as a FormData() object
    //C# accepts HttpPostedFileBase as the file argument
    var file = fileInput.files[0];

    //put the file in a new formdata object
    var payload = new FormData();
    payload.append("file", file);

    //upload file to C# controller
    $http.post("path/to/C#/controller", payload, {
            //you **need** to specify these options, without them upload does not work
            transformRequest: angular.identity,
            headers: { "Content-Type": undefined }
    }).then(function(data) {
        //success
    }, function(error) {
        //error
    });
}

C#/ASP.NET
[WebMethod]
public string UploadFile(HttpPostedFileBase file) {
    //access the file object here
    var inputStream = file.InputStream;
    var fileName = Path.GetFileName(file.FileName);

    try
    {
        file.SaveAs("local/path" + fileName);
    }
    catch (IOException exc)
    {
        return "Error: " + exc.Message;
    }

    return "success";
}


text:
Q: ?thesaurical, adj The adjectival form of thesaurus does not seem to have been listed on (all) standard dictionaries. However, thesaurical occurs in literature1 and is also defined in Urban Dictionary.
Do we have an alternate 'listed' word for a context like the one below (a question of the sort dealt with on the pages of thesauri)?

But, Sir, that's a thesaurical question.

1 These are the next epithets theorists have up their thesaurical sleeves.
(New Scientist, 1977)

A: OED has

thesaurus noun
Etymology:  Latin, < Greek θησαυρός a store, treasure, storehouse, treasury.
1. Archaeol. A treasury, as of a temple, etc.
2.
  a. A 'treasury' or 'storehouse' of knowledge, as a dictionary, encyclopædia, or the like.
  b. A collection of concepts or words arranged according to sense; also (U.S.) a dictionary of synonyms and antonyms.
  c. A classified list of terms, esp. key-words, in a particular field, for use in indexing and information retrieval.

I didn't realise the word meant treasury, but that leads us to

thesaurarial adjective
Etymology:  < Latin thēsaurārius (see thesaurary n.) + -al suffix1.
Of or pertaining to the office of treasurer.
†thesaury noun
Cheifly Sc. Obs.: The treasury; the treasurership.

OED doesn't list a canonical adjective for "of or pertaining a dictionary of synonyms", but it would be possible to coin thesaurial from thesaury which is sufficiently like thesaurus to be intelligible, and which introduces neither the extra syllable of thesaurarial nor the -c- in thesaurical.
I guess that New Scientist coined thesaurical because of its similar sound to rhetorical, but that is to misuse the -ical ending. The base word does not end -ic.


text:
Q: Getting the error 1119: Access of possibly undefined property visible through a reference with static type Class I am attempting to hide a symbol (Grill image) as soon as my animation loads.
Currently I am getting the error, E:\Burger Game\DragandDrop\Dragable.as, Line 4, Column 8  1119: Access of possibly undefined property visible through a reference with static type Class. As you can probably tell, I am new to flash.
package DragandDrop
{
    Grill.visible=false;
    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    import flash.geom.Point;

    public class Dragable extends MovieClip
    {

        protected var homePos:Point;
        var totalToBowl:int =3;
        var i:int = 0;
        public function Dragable ()
        {
            homePos=new Point( x, y);
            buttonMode =true;
            addEventListener ( MouseEvent.MOUSE_DOWN, move);
        }

        //egg functions
        protected function move(event:MouseEvent) :void
        {
            parent.addChild(this);
            startDrag();
            stage.addEventListener(MouseEvent.MOUSE_UP, stageUp)
        }

        //item drop function

        protected function stageUp(event:MouseEvent):void
                {

                stopDrag();
                if (event.target.dropTarget != null &&dropTarget.parent.name == "Bowl")
                {
                    scaleX=scaleY=0;
                    alpha=0.5;
                    y= stage.stageHeight-height -700;
                    x=stage.stageWidth-width- 1400;
                    buttonMode=false;
                    removeEventListener(MouseEvent.MOUSE_DOWN, stageUp)
                    i++

            }if (i == totalToBowl){

            i=10
            trace(i);
            event.target.dropTarget.visible = false;

        }
        if (i==10 )
        {
            dropTarget.parent.visible = false;
                }else{
                    returnToHome();

                }
    }

        protected function returnToHome():void
        {
            x = homePos.x;
            y= homePos.y;
        }

}

Any idea why I am getting this error?
Any help would be massively appreciated.
Many thanks,
Rob

A: There are two issues:

*

*Grill is a class, but it would seem you are trying to use it like an instance.  This is what it's expecting to see when used like you're doing:
public class Grill extends MovieClip {
    public static var visible:Boolean;
}

But more than likely, what you need to do is work with an instance, not the class itself:
var g:Grill = new Grill();
g.visible = false;

If this class is linked to a timeline instance, you'd have to use the instance name you gave it (and make sure that instance name doesn't clash with any Class names - or use getChildByName).

*Assuming this is not meant to be static code, you have code outside of a function/method that will cause another error.
In class files, all non-static functional code needs to be in a function. You need to move that line in question (Grill.visible=false) into a function.  Most likely, you want this to be the equivalent of timeline code.  So the best place to put would be this:
public function Dragable ()
{
    homePos=new Point( x, y);
    buttonMode =true;
    addEventListener ( MouseEvent.MOUSE_DOWN, move);

    //addedToStage is the best equivalent of when timeline code would run
    addEventListener(Event.ADDED_TO_STAGE, addedToStage);
}

private function addedToStage(e:Event):void {
     //where grillinstance is the instance name of your grill
     grillInstance.visible = false;
}

Now, this assumes you have this class linked at timeline that has an instance of Grill on it.  If this is an incorrect assumption, please clarify with a comment or by updating your question.


text:
Q: angular2 Dragula css cursor grab/grabbing not working Angular 2.4.8, dragula 3.10.6, it seems the cursor styling for grabbing is not applying when dnd. any suggestions?
css is imported in the index.html as
<link rel="stylesheet" href="../node_modules/dragula/dist/dragula.min.css">

A: It's working for me. I am using Angular Cli and i placed CSS file inside my .angular-cli.json file
  "styles": [
 "../node_modules/dragula/dist/dragula.css",
 ],

A: You can import css in style.css too like below.
@import '../node_modules/dragula/dist/dragula.css';


text:
Q: ggplot2 facet_grid How to create different x-axis with keeping all values in each panel? Let's say, I have data like following example,
dat1 <- data.frame(group = c("a", "a","a", "a", "a", "b", "b", "b","b","b","b","b","c","c","c"),
                   subgroup = c(paste0("R", rep(1:5)),paste0("R", rep(1:7)),paste0("R", rep(1:3))),
                   value = c(5,6,0,8,2,3,4,5,2,4,7,0,3,4,0),
                   pp = c("AT","BT","CT","AA","AT","TT","RT","CC","SE","DN","AA","MM","XT","QQ","HH"))

And, I want to add some cut off as dat1 = dat1[dat1$value > 2, ]. My code
pl <-  ggplot(dat1, aes(y = as.character(pp),  x = as.factor(subgroup))) +
  geom_point( aes(size=as.numeric(value)))+  facet_grid(cols = vars(group), scales="free", space="free")+
  ylab("names") +xlab(" ")
  pl
enter image description here
But I want to see all scale in each panel. For example in the first panel, there are five values or five scales even if below of cut off or zero I just want to see all five scale. The second panel has 7 scales but after cut off, there should be 6 columns, but I want to see all 7 scales even if it has zero.
How can I modify my code or make as this kind of plot?

A: We can use the scales and space arguments in facet_grid.
ggplot(dat1, aes(subgroup, pp)) +
  geom_point(aes(size = value)) +
  facet_grid(cols = vars(group), scales = "free", space = "free")


text:
Q: Trouble clicking submit button in selenium I am trying to click the submit button in the login page for my router, but am having trouble doing so.
Here is a screenshot of the login page:

I know I need to do some sort of driver.find_element_by_something(), but cannot figure out what to call it on.
here is what I use to fill in the forms
driver.get("http://172.18.40.177:8080/index.html")
username = driver.find_element_by_name("userid2")
username.send_keys("admin")

password = driver.find_element_by_name("passwd2")
password.send_keys("cyber")

html webpage

A: without your code and seeing the rest of the html it's hard to say. something like the below will probably work
driver.find_element_by_xpath("descendant::tr/td/img").Click();

the thing is if there's other img tags within a td it may find those first. In that case you'll have to do some analysis on the html to figure out a way to select the button but xpath is likely your best bet.


text:
Q: Error: write EPIPE when trying to upload file to FTP using gulp I've got a task to deploy some stylesheets out to a server using FTP and about 80% of the time I get this error,
Error: write EPIPE
  at _errnoException (util.js:1022:11)
  at WriteWrap.afterWrite [as oncomplete] (net.js:880:14)

I'm using vinyl-ftp to upload the file as seen in the code here,
var conn = ftp.create({
    host: 'host',
    user: 'user',
    password: 'pass',
    parallel: 10,
    idleTimeout: 10000,
    reload: true,
    secure: true,
    secureOptions: {rejectUnauthorized: false},
    log: gutil.log
});

// What files to transfer over (can be used in case there are more files to be uploaded in the future)
var globs = [
    localDir + '/' + jobName + 'Default.css'
];

gutil.log("Local File: " + globs[0]);

var remoteDir = '/' + environment + '/css/' + clientName + '/' + jobName;

gutil.log("Remote Dir: " + remoteDir);

return gulp.src(globs, {buffer: false}).pipe(conn.dest(remoteDir));

The server that I'm uploading to is using FTP-SSL (Explicit AUTH TLS). I'm not sure if that's what's causing the issue but I've tried catching the error and adding an onerror event to process.stdout but none of them work. When the error does trip it uploads an empty file to my server.
It'd be great to find a solution to this or better yet a different FTP package.
Edit 1: I'm on Windows.

A: Finally just said screw it and changed what module I was using. node-ftp only throws the EPIPE error about 5% of the time compared to the original 80%. You can also catch the error which is useful because I catch it and try to upload the file again.


text:
Q: What does "What's his deal" mean? What does "What's his deal" mean?
I couldn't find it in any dictionary, I thought it was an idiom, but it's not. It seems like a slang that's not widely used, or at least it isn't recognized by any dictionary as of now.
What's his deal mean "What is his problem?" I am guessing, but I am not sure.

A: There are a few ways we can interpret this:

*

*Most commonly used to ask what's going on (e.g. with a plan or a situation) - Inquiring about a deal (so basically we interpret this literally)

What's the deal the gentleman proposed to you about that loan?

*When asking about someone (Inquiring about someone's actions, reactions, attitude, or demeanor)

What's the deal with that guy? He doesn't look okay.

*When asking about a situation (Inquiring about a "next step" in a process or outcome)

So, what's the deal - are we going out to dinner?

My view of this is that it translates to "what's up", but it usually might mean the other meanings above.
References:

*

*What does "what is you deal" mean in an informal romantic context

A: The phrase is popular for its use in the American movies. It could mean:

*

*What's his/her problem?

*Why does he/she behave snobbish?

The list can go on.
You can usually omit the pronoun. See the definiton of the phrase in LDOCE

A: The question "What's his deal?" is very malleable. It's going to depend on the context. Generally, it means "what is his situation with regard to the current subject?" And the subject is going to be determined by context. It is intended to invite a general explanation of the situation regarding the subject.
So, if the discussion was personal wealth, then it would be asking about the person's personal wealth and outlook in that regard. If the discussion was about employment, then it would be about what the person's job and prosepects were. If it was about family, then it would be asking about the person's family and relationships with them. If it was about politics it would be asking the person's political opinions. And so on. In each case the person answering is invited to give important details regarding the subject person's situation.
The following is a clip from the TV show "Big Bang Theory." The character Sheldon Cooper is a Cal. Tech. professor, and really quite stunningly brilliant at it. But socially he is amazingly awkward. He has a visit from a woman. Sheldon's friends are quite surprised at this since, to this point, Sheldon had shown absolutely no interest in romantic social interactions of any sort. Yet, here is this attractive woman bringing food in a manner that gives every appearance of being a romantic date.
https://www.youtube.com/watch?v=fOIcFS1U9TI
Upon being shooed out of the apartment to give Sheldon and his date some privacy, the character Penny asks "What is Sheldon's deal?" In context she means "what is Sheldon's sexual proclivity?" The response is that his friends believed he "had no deal." Penny prompting for more information is followed by a couple of amusing hyperbolic notions of what Sheldon's reproductive strategy might consist of, since he is widely asserted to be a mutant or a space alien foundling.


text:
Q: Ubuntu Server - cant connect to github I am unable to access github at all from the command line on a newly installed Ubuntu server. Pinging and curling github fails but works fine for other hosts.
OS: Ubuntu 22.04.1 LTS
Ping test
# google
ping -c3 google.com
PING google.com(ord37s32-in-x0e.1e100.net (2607:f8b0:4009:808::200e)) 56 data bytes
64 bytes from ord31s21-in-x0e.1e100.net (2607:f8b0:4009:808::200e): icmp_seq=1 ttl=115 time=16.6 ms
64 bytes from ord37s32-in-x0e.1e100.net (2607:f8b0:4009:808::200e): icmp_seq=2 ttl=115 time=15.2 ms
64 bytes from ord37s32-in-x0e.1e100.net (2607:f8b0:4009:808::200e): icmp_seq=3 ttl=115 time=10.9 ms

--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2004ms
rtt min/avg/max/mdev = 10.914/14.210/16.553/2.398 ms

# github - fails with 'Destination Host Unreachable'
ping -c3 github.com
PING github.com (140.82.113.3) 56(84) bytes of data.
From ubuntu (192.168.0.38) icmp_seq=1 Destination Host Unreachable
From ubuntu (192.168.0.38) icmp_seq=2 Destination Host Unreachable
From ubuntu (192.168.0.38) icmp_seq=3 Destination Host Unreachable

--- github.com ping statistics ---
3 packets transmitted, 0 received, +3 errors, 100% packet loss, time 2026ms
pipe 3

# github ping -4
ping -c3 github.com
PING github.com (140.82.112.4) 56(84) bytes of data.
From ubuntu (192.168.0.38) icmp_seq=1 Destination Host Unreachable
From ubuntu (192.168.0.38) icmp_seq=2 Destination Host Unreachable
From ubuntu (192.168.0.38) icmp_seq=3 Destination Host Unreachable

--- github.com ping statistics ---
3 packets transmitted, 0 received, +3 errors, 100% packet loss, time 2020ms
pipe 2

curl test
# google
curl -s --head --request GET google.com > /dev/null; echo $?
0

# github
curl -s --head --request GET github.com > /dev/null; echo $?
7

git clone test
# Fails with 'no route to host'.
git clone https://github.com/pi-hole/pi-hole.git
Cloning into 'pi-hole'...
fatal: unable to access 'https://github.com/pi-hole/pi-hole.git/': Failed to connect to github.com port 443 after 18534 ms: No route to host

nslookup
# google
nslookup google.com
Server:     127.0.0.53
Address:    127.0.0.53#53

Non-authoritative answer:
Name:   google.com
Address: 142.250.191.206
Name:   google.com
Address: 2607:f8b0:4009:803::200e

# github
nslookup github.com
Server:     127.0.0.53
Address:    127.0.0.53#53

Non-authoritative answer:
Name:   github.com
Address: 140.82.112.4

ip r s
ip r s
default via 192.168.0.1 dev enp0s31f6 proto dhcp src 192.168.0.38 metric 100
1.1.1.3 via 192.168.0.1 dev enp0s31f6 proto dhcp src 192.168.0.38 metric 100
192.168.0.0/24 dev enp0s31f6 proto kernel scope link src 192.168.0.38 metric 100
192.168.0.1 dev enp0s31f6 proto dhcp scope link src 192.168.0.38 metric 100
192.168.0.38 dev enp0s31f6 proto dhcp scope host src 192.168.0.38 metric 100

ifconfig
ifconfig
enp0s31f6: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.38  netmask 255.255.255.0  broadcast 192.168.0.255
        inet6 2601:246:4d7f:8361:d681:d7ff:fe8d:637b  prefixlen 64  scopeid 0x0<global>
        inet6 fe80::d681:d7ff:fe8d:637b  prefixlen 64  scopeid 0x20<link>
        ether d4:81:d7:8d:63:7b  txqueuelen 1000  (Ethernet)
        RX packets 231023  bytes 191591697 (191.5 MB)
        RX errors 0  dropped 8  overruns 0  frame 0
        TX packets 174168  bytes 16427225 (16.4 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 16  memory 0xef200000-ef220000

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 10709  bytes 1034079 (1.0 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 10709  bytes 1034079 (1.0 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

traceroute
# google
traceroute to google.com (172.217.1.110), 30 hops max, 60 byte packets
 1  ubuntu (192.168.0.38)  3060.551 ms !H  3060.478 ms !H  3060.429 ms !H

# github
traceroute to github.com (140.82.114.4), 30 hops max, 60 byte packets
 1  ubuntu (192.168.0.38)  3049.846 ms !H  3049.774 ms !H  3049.725 ms !H

I am not, to my knowledge, dealing with any proxies or abnormal firewall setup.
Thanks for any advice.

A: For IPv4/6 related issue:
It seems that you only get an answer from IPv6 ip's and GitHub sadly does not provide a IPv6 address yet, more on that topic can be found here.
They recently started testing support for it internally.
Please provide the output of ip r s and/or ifconfig and traceroute google.com as well as traceroute github.com.
Further try ping -c3 -4 github.com - if they go through the easiest way would be to deactivate IPv6 for the NIC in use.
To temporarily disable IPv6:
$ sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1
net.ipv6.conf.all.disable_ipv6 = 1
$ sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1
net.ipv6.conf.default.disable_ipv6 = 1

and test again - if it works feel free to permanently disable IPv6 (if desired) by adjusting the line GRUB_CMDLINE_LINUX_DEFAULT in /etc/default/grub to read GRUB_CMDLINE_LINUX_DEFAULT="ipv6.disable=1"
and finally run sudo update-grub to have ipv6 disabled permanently disabled
For DNS related issue (unlikely in this case):
can you check systemd-resolve --status? If it uses a "proper" DNS Server like Google 8.8.8.8 or in fact the DNS from your provider/router?
In case it uses a DNS server from your provider/router I'd suggest changing it to 8.8.8.8.
Probably best to check on how to achieve that as we don't know whether you have GUI enabled or not it is kinda hard to provide a fully working answer.
For a CLI Setup (using Google DNS):
sudo nano /etc/netplan/01-network-manager.yaml and add nameservers to use for the desired interface
    nameservers:
        addresses: [8.8.8.8, 8.8.4.4]

save and exit the file and run sudo netplan try to verify the configuration file is valid.
If so apply it with sudo netplan apply

A: I hate to ask, but I don't see any mention of an access token being used?
To access through cli you'll need an access token.
I'd also recommend using the gh cli instead of git. I suspect the issue being related to server being wiped and not having any credentials.
Take a look here for details on setting up access token to use with ssh.
https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token
The easiest way to get started is by using the gh cli.
You can install it with the following commands
sudo apt update && sudo apt install gh

Then do
gh auth login

Hope this helps!


text:
Q: how do to sort a python dictionary with multiple attributes and unicode strings I have a list of dictionaries with some strings containing artists and their albums (fetched from Spotify). I want to sort this dictionary by artist first and then by album. But I want to use a locale aware sort (German in my case).
I found out that I can sort a list of dictionaries with multiple key like so:
somelist.sort(key=lambda k: (k['artist'].lower(), k["album"].lower()))

.lower because I want a case insensitive sort.
This works fine for English named artists and albums, but not for none-English. I found also out that for locale aware sorts I can use somelist.sort(key=locale.strxfrm).
What I don't understand: How can I combine locale-aware AND multiple key sorts?

A: Why not compose the two?
def normalizeSortString(s):
    return local.strxfrm(s).lower()

def getSortKey(k):
    return (normalizeSortString(k['artist']), normalizeSortString(k["album"]))

somelist.sort(key=getSortKey)


text:
Q: Asp.net objectdatasource TypeName property error I use ASP:ObjectDataSource for grid data binding.
My problem is when I run this code I get error.
<asp:ObjectDataSource ID="odsListing"
runat = "server"
SelectMethod = "MethodNameOfCodeBehindClass"
TypeName = "FolderName_CodeBehindClassName" ></asp:ObjectDataSource>

Error message
The type specified in the TypeName property of
ObjectDataSource 'odsListing' could not be found.

So I move my code to codebehind site.
    #region ObjectDataSource for Grid Binding
    Type type = typeof(FolderName_CodeBehindClassName);
    string assemblyQualifiedName = type.AssemblyQualifiedName;

    odsListing.TypeName = assemblyQualifiedName;
    odsListing.SelectMethod = "ListingDatabind";
    #endregion

Now Everythings is ok. It is work.
But I would like to know actual solution for my problem.
Why it raise error?
Actually, I don't want to move my code to codebehind layer if it can write at design layer.
Every suggestion will be appreciated.

A: The problem is that you are using short type name instead of full type name.
Replace FolderName_CodeBehindClassName with The.NameSpace.YouHaveYourTypeIn.FolderName_CodeBehindClassName, Name.Of.Your.Assembly.


text:
Q: $\Sigma_{m|n} \mu(m)^2/\phi(m) = n/\phi(n)$? I'm trying to prove
$$\sum_{m|n} \mu(m)^2/\phi(m) = n/\phi(n)$$
My first realization was that $\mu(m)^2 = 1$ iff $m=1$ or $m$ is a squareless factor of $n$ and otherwise is 0.  Let $\{1,m_1,m_2, ... m_k\}$ be the set of squarefree factors of $n$.
So now we have a sum
$$\frac{1}{\phi(1)} +\frac{1}{\phi(m_1)} + \cdots +\frac{1}{\phi(m_k)}.$$
How do I show the sum equals $n/\phi(n)$? Or am I going in the wrong direction?

A: You may know the result that if $f$ is a multiplicative function, and $F(n)=\sum_{d\mid n} f(d)$, then $F$ is multiplicative.
Using that fact, you only need to verify your assertion for $n$ a prime power, where it is immediate.

A: Hint.  For a different approach at establishing that your sum is what you want:
$$\displaystyle\phi(n) = n\!\!\!\!\!\prod_{p\mid n,\ p\text{ prime}}\!\!\!\!\left(1 - \frac{1}{p}\right).$$


text:
Q: 220V AC/DC converter on 110V circuit I have an AC/DC converter:

input AC 220-240V 50/60Hz

output DC 3.6-10.8V 1.5A.

It is a charger for an electric drill battery (Li-ion 10.8V 4Ah).
What would happen if I were to plug this converter on a 110V circuit? Would the DC voltage be half what it is supposed to be?
Would the battery charge at all, albeit slower?


text:
Q: Xcode error when attempting to archive project: Unexpected duplicate tasks My project runs totally fine with no warnings on both the simulator and a real device, but when I try to archive it, I get this error:

Unexpected duplicate tasks:

1) Target 'SwiftDataTables' (project 'Pods') has copy command from '/myAppPath/Pods/SwiftDataTables/SwiftDataTables/SwiftDataTables.bundle/column-sort-descending.png' to '/Users/Marius/Library/Developer/Xcode/DerivedData/myAppName-bvaclcqghnevllgdezgzmpfvrzrz/Build/Intermediates.noindex/ArchiveIntermediates/myAppName/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/SwiftDataTables.framework/column-sort-descending.png'
2) Target 'SwiftDataTables' (project 'Pods') has copy command from '/myAppPath/Pods/SwiftDataTables/SwiftDataTables/SwiftDataTables.bundle/column-sort-descending.png' to '/Users/Marius/Library/Developer/Xcode/DerivedData/myAppName-bvaclcqghnevllgdezgzmpfvrzrz/Build/Intermediates.noindex/ArchiveIntermediates/myAppName/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/SwiftDataTables.framework/column-sort-descending.png'

I get this error 3 times, one for each of the pictures that are in the SwiftDataTables.
I have already tried cleaning the project, uninstalling and reinstalling the problematic library, and removing all the files from Derived Data. From what I have seen from other similar questions, the solution is often checking that a file isn't listed both in Copy Bundle Resources and Compile Sources in target/Build phases, but I can't find any file that is listed twice.
Thanks in advance.

A: I could fix it by selecting the three images in Xcode and then remove the Target Membership for SwiftDataTables and adding it again.

A:
Try again - In the file navigator you can try searching (Cmd+F) to see
  if the files are somehow in the project twice. Try removing entire
  framework and any references from the file navigator and the build
  settings (check under Frameworks folder, et al), and then re-add. Check the pods files listed in the build
  settings. There is a place where the file paths are added for example
  if you tried using Carthage previously where the duplication is
  occurring.


text:
Q: Execute a Python script from Expect I am using Expect for automation, and I want to execute a Python script from it. But it is not working... This is what I have tried so far:
#!/usr/bin/expect
spawn  "./os_fun"

and
#!/usr/bin/expect
spawn  "./os_fun.py"

and
#!/usr/bin/expect
spawn  python "./os_fun(.py)"

The "os_fun.py" contains the simple code:
#!/bin/usr/python
import os
print os.getcwd()

I would also like to mention that I must use Expect only and not Bash as I need to do the automation part, and I am not supposed to use Pexpect.

A: When it comes to Expect, you always have to expect something, so that Expect will wait for it. Else, it will proceed as such. Simply spawning a processing does not make sense, as Expect don't wait to see for it which in turn makes the user not to see the output as well.
In your case, you just have to run the code and see the output till the program completes. I hope my understanding is correct.
!/usr/bin/expect
spawn python os_fun.py
expect eof; # will wait till 'eof' seen

Here, expect command will wait till it sees close of the running program.
Default timeout is 10 seconds which can be changed as
set timeout 60; # Timeout value as 1 min


text:
Q: Will AllowAppOnlyPolicy and CreateUserClientContextForSPHost elevate user rights If one has enabled AllowAppOnlyPolicy and use the CreateUserClientContextForSPHost method will I elevate the users rights, or is this only the case when you create app only token?

A: Enabling AllowAppOnlyPolicy  in app manifest alone will not guarantee that your code will be run in elevated rights. But you should generate apponlyaccesstoken using TokenHelper.GetAppOnlyAccessToken and use this token in TokenHelper.GetClientContextWithAccessToken to generate the client context. Now this context will be of elevated rights.
CreateUserClientContextForSPHost  will always  be run under the current user context.
Please see this article which explains AppOnlyPolicy.


text:
Q: Dropdown list (select/option) not working on Firefox mobile (with touch) I've recently noticed that my dropdown lists stopped working on Firefox mobile browser.
I've done a simple example in a fiddle:
https://jsfiddle.net/a52jm6h3/8/
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>

I'm using Firefox Quantum (57, 64bits) and then use the developer tools to simulate the mobile, when I select a device like Google Nexus 7 (and make sure the Touch Simulation is Enabled) I'm not able to open the Dropdown list.
Does anyone else had a similar issue?

A: I've solved this problem, I was using Fastclick.js (https://github.com/ftlabs/fastclick) plugin in my app.
Just disabled it and the problem was solved.
Seems like the mobile browsers don't need these kind of plugins nowadays anyway.


text:
Q: Does Facebook login kick off an event? I have this on my page
<fb:login-button perms="publish_stream">Login with Facebook</fb:login-button>

But I want to know if there is a way that when a user clicks the login button, I can tell if they've successfully logged in or not, like if there's an event that Facebook throws me or something when that login window is closed, if the users attempt was successful or not.
I know I can check randomly in the app by making a request for the me object, and seeing if it comes back correctly, but I want it to be thrown right after that login window is exited (whether it is exited b/c a login was successful, or a user denied something).

A: I can do it with this :)
FB.Event.subscribe('auth.login', function(response) {
  // do something with response.session
});

A: Is this what you're looking for? http://developers.facebook.com/docs/reference/javascript/FB.login/


text:
Q: How to get post with multiple but not all tags in common How do I get posts which have at least two tags in common?
tag__in => $args  shows posts which have either tag in common
tag__and => $args for post which have all tags in common
What i need is get all posts which have some tags in common, more than one tag and less than all tags in common.
Can anyone please help?
Thanks in advance!

A: Try using the 'tax_query' parameter in WP_Query. I haven't tried to do exactly what you're trying to do, but it should work.  The tax_query parameter is an array of separate taxonomy queries, with each query specifying the taxonomy, the term_id(s) and an operator like "IN" or "NOT IN".
Look at WP_Tax_Query in wp-includes/taxonomy.php on line 534 and WP_Query::parse_tax_query in wp-includes/query.php (line 1674).
Here's an example of using tax_query with WP_Query
Hope this helps.


text:
Q: how to check user is login in facebook in iphone setting or not ? if user is already login then don't open facebook login page  in IOS......
is there any API in facebook sdk to check this kind of  ?
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {

    // Facebook SDK * login flow *
    // Attempt to handle URLs to complete any auth (e.g., SSO) flow.
    NSLog(@"we reach here");
    return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication fallbackHandler:^(FBAppCall *call) {
        // Facebook SDK * App Linking *
        // For simplicity, this sample will ignore the link if the session is already
        // open but a more advanced app could support features like user switching.
        if (call.accessTokenData) {
            if ([FBSession activeSession].isOpen) {
                NSLog(@"we r here");
                NSLog(@"INFO: Ignoring app link because current session is open.");
            }
            else {
                [self handleAppLink:call.accessTokenData];
            }
        }
    }];
}

i try this but it's not working for me


text:
Q: Who uses sequence diagram in project team? In project team, who is the responsible of drawing up sequence diagram (UML 2.0) and who uses it after?
Thanks in advance.
Best regards,
Ali

A: Anyone who is designing the architecture of the project would be assigned to design the sequence diagram. The duty can be assigned to various team members depending on the dynamics of the software house, the stake holders involved and depending on the seriousness of the project.
To add to this, a developer, tester, team leader, CTO would be using the diagram at the time of the development cycle. Moreover, the management and even the client would/can use it to check how the project is proceeding.

A: A sequence diagram models the flow of you logic.
So anyone who want's to model some workflow or some program/test logic can/should draw it and everyone who want's to implement the logic should use it afterwards.
For example it might be useful to make a sequence diagram to model a certain part of your application, generate or write a test from the diagram, implement the logic and see if it still conforms to the tests you generated/written earlier, which should be equivalent to the sequence diagram.


text:
Q: Yii - How to use conditions like where and limit I use findAll() like this:
$l = SiteContentRelated::model()->findAll('content_1=:c', array(':c' => $id));

How I can add condition to this?
Like as LIMIT 5 or anything?

A: Use CDbCriteria to specify more detailed criteria:
$criteria = new CDbCriteria;
$criteria->condition = 'content_1=:c';
$criteria->limit = 5;
$criteria->params = array(':c' => $id);

$l = SiteContentRelated::model()->findAll($criteria);

or pass an array to findAll which will be converted to a CDbCriteria:
$l = SiteContentRelated::model()->findAll(array(
  'condition' => 'content_1=:c',
  'limit' => 5,
  'params' => array(':c' => $id),
));

When you specify a LIMIT, it's a good idea to also specify ORDER BY.

For filtering based on model attributes, you can also use findAllByAttributes:
$l = SiteContentRelated::model()->findAllByAttributes(array(
  'content_1' => $id,
), array(
  'limit' => 5,
));


text:
Q: How to read the concatenated string as a variable in angularjs? In my angular controller i defined
$scope.flag1 = false;
$scope.flag2 = false;
$scope.flag3 = false;

I need to read those variable in my view page as bellow

 <md-icon id = "{{'flag'+shortListLoad.id}}">
 </md-icon>

The thing is id ="{{'flag'+shortListLoad.id}}" brings as id = 'flag2' than id= 'false'.
how to get id= 'false' ? please help me?

A: Another way is
<md-icon id = "flag{{id}}"> {{id}}</md-icon>

Working plunkr: http://plnkr.co/edit/1ufO3CJoUefVb2wDr4TZ?p=preview

A: If I understand your question right, you want to output to id flag1, or flag2 or flag3..
It's not recommended to use a function with angular binding, but you can do something like this.
$scope.getFlag = function(id){
    return 'flag'+id;
};

and in your view

     <md-icon id = "{{getFlag(shortListLoad.id)}}">
     </md-icon>


text:
Q: Sonarlint warning: Remove this "exit()" call or ensure it is really required Sonarlint (a code quality tool) complains about exit(); calls in my code. The code is a target (action="") in a form that creates a DB row, then redirects to an overview page. Simplified like this:
// do something
// on success:
header('Location: ' . $location);
exit;

Their explanation of this error.
Is there is a "proper" way to redirect in such cases without using the exit() call? The redirect can happen very early in the file and running through all the other code following this location seems redundant.
I don't want to just make the warning disappear (I know it's possible to do with // NOSONAR.) but rather understand how to proper program this piece of code or if this some kind of overzealous quality control thing.
I understand, that exit(); calls are not testable - the reason for this warning. On the other side, using, for instance, the Browser tester of Codeception I can test properly if a redirect is happening.


text:
Q: angularjs : how to get width from a $element in directive without using jquery I try to get a width from a $element in directive. but, it continues to return 0.
Can you tell me what is the problem? and, can you tell me the solution?
To see problem, i've created a demo :

*

*directive
angular.module('testApp').directive('testDirective', testDirective)
function testDirective() {
    return {
        restrict: 'E',
        controller: 'TestController',
        controllerAs: 'vm',
        bindToController: true,
        scope: {}
    }
}

*controller
angular.module('testApp').controller('TestController', TestController);

TestController.$inject = ['$element'];

function TestController($element) {
    var vm = this;

    init()

    function init(){
    vm.elWidth0 = $element.find("div")[0].clientWidth;
    vm.elWidth1 = $element.find("div")[0].offsetWidth;
    vm.elWidth2 = $element.prop('clientWidth');
    console.log(vm.elWidth0); //return 0
    console.log(vm.elWidth1); //return 0
    console.log(vm.elWidth2); //return 0
    }
}

*html
<test-directive>
    <div>
        <button>a</button>
        <button>c</button>
        <button>d</button>
        <button>e</button>
        <button>f</button>
    </div>
</test-directive>

Thank you for your advice

A: Take a look at this plnkr: http://plnkr.co/edit/3D8kQUukMkXRld9kNYJ1?p=preview
It would appear that you're not getting a proper reference to the elements. Try using querySelector instead:
$element[0].querySelector('button').clientWidth;

UPDATE
The best place to put DOM manipulation in a directive is in the link function(which is actually post-link) because link happens after the directive html has been compiled.
The controller also is created after the directive html has been compiled but it's good to use the controller to separate logic that requires communication with an angular service.  There's some really good information on directive link vs. controller here.
Your directive could then look something like this:
function testDirective() {
  return {
    restrict: 'E',
    controller: 'TestController',
    controllerAs: 'vm',
    bindToController: true,
    scope: {},
    link: function(scope, element, attrs) {
      scope.elWidth0 = element.find("div")[0].clientWidth;
      scope.elWidth1 = element.find("div")[0].offsetWidth;

      console.log(scope.elWidth0);
      console.log(scope.elWidth1);
    }
  }
}


text:
Q: Logout functionality in OutSystems I am working on web app in OutSystems 10.0. In the application, if I log out, it logs off. But when I click the browser back Button, it redirects to the Previous page (which should be displayed only after login). Any suggestions?

A: You probably need to have roles on the pages, if the pages have the role anonymous anyone can open it.

A: You're probably accessing the website via http and not https, so when you press back on the browser it will show you a cached version of the previous page.
Because it's the cached version, the session and roles are not checked.
As a recommendation, force the https protocol.

A: Following the link provided by @Abdulhakeem, they recommend the following:

*

*Add a hidden input to the page - initialize it to some value (for example 'no') - so when the page is rendered by the server it always has a 'no'

*Add a bit of Javascript to the page ready event to:

*

*Check that value - if it's not what you'd expect from the server (in our case, <> 'no'), force refresh the page (see below)

*If it is still set to what you'd expect from the server, change it (in our case to 'yes') and do nothing else

I recommend downloading the .oml provided in the post and reviewing how they actually implemented it.

A: if you can change to https, you can also in every action that is on the page that do changes on the database. check if you have permissions or you are logged. that way if the person tries to do back and do some action you can redirect it somewhere.


text:
Q: Is it possible to specify the PayPal fixed donation amount in the querystring parameters? Let's suppose we have an <input> element where the user can enter a number (e.g. 500).
When clicking some button or so, I want the user to be redirected to the PayPal donation page where they can specify the ammount but to have the default value set to the number set in the input (500 in this case).
Does the PayPal url allows such an option (maybe via querystring parameters)?

A: Yes it is possible. You will need to create an open source Donation Button in order to have your donors add the donation amount from the form you create rather than on the PayPal Hosted page.
You need to add this to your donation button code
<input type="text"   name="amount" size=10>

Below is the complete Donation Button Sample code.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_donations">

<input type="hidden" name="business" value="youremail@email.com">
<input type="hidden" name="lc" value="US">

<input type="hidden" name="item_name" value="Test Donations">
Please Enter an Amount

<input type="text"   name="amount" size=10>

<input type="hidden" name="no_note" value="0">
<input type="hidden" name="cn" value="Add special instructions to the seller:">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHosted">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

</form>

Creating Donation Buttons


text:
Q: Laurent series of a complex multivariate function Suppose $f(x,y)$ to be a function  of variables $x$, $y$
$$
f(x,y)=\frac{-\left(\pi^{2}-4x^{2}\right)y\left(\pi^{2}-4y^{2}\right)\left(\pi^{2}\cos2x-4x(x-\pi\sin x)\right)}{\pi\left(\left(x^{2}+y^{2}\right)\left(64x^{2}y^{2}+4\pi^{4}\right)-64\pi^{2}x^{2}y^{2}+\pi\left(\pi^{2}-4y^{2}\right)^{2}\sin x(\pi\sin x-4x)\right)}.
$$
For $(x,y)\rightarrow(0,0)$ is $f(x,y)\rightarrow-\infty$. How to
find the Laurent series at $(0,0)$ for such complex form of the multivariate
function? Is it possible, or, only some numeric approach is available?
There are many samples of the elementary functions but more complicated examples are missing.
Mathematica provides the following solution:
f = -((Pi^2 - 4*x^2)*y*(Pi^2 - 4*y^2)*(Pi^2*Cos[2*x] - 4*x*(x - Pi*Sin[x])))/
     (Pi*(-64*Pi^2*x^2*y^2 + 4*Pi^4*(x^2 + y^2) + 64*x^2*y^2*(x^2 + y^2) +
      Pi*(Pi^2 -4*y^2)^2*Sin[x]*(-4*x + Pi*Sin[x])))
Normal[Series[f, {x, 0, 3}, {y, 0, 3}]]

$$x^2 \left(\left(\frac{16}{\pi ^4}-\frac{16}{\pi ^5}-\frac{4}{\pi ^3}\right) y^3+\frac{\frac{\pi }{4}-\frac{\pi ^2}{4}+\frac{\pi ^3}{16}}{y^3}+\left(\frac{12}{\pi ^3}-\frac{8}{\pi ^2}+\frac{1}{\pi }\right) y+\frac{2-\frac{3}{\pi }-\frac{\pi }{4}}{y}\right)+\frac{y}{\pi }-\frac{\pi }{4 y} + O(4).$$
Thanks for your help.


text:
Q: on trigger click event script called 2 time in first attempt I am creating an image gallary using owl carousel and php.there mouse click event working perfectly but when click command over keyboard having problem skip one image on prev keyup only and only first time. which code are calling after keyup function when write that code inside that function working perfectly
 $(document.documentElement).keyup(function(event) {
        // handle cursor keys
        if (event.keyCode == 37) {
        $(".prev").click();
    });

      var prevkey = $(".prev");
    prevkey.unbind("click").click(function() {
    $(".reset").click();
        setTimeout(function() {
            $(".printable").load(function(){
            $(".owl-carousel").myfunction();
        });
    }, 200);
    curEle = $(".item.active").parent();
   //console.log(curEle);
    if(curEle.find(".item").attr("data-id")==0)
    {
    $(this).addClass("disabled");
    }
    else
    {
    $(this).removeClass("disabled");
    prevEle = curEle.prev();
    console.log(prevEle);
    prevEle.find(".item").addClass("active");
                                curEle.find(".item").removeClass("active");
                                prevEle.find(".printable").attr("src",prevEle.find(".printable").attr("data-src"));
        carousel.trigger("owl.prev");
        curEle.find(".printable").attr("src","");
    }
    });

A: Insert preventDefault() to avoid other events than yours...
$(document.documentElement).keyup(function(event) {
    // handle cursor keys
    event.preventDefault();
    if (event.keyCode == 37) {
        $(".prev").click();
    }
});

EDIT check this answer if you're using IE8

A: try this using one will prevent a second call
$(".prev").one("click",function(){
//your stuff
});


text:
Q: Regex don't match more than once the pattern in incoming string I have a task to write a regex for a valid name. It has to consist two words, each word starts with capital letter, afterwards contains only lowercase letters, should be at least two letters long and the words are separated by a space.
string input = "Stephen King, Bruce hatow, eddie Lee, AShley Greene, Test Testov, Ann   Grey";

        string pattern = @"^\b[A-Z][a-z]{1,}\s\b[A-Z][a-z]{1,}$";

        MatchCollection output = Regex.Matches(input, pattern);

        foreach (Match item in output)
        {
            Console.Write(item);
        }

My pattern matches only if the string has one name. e.g. string input = "Stephen King". Is there a way to do it with string or I should use List of strings and check each one of them

A: Try removing the starting and ending anchors ^ and $.  Instead, replace them with word boundaries, allowing for a first/last name match to occur anywhere in the input string:
string input = "Stephen King, Bruce hatow, eddie Lee, AShley Greene, Test Testov, Ann   Grey";
string pattern = @"\b[A-Z][a-z]{1,}\s[A-Z][a-z]{1,}\b";
MatchCollection output = Regex.Matches(input, pattern);
foreach (Match item in output)
{
    Console.Write(item + "\n");
}

This prints:
Stephen King
Test Testov


text:
Q: Open layer properties dialog with PyQGIS When I have an object lyr of class QgsMapLayer, say iface.activeLayer() is there a way to open the layer properties dialog for that layer lyr at a specific tab, for example "Labels" using PyQGIS?
Something like lyr.openPropertiesDialog(currentTab = 'Labels')?
iface.actionLayerProperties().trigger() opens the dialog (for the active layer presumably), so I could use iface.setActiveLayer(lyr) before. But can I open it at a specific tab?

A: There is a function called QgisInterface::showLayerProperties to achieve exactly that. It expects a QgsMapLayer as first argument and a string identifying a page as second argument. All the available page names are listed in the documentation.
So in your example case to open the 'labels' tab it would be:
iface.showLayerProperties(iface.activeLayer(), 'mOptsPage_Labels')

iface.actionLayerProperties().trigger() does nothing else than invoking showLayerProperties on the active layer without specifying a page.


text:
Q: WiFi adapter works when directly connected, doesn't when plugged into hub I have only one USB port that works on my computer, and I usually use it for my mouse.
when I plug the Wi-Fi adapter into a powered USB hub, it doesn't work. However, it works fine when connected directly to the computer.
I tried it in Windows, and it works fine both through the hub, and when connected directly.
Any ideas as to why this strange behavior is occurring?


text:
Q: Accessing last values of multilevel Dictionaries I have a string input that I convert into a Dictionary. Usually the resulting Dictionary has multiple levels, i.e. a nested structure.
I would like to access its "leaf" elements, independently from the number of levels of the Dictionary.
Example:
# inputs arriving to my code from external users
input1 = "{'country':{'name':'Italy', 'region':'Europe'}}"
input2 = "{'country':{'first_country':{'name':'Italy', 'region':'Europe'}, 'second_country':{'name':'France', 'region':'Europe'}}}"

import ast
dict1 = ast.literal_eval(input1)
dict2 = ast.literal_eval(input2)

print(dict1)
>>> {'country': {'name': 'Italy', 'region': 'Europe'}}

print(dict2)
>>> {'country': {'first_country': {'name': 'Italy', 'region': 'Europe'}, 'second_country': {'name': 'France', 'region': 'Europe'}}}

Is there a way to access the fields name and region, independently from the passed dictionary?
I cannot know in advance the number of dictionary levels, as they depend from the input entered by external users. I would like to access the last level of the dictionary, independently from its levels.
EDIT
Let the code speak. The following code does what I want, but something in my brain suggests me avoiding the exec statement.
#swap Italy country with Germany, independently from the passed dictionary
def levels(d):
    return max(count(v) if isinstance(v,dict) else 0 for v in d.values()) + 1

def swapCountry(inputDict):
    if levels(inputDict) == 2:
        path = "dict1['country']['name']"
    elif levels(inputDict) == 3:
        path = "dict2['country']['first_country']['name']"

    exec('{} = "Germany"'.format(path))

Therfore:
swapCountry(dict1)
print(dict1)
>>> {'country': {'name': 'Germany', 'region': 'Europe'}}

swapCountry(dict2)
print(dict2)
>>> {{'country': {'first_country': {'name': 'Germany', 'region': 'Europe'}, 'second_country': {'name': 'France', 'region': 'Europe'}}}

A: Here is a simple way:
import ast

def get_leafs(d):
    res = [leaf for v in d.values() if isinstance(v, dict) for leaf in get_leafs(v)]
    if not res:
        res = [d]
    return res

# inputs arriving to my code from external users
input1 = "{'country':{'name':'Italy', 'region':'Europe'}}"
input2 = "{'country':{'first_country':{'name':'Italy', 'region':'Europe'}, 'second_country':{'name':'France', 'region':'Europe'}}}"
dict1 = ast.literal_eval(input1)
dict2 = ast.literal_eval(input2)

print(get_leafs(dict1))
# [{'name': 'Italy', 'region': 'Europe'}]
print(get_leafs(dict2))
# [{'name': 'Italy', 'region': 'Europe'}, {'name': 'France', 'region': 'Europe'}]

If you prefer to do it with a generator:
def get_leafs_gen(d):
    if any(isinstance(v, dict) for v in d.values()):
        yield from (leaf for v in d.values() if isinstance(v, dict) for leaf in get_leafs(v))
    else:
        yield d

print(*get_leafs_gen(dict1))
# {'name': 'Italy', 'region': 'Europe'}
print(*get_leafs_gen(dict2))
# {'name': 'Italy', 'region': 'Europe'} {'name': 'France', 'region': 'Europe'}

EDIT: If you prefer to have the keys that take you to each leaf, you can have something like this:
def get_leaf_keys_gen(d):
    if any(isinstance(v, dict) for v in d.values()):
        for k, v in d.items():
            if isinstance(v, dict):
                for leaf_key in get_leaf_keys_gen(v):
                    yield (k,) + leaf_key
    else:
        yield ()

print(*get_leaf_keys_gen(dict1))
# ('country',)
print(*get_leaf_keys_gen(dict2))
# ('country', 'first_country') ('country', 'second_country')

Then to actually retrieve the leaves:
def get_from_multikey(d, key):
    if not key:
        return d
    else:
        return get_from_multikey(d[key[0]], key[1:])

print(*(get_from_multikey(dict1, key) for key in get_leaf_keys_gen(dict1)))
# {'name': 'Italy', 'region': 'Europe'}
print(*(get_from_multikey(dict2, key) for key in get_leaf_keys_gen(dict2)))
# {'name': 'Italy', 'region': 'Europe'} {'name': 'France', 'region': 'Europe'}

EDIT 2: Added yet another alternative to apply a visitor function to each leaf:
def visit_leaves(d, visitor):
    if any(isinstance(v, dict) for v in d.values()):
        for v in d.values():
            if isinstance(v, dict):
                visit_leaves(v, visitor)
    else:
        visitor(d)

# Adds a new item 'n' to every leaf in dict1
visit_leaves(dict1, lambda leaf: leaf.setdefault('n', 0))
print(dict1)
# {'country': {'name': 'Italy', 'region': 'Europe', 'n': 0}}

# Removes 'region' from every leaf in dict2
visit_leaves(dict2, lambda leaf: leaf.pop('region', None))
print(dict2)
# {'country': {'first_country': {'name': 'Italy'}, 'second_country': {'name': 'France'}}}


text:
Q: Script for LaTeX formula to image conversion
Possible Duplicate:
TeX to image over command line

Is there a script for converting LaTeX math formulae (not document) to PNG, GIF or JPEG?

A: You can use TeX to GIF or PNG for this.

A: I really like Tex2im because:

*

*It's a simple bash script

*It doesn't require a document wrapper or \begin{equation}

*It supports stuff other than formulae (see the -n argument)

*It's easy to customize text and background colors, or to get a transparent background

*Your preferred default values can be set in a .tex2imrc file

It requires a working LaTeX installation and ImageMagick.


text:
Q: Local IIS in Windows 10 can be accessed using 127.0.0.1 and localhost, but not by mean of its IP I have a notebook with Windows 10.
I have installed IIS, then,I have tried to browse, using a browser in the same notebook, to URL 127.0.0.1, it shows default web site. Then, I used localhost, and the same, it shows default web site. However, I used its IP, and the site delays a time and then it shows the message:

This site cannot be accessed
IP delays too much to reply.
ERR_CONNECTION_TIME_OUT

(sorry if the above text is not exact as the messages in English version of Windows. I have Spanish version)
Bindings of the default web site is set to "all assigned ip". I tried by explicitly set that combobox to its IP, but the same problem happens.
How can I solve it?
Thanks
Jaime

A: There's really no reason to try to access the website on your local machine from your own machine using the machine's IP address.
You're trying to troubleshoot something that won't ever happen on its own.
Reference the site by DNS name (you can use your c:\windows\system32\drivers\etc\hosts file to define this if you don't have an internal DNS server), use 'localhost' as you already said works.


text:
Q: Pretty Print JSON with JBuilder I am using JBuilder as a JSON DSL. I have it working properly but cannot figure out how to pretty print JSON.
I want to use JSON.pretty_generate but that requires a string or a hash, and JBuilder is a custom JBuilder object that does not convert.
Any ideas how to pretty print JSON with JBuilder template?

A: Try parsing the JBuilder output, then using JSON.pretty_generate on that resulting output
json_builder = Jbuilder.encode do |json|
  ... your json.data ...
end

json_obj = JSON.parse(json_builder)
puts       JSON.pretty_generate(json_obj)

A: I use pretty output for all my JSON in development by using an initializer for multi_json (the current backend for jbuilder):
In config/initializers/multi_json.rb
require 'multi_json'

MultiJson.dump_options = { pretty: true } if Rails.env.development?


text:
Q: Open embedded mpp file in Excel I do have project file(mpp) embedded as object in my excel file. My vba script below that will open the embedded file. But stuck and received runtime error in this line --> oEmbFile.Verb Verb:=xlPrimary
.
Thank you in advance
Private Sub Project_Click()
Dim x As MSProject.Application
Dim oEmbFile As Object

'// Opens object

Application.DisplayAlerts = False
Set oEmbFile = ThisWorkbook.Sheets("Execution_plan").OLEObjects("Object 1")
oEmbFile.Verb Verb:=xlPrimary
Application.DisplayAlerts = True
'Look for existing instance
On Error Resume Next
Set x = GetObject("Project.Application")

AppActivate ("Microsoft Project")
Set x = Nothing
Set oEmbFile = Nothing

End Sub

A: Try using the Activate method instead. You could do something like this where you try the Verb method first and if if fails, try the Activate method:
Private Sub Project_Click()
Dim x As MSProject.Application
Dim oEmbFile As OLEObject

Application.DisplayAlerts = False
Set oEmbFile = ThisWorkbook.Sheets("Execution_plan").OLEObjects("Object 1")
On Error Resume Next
oEmbFile.Verb Verb:=xlPrimary
If Err.Number <> 0 Then
    oEmbFile.Activate
End If

Application.DisplayAlerts = True
'Look for existing instance
Set x = GetObject("Project.Application")

AppActivate ("Microsoft Project")
Set x = Nothing
Set oEmbFile = Nothing

End Sub


text:
Q: Table shows blank spaces I was trying to make this table but it has blank spaces and I don't know why?
Can someone tell me how to fix this?

This is my code:
\documentclass{article}
\begin{document}
\renewcommand{\arraystretch}{1.3}
\small
\begin{table}[ht]
\begin{tabular}{|c|c|c|c|c|}
\hline
& \multicolumn{4}{|c|}{Display Format}& \\ \cline{2-5}
&\multicolumn{2}{|c|}{High information density}& \multicolumn{2}{|c|}{Low information density} &\\ \hline
Cookie type & Noticeable& Non-noticeable& Noticeable& Non-noticeable\\ \hline
1\textsuperscript{st} &Group 1&Group 2& Group 3&Group 4\\ \hline
1\textsuperscript{st}/3\textsuperscript{rd}&Group 5& Group 6&Group 7&Group 8\\ \hline
\end{tabular}
\caption{Number of respondents per treatment}
\label{table:1}
\end{table}
\end{document}

A: The first and second row has an additional &. TeX throws an error message and makes a new row as error recovery:
! Extra alignment tab has been changed to \cr.
<template> \endtemplate

l.9 & \multicolumn{4}{|c|}{Display Format}&
                                             \\ \cline{2-5}

Fixed example including Mico's fix:
\documentclass{article}
\begin{document}
\renewcommand{\arraystretch}{1.3}
\small
\begin{table}[ht]
  \begin{tabular}{|c|c|c|c|c|}
    \hline
    & \multicolumn{4}{c|}{Display Format}\\ \cline{2-5}
    & \multicolumn{2}{c|}{High information density}& \multicolumn{2}{c|}{Low information density}\\ \hline
    Cookie type & Noticeable& Non-noticeable& Noticeable& Non-noticeable\\ \hline
    1\textsuperscript{st} &Group 1&Group 2& Group 3&Group 4\\ \hline
    1\textsuperscript{st}/3\textsuperscript{rd}&Group 5& Group 6&Group 7&Group 8\\ \hline
  \end{tabular}
  \caption{Number of respondents per treatment}
  \label{table:1}
\end{table}
\end{document}

BTW, \small is set outside of the table environment. Thus it does not change the font size inside, because floating environments usually reset the font at the beginning.
\documentclass{article}
\begin{document}
\begin{table}[ht]
  \small
  \begin{tabular}{|c|c|c|c|c|}
    \hline
    & \multicolumn{4}{c|}{Display Format} \\ \cline{2-5}
    & \multicolumn{2}{c|}{High information density}& \multicolumn{2}{c|}{Low information density}\\ \hline
    Cookie type & Noticeable& Non-noticeable& Noticeable& Non-noticeable\\ \hline
    1\textsuperscript{st} &Group 1&Group 2& Group 3&Group 4\\ \hline
    1\textsuperscript{st}/3\textsuperscript{rd}&Group 5& Group 6&Group 7&Group 8\\ \hline
  \end{tabular}
  \caption{Number of respondents per treatment}
  \label{table:1}
\end{table}
\end{document}

Finally a version with package booktabs, less and better lines and spacing:
\documentclass{article}
\usepackage{booktabs}
\usepackage{caption}
\usepackage[normal]{engord}% no option or option "raise" for raised suffixes

\begin{document}
\begin{table}[ht]
  \caption{Number of respondents per treatment}
  \label{table:1}
  \begin{tabular}{ccccc}
    \toprule
    & \multicolumn{4}{c}{Display Format}\\
    \cmidrule(lr){2-5}
    & \multicolumn{2}{c}{High information density} &
    \multicolumn{2}{c}{Low information density}\\
    \cmidrule(lr){2-3}
    \cmidrule(lr){4-5}
    Cookie type & Noticeable & Non-noticeable &
    Noticeable & Non-noticeable\\
    \midrule
    \engordnumber{1} & Group 1 & Group 2 & Group 3 & Group 4\\
    \engordnumber{1}/\engordnumber{3} &
    Group 5 & Group 6 & Group 7 & Group 8\\
    \bottomrule
  \end{tabular}
\end{table}
\end{document}

A: By using the c column type for the four data columns, one ends up with noticeably different widths for these columns. IMHO, this makes for a less-than-optimal "look". I would like to suggest, therefore, that you use a column type that assures that the four data columns are all equally wide. One such column type is the X type, provided by the tabularx package.
I would further like to suggest that you (a) give the table a more "open" appearance -- mostly by omitting all vertical lines and by using the macros \toprule, \midrule, \bottomrule and \cmidrule, provided by the booktabs package instead of \hline and \cline -- and (b) provide more visual structure to the three-row header in order to help the reader take in the information more easily.

\documentclass{article}
\usepackage{booktabs,tabularx}
\newcolumntype{C}{>{\centering\arraybackslash}X} % centered "X" columns
\begin{document}

\begin{table}
\setlength\tabcolsep{3pt} % default value: 6pt
\begin{tabularx}{\textwidth}{@{}lCCCC@{}}
\toprule
Cookie type & \multicolumn{4}{c@{}}{Display Format} \\
\cmidrule(l){2-5}
&\multicolumn{2}{c}{High information density}
&\multicolumn{2}{c@{}}{Low information density} \\
\cmidrule(lr){2-3} \cmidrule(l){4-5}
& Noticeable& Non-noticeable& Noticeable& Non-noticeable\\
\midrule
1\textsuperscript{st} &Group 1&Group 2& Group 3&Group 4\\
1\textsuperscript{st}/3\textsuperscript{rd}&Group 5& Group 6&Group 7&Group 8\\
\bottomrule
\end{tabularx}
\caption{Number of respondents per treatment}
\label{table:1}
\end{table}

\end{document}


text:
Q: Google Adwords V201402 get campaign data I am new in google adwords. i want to know how to get campaign data like impression, click, CTR, avg.pos etc. using php. i search alot in google i got one code but this code is in v201306 and i am using v201402. i tried to implement this code in my new version but its not working it is giving me field error. at below i pasted that code and its source link.
<?php
/**
 * This example gets various statistics for campaigns that received at least one
 * impression during the last week. To get campaigns, run GetCampaigns.php.
 *
 * Tags: CampaignService.get
 *
 * Copyright 2012, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201306
 * @category   WebServices
 * @copyright  2012, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 * @author     Eric Koleda
 */

// Include the initialization file
require_once dirname(dirname(__FILE__)) . '/init.php';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $campaignId the ID of the campaign to get stats for
 */
function GetCampaignStatsExample(AdWordsUser $user) {
  // Get the service, which loads the required classes.
  $campaignService = $user->GetService('CampaignService', ADWORDS_VERSION);

  // Create selector.
  $selector = new Selector();
  $selector->fields =
      array('Id', 'Name', 'Impressions', 'Clicks', 'Cost', 'Ctr');
  $selector->predicates[] =
      new Predicate('Impressions', 'GREATER_THAN', array(0));

  // Set date range to request stats for.
  $dateRange = new DateRange();
  $dateRange->min = date('Ymd', strtotime('-1 week'));
  $dateRange->max = date('Ymd', strtotime('-1 day'));
  $selector->dateRange = $dateRange;

  // Create paging controls.
  $selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);

  do {
    // Make the get request.
    $page = $campaignService->get($selector);

    // Display results.
    if (isset($page->entries)) {
      foreach ($page->entries as $campaign) {
        printf("Campaign with name '%s' and id '%s' had the following stats "
            . "during the last week:\n", $campaign->name, $campaign->id);
        printf("  Impressions: %d\n", $campaign->campaignStats->impressions);
        printf("  Clicks: %d\n", $campaign->campaignStats->clicks);
        printf("  Cost: $%.2f\n", $campaign->campaignStats->cost->microAmount
            / AdWordsConstants::MICROS_PER_DOLLAR);
        printf("  CTR: %.2f%%\n", $campaign->campaignStats->ctr * 100);
      }
    } else {
      print "No matching campaigns were found.\n";
    }

    // Advance the paging index.
    $selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
  } while ($page->totalNumEntries > $selector->paging->startIndex);
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Run the example.
  GetCampaignStatsExample($user);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Its source link is
http://code.google.com/p/google-api-adwords-php/source/browse/examples/AdWords/v201306/Reporting/GetCampaignStats.php?spec=svnf9556a1c2a3c4bce0345c9e988d875d5977e0f3f&r=f9556a1c2a3c4bce0345c9e988d875d5977e0f3f

A: Your code is not working because Google removed all stats fields from several of its Adwords API services, including CampaignService, with the release of v201309.
To get campaign stats in v201309 or v201402, you will need to use CAMPAIGN_PERFORMANCE_REPORT instead.
Here is a PHP example of how to download a report.  The example uses CRITERIA_PERFORMANCE_REPORT, whereas you are looking for CAMPAIGN_PERFORMANCE_REPORT, but code will be very similar.
You should be able to use the same selector as in your original code above.


text:
Q: desktop shortcut does not work I have created batch file that start apache and mysql server,copy try.exe on desktop and run project in browser.that works fine.but onclick desktop shorcut error occured.error is windows can not find mysql_start.exe. actully i convert try.bat into try.exe. IN installation folder it work fine,but on shortcut error occured.                                  the code is:
@echo off
echo Diese Eingabeforderung nicht waehrend des Running beenden
echo Bitte erst bei einem gewollten Shutdown schliessen
echo Please close this command only for Shutdown
echo Apache 2 is starting ...

start  xampp_start.exe /h
start   firefox.exe http://localhost/xampp/newamcs12/index.php
copy "try.exe" %userprofile%\desktop
if errorlevel 255 goto finish
if errorlevel 1 goto error
goto finish

:error
echo.
echo Apache konnte nicht gestartet werden
echo Apache could not be started

pause

:finish
CLS
EXIT

A: It all looks right to me.  Try double-checking your file name and user name, as @:Prof Pickle said.


text:
Q: Convert CDF $F$ to $G $ defined by $G(x) = P(XLet $X$ be a r.v. whose possible values are $0, 1, 2,... ,$ with CDF $F$. In some
countries, rather than using a CDF, the convention is to use the function $G $defined
by $G(x) = P(X<x)$ to specify a distribution. Find a way to convert from F to G,
i.e., if F is a known function show how to obtain $G(x)$ for all real $x$.
Answer
First
$G(x) = P(X \le x)  - P(X = x) = F(x) - P(X = x)$
If $x$ is not a nonnegative integer, then $P(X = x) = 0 $ so $ G(x) = F(x)$.
(first, wouldn't $P(X \le x)$ also be equal to 0, so G(x) = F(x) = 0 anyways? Otherwise I understand up until this part, but I would appreciate help understanding the rest of this answer)
For $x$ a
nonnegative integer,
$P(X = x) = F(x) - F(x - 1/2)$
since the PMF corresponds to the lengths of the jumps in the CDF. (The 1/2 was
chosen for concreteness; we also have $F(x - 1/2) = F(x - a)$ for any $a \in (0, 1]$.)
$$G(x) = \begin{cases}
  F(x), & \text{if } x \not\in \{0, 1, 2,... \}\\
  F(x - 1/2), & \text{if } x \in \{0, 1, 2,... \}
\end{cases}
$$

A: $$G(x)=F(x^-):=\lim_{y\to x,\ y\lt x}F(y)$$

A: $G\left ( x \right ) = P\left ( X< x \right ) = P \left ( X \leq  x - 1 \right ) \forall x \in \mathbb{N}
\rightarrow  F\left ( x - 1 \right )$


text:
Q: JavaMail repository for maven not found I want to import this dependency:
https://mvnrepository.com/artifact/javax.mail/javax.mail-api/1.6.2
<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.6.2</version>
</dependency>

in my maven project from Intellij, but I get an error at artifactId and version:
Dependency 'javax.mail:javax.mail-api:1.6.2' not found


text:
Q: can not send const value to operator+ that use operator[][] I want to implement a matrix class that use operator [][] .
I wrote the below code but the problem is that I cant send const value to operator+ !!(error: passing 'const Matrix' as 'this' argument of 'Matrix::Indexer Matrix::operator' discards qualifiers [-fpermissive])
If I change it to Matrix operator+(Matrix& other);  It works fine...
I think I need two overload of Matrix::Indexer Matrix::operator[](int index) one for reading and one for writing to mat_ (like property in c# !) But how ?!
or may be I should use const_cast ?!
What is the best way to implement this class ?!
//Matrix.h
class Matrix
{
public:
    Matrix(const int rows, const int cols, float defaultValue=0);
    //TODO copy constructor , destructor

    int rows() const;
    int cols() const;

    Matrix operator+(const Matrix& other);

    class Indexer
    {
    public:
        Indexer(float* arr,int cols);
        float& operator[](int index);
    private:
        float* arr_;
        int cols_;
    };

    Indexer operator[](int index);

private:
    int rows_;
    int cols_;
    float **mat_;

};

Matrix.cpp
#include "matrix.h"

Matrix::Matrix(const int rows, const int cols, float defaultValue) :
    rows_(rows),
    cols_(cols)
{
    mat_=new float*[rows_];

    for(int i=0;i<rows;i++)
    {
        mat_[i]=new float[cols];
    }

    for(int i=0;i<rows;i++)
    {
        for(int j=0;j<cols;j++)
        {
            mat_[i][j]=defaultValue;
        }
    }

}

int Matrix::rows() const
{
    return rows_;
}
int Matrix::cols() const
{
    return cols_;
}

Matrix::Indexer::Indexer(float* arr,int cols):
    arr_(arr),
    cols_(cols)
{}

Matrix::Indexer Matrix::operator[](int index)
{
    if(index>=rows_)
        throw "Out of row index";
    return Indexer(mat_[index],cols_);
}

float& Matrix::Indexer::operator[](int index)
{
    if(index>=cols_)
       throw "Out of cols index";
    return arr_[index];
}

 Matrix Matrix::operator+(const Matrix& other)//error
 {
     if(other.rows()!=this->rows()||other.cols()!=this->cols())
         throw "rows and cols are not equal";
     Matrix result(other.rows(),other.cols());
     for(int i=0;i<rows();i++)
     {
         for(int j=0;j<cols();j++)
         {
             result[i][j]=mat_[i][j]+other[i][j];//error: passing 'const Matrix' as 'this' argument of 'Matrix::Indexer Matrix::operator' discards qualifiers [-fpermissive
         }

     }
     return result;
 }

A: Your operator+ should be a const member function, since it doesn't modify the object it is called on.  For the rest, you'll probably need a ConstIndexer and an operator[]( int index ) const as well.
And totally unrelated to your question, but: you'd probably be better off using an std::vector<float> for the actual data.  It's both easier to use, and (probably) faster.

A: I fixed my problem by adding
const Indexer operator[](int index)const;

and
const float& operator[](int index)const;

My code :
Matrix.h
#ifndef MATRIX_H
#define MATRIX_H

#include <iostream>

class Matrix
{
public:
    Matrix(const int rows, const int cols, float defaultValue=0);
    //TODO copy constructor , destructor

    int rows() const;
    int cols() const;

    Matrix operator+(const Matrix& other) const;

    class Indexer
    {
    public:
        Indexer(float* arr,int cols);
        const float& operator[](int index)const;
        float& operator[](int index);
    private:
        float* arr_;
        int cols_;
    };

    Indexer operator[](int index);
    const Indexer operator[](int index)const;

    friend std::ostream& operator<<(std::ostream& os,const Matrix& m);

private:
    int rows_;
    int cols_;
    float **mat_;
};

#endif // MATRIX_H

Matrix.cpp
#include "matrix.h"

Matrix::Matrix(const int rows, const int cols, float defaultValue) :
    rows_(rows),
    cols_(cols)
{
    mat_=new float*[rows_];

    for(int i=0;i<rows;i++)
    {
        mat_[i]=new float[cols];
    }

    for(int i=0;i<rows;i++)
    {
        for(int j=0;j<cols;j++)
        {
            mat_[i][j]=defaultValue;
        }
    }

}

int Matrix::rows() const
{
    return rows_;
}
int Matrix::cols() const
{
    return cols_;
}

Matrix::Indexer::Indexer(float* arr,int cols):
    arr_(arr),
    cols_(cols)
{}

const float &Matrix::Indexer::operator[](int index) const
{
    if(index>=cols_)
       throw "Out of cols index";
    return arr_[index];
}

Matrix::Indexer Matrix::operator[](int index)
{
    if(index>=rows_)
        throw "Out of row index";
    return Indexer(mat_[index],cols_);
}

const Matrix::Indexer Matrix::operator[](int index) const
{
    if(index>=rows_)
        throw "Out of row index";
    return Indexer(mat_[index],cols_);
}

std::ostream& operator<<(std::ostream &os, const Matrix &m)
{
    for(int i=0;i<m.rows();i++)
    {
        for(int j=0;j<m.cols();j++)
        {
            os<<m[i][j]<<" ";
        }
        os<<"\n";
    }
    return os;
}

float& Matrix::Indexer::operator[](int index)
{
    if(index>=cols_)
       throw "Out of cols index";
    return arr_[index];
}

 Matrix Matrix::operator+(const Matrix& other) const
 {
     if(other.rows()!=this->rows()||other.cols()!=this->cols())
         throw "rows and cols are not equal";
     Matrix result(other.rows(),other.cols());
     for(int i=0;i<rows();i++)
     {
         for(int j=0;j<cols();j++)
         {
             result[i][j]=mat_[i][j]+other[i][j];
         }

     }
     return result;
 }


text:
Q: Why did Google invalidate all OAuth2 access tokens today? What happened to your OAuth2/token servers today around 7am PST?
URL: https://accounts.google.com/o/oauth2/token
Token refreshing failed (credential.refreshToken()==false) for all our Google users resulting in losing access tokens and connectivity for hundreds of our clients!
Then for a while our users could not re-authorize as Google was returning 503 Unavailable and CAPTURE in response to the following API call:
GoogleAuthorizationCodeFlow gacf =
            new GoogleAuthorizationCodeFlow.Builder(new NetHttpTransport(),
                new JacksonFactory(), appId,
                appSecret, scopes).build();
tokenResponse = gacf.newTokenRequest(code).setRedirectUri(<callback_url>).execute();

com.google.api.client.auth.oauth2.TokenResponseException: 503 Service Unavailable

Our systems have detected unusual traffic from your computer network.  This page checks to see if it's really you sending the requests, and not a robot.

After a while everything started working again only now we have hundreds of clients for whom our service stopped working because there is no valid OAuth2 access tokens anymore.
Can you please explain what Google did earlier today and how it managed to invalidate all the tokens? How can we find out what "unusual traffic" it detected?
Thank you

A: You on AppEngine??
if so, maybe it's this...
SUMMARY:
On Thursday 5 March 2015, for a duration of 84 minutes, Google App Engine applications that accessed some Google APIs over HTTP experienced elevated error rates. We apologize for any impact this incident had on your service or application, and have made immediate changes to prevent this issue from recurring.
DETAILED DESCRIPTION OF IMPACT:
On Thursday 5 January, from 07:04 AM to 08:28 AM, some Google App Engine applications making calls to other Google APIs via HTTP experienced elevated error rates. During the incident, the global error rate for all API calls remained under 1%, and in total, the outage affected 2% of applications that were active during the incident.  The effect on those applications was significant: requests to issue OAuth tokens experienced an error rate of over 85%. In addition, the HTTP APIs to googleapis.com/storage and googleapis.com/gmail received error rates between 50% and 60%. Other googleapis.com endpoints were affected with error rates of 10% to 20%.
ROOT CAUSE:
A component in Google's shared HTTP load balancing fabric experienced a non-malicious increase in traffic, exceeding its provisioned capacity. This triggered an automatic DoS protection which shunted a portion of the incoming traffic to a CAPTCHA.  The unexpected response caused some clients to issue automated retries, exacerbating the problem.
REMEDIATION AND PREVENTION:
Google Engineers were alerted to the issue by automated monitoring at 07:02, as the load balancing system detected excess traffic and attempted to automatically mitigate it. At 07:46, Google Engineers enabled standby load balancing capacity to rectify the issue. From 08:15 to 08:40, Google Engineers continued to provision additional resources in the load balancing fabric in order to serve the increased traffic. During this period, at 08:28, Google engineers determined that sufficient capacity was in place to serve both regular and retry traffic, and instructed the load balancing system to cease mitigation and resume normal traffic serving.  This action marked the end of the event.
To prevent this issue from recurring, Google engineers are comprehensively re-examining the affected load balancing fabric to ensure it is and remains correctly provisioned.  Additionally, Google engineers are improving monitoring rules to provide an early warning of capacity shortfall. Finally, Google engineers are examining the services that depend on this load balancing system, and will move some services to a separate pool of more easily scalable load balancers where appropriate.


text:
Q: call javascript function from a tag in foreach i'm trying to call a javascript function from a tag , but for some reasons i can't get it work i don't get an alert at all, if i delete the call of function goToprofile i get the json readin right , does the place of the function affects if he can read it ?
my html page :
<!DOCTYPE html>

*

*You need to close all HTML tags properly. For example your . This is a problem with the  and
 tags in your file as well.

*You need to include jQuery somewhere in order to access its functions. You can tell a jQuery function apart from standard javascript functions if they start with $

*The formatting of your html strings in the load() function are incorrect as @Quentin pointed out so I included his fix in my code snippet.

*The function names you are calling have typos in them. As @user78403 pointed out onload=loadings() should be replaced with onload=load() and function goToprofile(Theuser) should be replaced with function goToProfile(Theuser)
There might be additional minor syntax errors in the file but this should give you a good start. I would recommend downloading an IDE if you haven't already which will have some helpful tools for identifying syntax errors in your code. A good one to start with is Sublime Text. I would also recommend starting with a very simple HTML file and then successively building on it once you know it runs. Using your file as an example, it would have been better to start with an empty  and a simple load function like function load() {
  alert('hi!');
}
Hope this helps


text:
Q: Что означает Class.this Я знаю два случая когда используется ключевое слово this:

*

*когда вызываем нестатический метод на каком-нибудь объекте, то this неявно передается в параметр этого метода и возвращает ссылку на этот объект;

*когда мы хотим вызвать один конструктор из другого, здесь this тоже является ссылкой на объект который инициализируется в конструкторе;

Получается, что this - это ссылка на объект. Тогда у меня возникает вопрос, что означает эта запись:
Class.this
Что здесь может возвращать this, если в классе я не создавал никаких объектов. Чем здесь является this?

A: Записи типа Class.this используются во вложенных или анонимных классах, когда из них нам нужно сослаться на объект включающего их класса. Class - имя внешнего (включающего) сласса, this - ссылка на экземпляр внешнего (включающего) класса. Если вы вложенном классе или анонимном классе обратитесь, просто по this, то вы сошлётесь на текущий объект этого вложенного или анонимного класса, а не на объект внешнего.

A: Это контекст текущего объекта этого класса, т.е.:
package com.lampa;

public class Main {
    public Main() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                this.test(); // ошибка, т.к. this это Runnable
                Main.this.test();
            }
        }).start();
    }

    private void test() {
        System.out.println("test");
    }

    public static void main(String[] args) {
        new Main();
    }
}


text:
Q: Enabling new API to already published Gsuite APP We already have our G-suite market place APP published and enabled with the below API

*

*Google Drive API

*Admin SDK API
Now we want to enable the new API which is "Drive Activity API"

Wanted to know the impact of enabling the new API. Will this have any effect with existing APIs for our customers? And any other impact? Please assist.
Thankyou.

A: There should be no issue when adding another api in your existing app but you might need to publish the app again and request for a new OAuth verification to access the newly added API.
Reference
Update or unpublish an app listing
OAuth 2.0 Scopes for Google APIs


text:
Q: Use of "whenever" or "when" instead of "if" in logical sentences The conjunction "if" is used a lot in scientific writing. I wonder if it is correct to replace it with "when" and/or "whenever".
For example, instead of writing:

(1) a · b = 0 if a, b are orthogonal.

writing

(2) a · b = 0 whenever a, b are orthogonal.

or

(3) a · b = 0 when a, b are orthogonal.

I read sentences like (2) and (3) in many scientific articles, but they were not written by English speakers, so I am not sure if they are correct.

A: They are all equally correct and equivalent one-way statements of implication. In other words, none of them means the two way "iff".
They all say:
a, b are orthogonal implies a · b = 0
or
orthogonal(a,b) => a . b = 0


text:
Q: How to log output from Airflow DAG for debugging? I am writing a Airflow DAG and having some problems with a function. I am trying to debug by printing data to stdout and using the logging library.
My example DAG is:
    from datetime import timedelta

    import airflow
    import logging

    from airflow.models import DAG
    from airflow.operators.dummy_operator import DummyOperator
    from airflow.contrib.hooks.datadog_hook import DatadogHook

    def datadog_event(title, text, dag_id, task_id):
        hook = DatadogHook()
        tags = [
            f'dag:{dag_id}',
            f'task:{task_id}',
        ]

        hook.post_event(title, text, tags)

    def datadog_event_success(context):
        dag_id = context['task_instance'].dag_id
        task_id = context['task_instance'].task_id
        text = f'Airflow DAG failure for {dag_id}\n\nDAG: {dag_id}\nTasks: {task_id}'
        title = f'Airflow DAG success for {dag_id}'

        logging.info(title)
        logging.info(text)
        logging.info(dag_id)
        logging.info(task_id)

        datadog_event(title, text, dag_id, task_id)

    args = {
        'owner': 'airflow',
        'start_date': airflow.utils.dates.days_ago(2),
    }

    dag = DAG(
        dag_id='example_callback',
        default_args=args,
        schedule_interval='*/5 * * * *',
        dagrun_timeout=timedelta(minutes=60),
        on_success_callback=datadog_event_success,
    )

    my_task = DummyOperator(
        task_id='run_this_last',
        dag=dag,
    )

During a run I get an error:
airflow[9490]: Process DagFileProcessor4195-Process:
airflow[9490]: Traceback (most recent call last):
airflow[9490]:   File "/usr/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
airflow[9490]:     self.run()
airflow[9490]:   File "/usr/lib/python3.6/multiprocessing/process.py", line 93, in run
airflow[9490]:     self._target(*self._args, **self._kwargs)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/jobs/scheduler_job.py", line 148, in _run_file_processor
airflow[9490]:     result = scheduler_job.process_file(file_path, pickle_dags)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/utils/db.py", line 74, in wrapper
airflow[9490]:     return func(*args, **kwargs)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/jobs/scheduler_job.py", line 1542, in process_file
airflow[9490]:     self._process_dags(dagbag, dags, ti_keys_to_schedule)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/jobs/scheduler_job.py", line 1239, in _process_dags
airflow[9490]:     self._process_task_instances(dag, tis_out)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/utils/db.py", line 74, in wrapper
airflow[9490]:     return func(*args, **kwargs)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/jobs/scheduler_job.py", line 732, in _process_task_instances
airflow[9490]:     run.update_state(session=session)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/utils/db.py", line 70, in wrapper
airflow[9490]:     return func(*args, **kwargs)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/models/dagrun.py", line 318, in update_state
airflow[9490]:     dag.handle_callback(self, success=True, reason='success', session=session)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/utils/db.py", line 70, in wrapper
airflow[9490]:     return func(*args, **kwargs)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/models/dag.py", line 620, in handle_callback
airflow[9490]:     callback(context)
airflow[9490]:   File "/home/airflow/analytics/etl_v2/airflow_data/dags/example_bash_operator_andy.py", line 68, in datadog_event_success
airflow[9490]:     datadog_event(title, text, dag_id, task_id)
airflow[9490]:   File "/home/airflow/analytics/etl_v2/airflow_data/dags/example_bash_operator_andy.py", line 45, in datadog_event
airflow[9490]:     hook.post_event(title, text, tags)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/contrib/hooks/datadog_hook.py", line 157, in post_event
airflow[9490]:     self.validate_response(response)
airflow[9490]:   File "/home/airflow/virtualenv/lib/python3.6/site-packages/airflow/contrib/hooks/datadog_hook.py", line 58, in validate_response
airflow[9490]:     if response['status'] != 'ok':
airflow[9490]: KeyError: 'status'

But none of my logged into is before or after the error in the scheduler, webserver, worker, or task logs.
I have tested the datadog_event call on my Airflow worker by manually importing the code and it logs properly when I run it that way:
airflow@airflow-worker-0:~/analytics$ /home/airflow/virtualenv/bin/python -i /home/airflow/analytics/etl_v2/airflow_data/dags/example_bash_operator_andy.py
[2019-08-07 20:48:01,890] {settings.py:213} INFO - settings.configure_orm(): Using pool settings. pool_size=5, max_overflow=10, pool_recycle=1800, pid=29941
[2019-08-07 20:48:02,227] {__init__.py:51} INFO - Using executor DaskExecutor

>>> datadog_event('My title', 'My task', 'example_bash_operator_andy', 'run_this_last')
[2019-08-07 20:51:17,542] {datadog_hook.py:54} INFO - Setting up api keys for Datadog
[2019-08-07 20:51:17,544] {example_bash_operator_andy.py:38} INFO - My title
[2019-08-07 20:51:17,544] {example_bash_operator_andy.py:39} INFO - My task
[2019-08-07 20:51:17,544] {example_bash_operator_andy.py:40} INFO - example_bash_operator_andy
[2019-08-07 20:51:17,545] {example_bash_operator_andy.py:41} INFO - run_this_last
[2019-08-07 20:51:17,658] {api_client.py:139} INFO - 202 POST https://api.datadoghq.com/api/v1/events (113.2174ms)

My airflow.cfg is posted at https://gist.github.com/andyshinn/d743ddc61956ed7440c500fca962ce92 and I am using Airflow 1.10.4.
How can I output logging or messages from the DAG itself to better debug what might be happening?

A: DAG-level callbacks (on_success, on_failure) occur in the main scheduler loop.  See this open issue to move execution of these functions out of the scheduler thread. Exceptions raised in your callback function will appear in the scheduler logs. However, annoyingly, print and logging do NOT appear to make it into the scheduler logs.
For debugging purposes, I typically just raise as an exception the info I'm trying to log so it will appear in the scheduler logs.
Alternatively, you could move the callback to the TASK level. This means moving it into your default_args, like so:
args = {
    'owner': 'airflow',
    'start_date': airflow.utils.dates.days_ago(2),
    'on_success_callback': datadog_event_success
}

dag = DAG(
    dag_id='example_callback',
    default_args=args,
    schedule_interval='*/5 * * * *',
    dagrun_timeout=timedelta(minutes=60)
)

Your callback's logging will now appear in the task logs (not the scheduler logs). However, this means the callback will be called for every qualifying task, not just once for the DAG.